Z User commited on
Commit ·
edaa6b9
1
Parent(s): d3fbdad
phase7: v0.2.0 — add get_roots, get_xrefs, get_commentary, audit_hadith, extend compare_traditions (positions[]/data_flags/consensus_level), provenance block on every response, sources CLI; node:test suite (3 tests PASS); version bump
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- README.md+15
- dist/index.js+210-11
- node_modules/.bin/node-whichAdded+1
- node_modules/.bin/tscAdded+1
- node_modules/.bin/tsserverAdded+1
- node_modules/.package-lock.jsonAdded+1251
- node_modules/@hono/node-server/LICENSEAdded+21
- node_modules/@hono/node-server/README.mdAdded+450
- node_modules/@hono/node-server/dist/conninfo.cjsAdded+22
- node_modules/@hono/node-server/dist/conninfo.d.ctsAdded+11
- node_modules/@hono/node-server/dist/conninfo.d.mtsAdded+11
- node_modules/@hono/node-server/dist/conninfo.mjsAdded+20
- node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjsAdded+5
- node_modules/@hono/node-server/dist/constants-BXAKTxRC.cjsAdded+11
- node_modules/@hono/node-server/dist/early-hints.cjsAdded+35
- node_modules/@hono/node-server/dist/early-hints.d.ctsAdded+16
- node_modules/@hono/node-server/dist/early-hints.d.mtsAdded+16
- node_modules/@hono/node-server/dist/early-hints.mjsAdded+33
- node_modules/@hono/node-server/dist/index.cjsAdded+1386
- node_modules/@hono/node-server/dist/index.d.ctsAdded+101
- node_modules/@hono/node-server/dist/index.d.mtsAdded+101
- node_modules/@hono/node-server/dist/index.mjsAdded+1381
- node_modules/@hono/node-server/dist/serve-static.cjsAdded+153
- node_modules/@hono/node-server/dist/serve-static.d.ctsAdded+19
- node_modules/@hono/node-server/dist/serve-static.d.mtsAdded+19
- node_modules/@hono/node-server/dist/serve-static.mjsAdded+152
- node_modules/@hono/node-server/dist/utils/response.cjsAdded+8
- node_modules/@hono/node-server/dist/utils/response.d.ctsAdded+4
- node_modules/@hono/node-server/dist/utils/response.d.mtsAdded+4
- node_modules/@hono/node-server/dist/utils/response.mjsAdded+7
- node_modules/@hono/node-server/dist/utils/stream.cjsAdded+65
- node_modules/@hono/node-server/dist/utils/stream.d.ctsAdded+6
- node_modules/@hono/node-server/dist/utils/stream.d.mtsAdded+6
- node_modules/@hono/node-server/dist/utils/stream.mjsAdded+64
- node_modules/@hono/node-server/package.jsonAdded+128
- node_modules/@modelcontextprotocol/sdk/LICENSEAdded+21
- node_modules/@modelcontextprotocol/sdk/README.mdAdded+178
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.tsAdded+231
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts.mapAdded+1
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.jsAdded+320
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js.mapAdded+1
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.tsAdded+473
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts.mapAdded+1
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.jsAdded+1046
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js.mapAdded+1
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.tsAdded+591
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts.mapAdded+1
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.jsAdded+618
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js.mapAdded+1
- node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.d.tsAdded+169
21 unmodified lines22232421 unmodified linesnpx quran-md init # Download root quran.md manifestnpx quran-md 6:74 # Fetch canonical JSON for Surah 6, Ayah 74```21 unmodified lines22232425262728293031323334353637383921 unmodified linesnpx quran-md init # Download root quran.md manifestnpx quran-md 6:74 # Fetch canonical JSON for Surah 6, Ayah 74```## v0.2.0 — Phase 7 tools| Tool | What it returns | Grounding ||---|---|---|| `get_verse` | canonical verse record | provenance block on every response || `compare_traditions` | Sunni/Imami side-by-side + positions[] + data_flags | consensus_level per claim; verification states || `get_roots` | word-level morphology (form/lemma/root/POS) + lexical edges | corpus-verified (Quranic Arabic Corpus v0.4, sha256) || `get_xrefs` | cross-reference edges (lexical IDF-weighted; exegetical citation edges) | relations from closed set; `review_status` exposed — 'queue' = NOT human-approved || `get_commentary` | tafsir commentary units (verbatim quote_ar + sha256) | Imami note when units pending (Al-Mizan license-blocked) || `audit_hadith` | isnad/matn audits per criteria set (never one score) | ghayb rule + 'ard 'ala al-Quran shared test; `unresolved` is a valid result || `sources` (CLI) | license manifest per source | states: use / use_with_notice / exclude_until_resolved / exclude_entirely |Tests: `npm test` (node:test; needs `npm run build` first and `QURAN_MD_LOCAL_DIR` pointing at a data checkout for offline runs).
3 unmodified lines45678919 unmodified lines293031323334353615 unmodified lines52535455565758596061626312 unmodified lines767778798081824 unmodified lines8788899091929394959697989922 unmodified lines1221231241251261271281291301311321331341351361371383 unmodified linesimport { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";import * as fs from "node:fs";import * as path from "node:path";const HF_BASE_URL = process.env.QURAN_MD_BASE_URL ||"https://huggingface.co/datasets/bravesigma/quran-md-data/resolve/main";const LOCAL_DATA_DIR = process.env.QURAN_MD_LOCAL_DIR || "";19 unmodified linesconst text = await fetchDataFile(relPath);return JSON.parse(text);}async function startMcpServer() {const server = new Server({ name: "quran-md", version: "0.1.0" }, { capabilities: { tools: {} } });server.setRequestHandler(ListToolsRequestSchema, async () => ({tools: [{15 unmodified lines},{name: "compare_traditions",description: "Compare Sunni and Shia canonical perspectives alongside the Isnad (chain) and Matn (logic) audit for a verse.",inputSchema: {type: "object",properties: {surah: { type: "number", description: "Surah number (1-114)" },ayah: { type: "number", description: "Ayah number" },},required: ["surah", "ayah"],},12 unmodified linesconst ayah = Number(args?.ayah);const data = await getVerseJson(surah, ayah);return {content: [{ type: "text", text: JSON.stringify(data, null, 2) }],};}if (name === "compare_traditions") {4 unmodified linesverse: data.verse_key,arabic_text: data.arabic_text,roots: data.roots,sunni: data.sunni_perspectives,shia: data.shia_perspectives,isnad_matn_audit: data.isnad_matn_audit,};return {content: [{ type: "text", text: JSON.stringify(comparison, null, 2) },],};}22 unmodified linesconsole.log("Created quran.md in current directory.");return;}if (cmd && cmd.includes(":")) {const [s, a] = cmd.split(":").map(Number);const data = await getVerseJson(s, a);console.log(JSON.stringify(data, null, 2));return;}console.log(`quran-md v0.1.0Usage:npx quran-md mcp Start MCP server (for Claude, Cursor, Windsurf, etc.)npx quran-md init Download root quran.md manifest into current foldernpx quran-md <surah:ayah> Fetch canonical JSON for a verse (e.g. 6:74)`);}main().catch((err) => {console.error(err);3 unmodified lines4567891019 unmodified lines3031323334353637383940414243444546474849505152535415 unmodified lines70717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913012 unmodified lines1431441451461471481494 unmodified lines15415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228322 unmodified lines3063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373 unmodified linesimport { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";import * as fs from "node:fs";import * as path from "node:path";const VERSION = "0.2.0";const HF_BASE_URL = process.env.QURAN_MD_BASE_URL ||"https://huggingface.co/datasets/bravesigma/quran-md-data/resolve/main";const LOCAL_DATA_DIR = process.env.QURAN_MD_LOCAL_DIR || "";19 unmodified linesconst text = await fetchDataFile(relPath);return JSON.parse(text);}async function getJsonl(name) {const text = await fetchDataFile(`data/${name}`);return text.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));}// Every tool response carries provenance and consensus_level (Phase 7 rule).const PROVENANCE = {source_repo: "bravesigma/quran-md-data (HF datasets)",data_version: "schema v2.0.0",grounding_rule: "All quotes are verbatim substrings of stored source files with sha256 provenance; positions carry consensus_level; xref edges are review-queue items until human-approved.",consensus_level_note: "consensus_level values: agreed | majority | disputed | single_source (null = not yet established)",};function wrap(payload) {return { ...payload, _provenance: PROVENANCE };}async function startMcpServer() {const server = new Server({ name: "quran-md", version: VERSION }, { capabilities: { tools: {} } });server.setRequestHandler(ListToolsRequestSchema, async () => ({tools: [{15 unmodified lines},{name: "compare_traditions",description: "Compare Sunni and Shia canonical perspectives (tafsir, hadith, positions[]) alongside the Isnad/Matn audit for a verse. Response includes provenance and consensus_level.",inputSchema: {type: "object",properties: {surah: { type: "number", description: "Surah number (1-114)" },ayah: { type: "number", description: "Ayah number" },},required: ["surah", "ayah"],},},{name: "get_roots",description: "Word-level morphology (form, lemma, root, POS) for a verse from the Quranic Arabic Corpus, plus IDF-weighted lexical cross-reference edges. Every root/lemma claim is corpus-verified.",inputSchema: {type: "object",properties: {surah: { type: "number", description: "Surah number (1-114)" },ayah: { type: "number", description: "Ayah number" },},required: ["surah", "ayah"],},},{name: "get_xrefs",description: "Cross-reference edges for a verse (lexical shared root/lemma with IDF weighting; exegetical tafsir-citation edges; classifier relations). Items marked review_status='queue' are NOT human-approved — treat relations as candidate, never as established fact.",inputSchema: {type: "object",properties: {surah: { type: "number", description: "Surah number (1-114)" },ayah: { type: "number", description: "Ayah number" },limit: { type: "number", description: "Max edges returned (default 25)" },},required: ["surah", "ayah"],},},{name: "get_commentary",description: "Tafsir commentary units for a verse (optionally filtered by tradition: sunni|imami). quote_ar fields are verbatim substrings of stored source files with sha256; summary fields (if any) carry generated_by and are paraphrases.",inputSchema: {type: "object",properties: {ayah: { type: "string", description: "Verse key, e.g. '6:74'" },tradition: { type: "string", enum: ["sunni", "imami"], description: "Optional filter" },},required: ["ayah"],},},{name: "audit_hadith",description: "Isnad/Matn audit for hadith records linked to a verse: per-criteria-set checks (sunni_classical, imami_classical — never merged into one score), typed matn claims, ghayb rule applied, 'ard 'ala al-Quran as shared test. Unresolved is a valid result.",inputSchema: {type: "object",properties: {surah: { type: "number" },ayah: { type: "number" },},required: ["surah", "ayah"],},12 unmodified linesconst ayah = Number(args?.ayah);const data = await getVerseJson(surah, ayah);return {content: [{ type: "text", text: JSON.stringify(wrap(data), null, 2) }],};}if (name === "compare_traditions") {4 unmodified linesverse: data.verse_key,arabic_text: data.arabic_text,roots: data.roots,words_corpus_verified: (data.words || []).length,sunni: {...data.sunni_perspectives,consensus_level: data.sunni_perspectives?.consensus_level ?? null,},shia: {...data.shia_perspectives,consensus_level: data.shia_perspectives?.consensus_level ?? null,},positions: data.positions || [],isnad_matn_audit: data.isnad_matn_audit,data_flags: data.data_flags || [],};return {content: [{ type: "text", text: JSON.stringify(wrap(comparison), null, 2) },],};}if (name === "get_roots") {const surah = Number(args?.surah);const ayah = Number(args?.ayah);const vk = `${surah}:${ayah}`;const words = await getJsonl("words.jsonl");const mine = words.filter((w) => w.ref.startsWith(`${vk}:`));const allEdges = await getJsonl("xref_edges.jsonl");const lexical = allEdges.filter((e) => e.from === vk && e.source === "lexical");return {content: [{type: "text",text: JSON.stringify(wrap({verse: vk,word_count: mine.length,words: mine,roots_index: [...new Set(mine.map((w) => w.root).filter(Boolean))],lexical_edges: lexical.slice(0, 25),corpus_verified: true,}), null, 2),},],};}if (name === "get_xrefs") {const surah = Number(args?.surah);const ayah = Number(args?.ayah);const limit = Number(args?.limit) || 25;const vk = `${surah}:${ayah}`;const allEdges = await getJsonl("xref_edges.jsonl");const mine = allEdges.filter((e) => e.from === vk || e.to === vk);return {content: [{type: "text",text: JSON.stringify(wrap({verse: vk,total_edges: mine.length,edges: mine.slice(0, limit),warning: "Edges carry review_status; 'queue' = not human-approved. Classified relations are LLM-assigned from closed set, pending review.",}), null, 2),},],};}if (name === "get_commentary") {const ayahKey = String(args?.ayah || "");const tradition = args?.tradition;const units = await getJsonl("commentary_units.jsonl");let mine = units.filter((u) => u.span?.start === ayahKey || u.span?.end === ayahKey);if (tradition) {mine = mine.filter((u) => u.tradition === tradition);}const trimmed = mine.map((u) => ({id: u.id,work: u.work,author: u.author,tradition: u.tradition,span: u.span,span_roles: u.span_roles,section_type: u.section_type,quote_ar: u.quote_ar.slice(0, 1200),quote_verbatim: true,source_sha256: u.quote_location?.source_sha256,attribution_flags: u.attribution_flags,ayah_citations: u.ayah_citations,license: u.provenance?.license,}));return {content: [{type: "text",text: JSON.stringify(wrap({ayah: ayahKey,tradition_filter: tradition || null,units: trimmed,imami_note: mine.length > 0? undefined: "No Imami commentary units ingested yet: Al-Mizan is license-blocked (see sources/manifest.json), Majma' al-Bayan / Tafsir al-Qummi pending clean-source transcription. Imami positions for this verse are therefore sourced only from the legacy enrichment (flagged unverified_recall).",}), null, 2),},],};}if (name === "audit_hadith") {const surah = Number(args?.surah);const ayah = Number(args?.ayah);const vk = `${surah}:${ayah}`;const hadiths = await getJsonl("hadith.jsonl");const audits = await getJsonl("audits.jsonl");const narrators = await getJsonl("narrators.jsonl");const mine = hadiths.filter((h) => (h.linked_ayat || []).some((l) => l.ref === vk));const mineAudits = audits.filter((a) => mine.some((h) => h.id === a.target));return {content: [{type: "text",text: JSON.stringify(wrap({verse: vk,hadiths: mine,audits: mineAudits,narrators,discipline: "No numeric trust score. Each criteria set reports result+why independently; ghayb/eschatological claims are audited for transmission and internal coherence only; 'ard 'ala al-Quran is the stated shared test.",}), null, 2),},],};}22 unmodified linesconsole.log("Created quran.md in current directory.");return;}if (cmd === "sources") {const m = await fetchDataFile("sources/manifest.json");const parsed = JSON.parse(m);console.log(JSON.stringify({license_policy: parsed.policy,sources: parsed.sources.map((s) => ({id: s.id,license: s.license?.value,hf_redistribution: s.redistribution?.huggingface,state: s.proposed_state,})),}, null, 2));return;}if (cmd && cmd.includes(":")) {const [s, a] = cmd.split(":").map(Number);const data = await getVerseJson(s, a);console.log(JSON.stringify(wrap(data), null, 2));return;}console.log(`quran-md v${VERSION}Usage:npx quran-md mcp Start MCP server (for Claude, Cursor, Windsurf, etc.)npx quran-md init Download root quran.md manifest into current foldernpx quran-md sources Print the license manifest (per-source state)npx quran-md <surah:ayah> Fetch canonical JSON for a verse (e.g. 6:74)`);}main().catch((err) => {console.error(err);
1../which/bin/node-which1../typescript/bin/tsc1../typescript/bin/tsserver123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251{ "name": "quran-md", "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "node_modules/@hono/node-server": { "version": "2.1.11", "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.11.tgz", "integrity": "sha512-KzKz9vl4vvr1vgLHamj+g5uonbrj5NwAdO3yzOS6cd2HjALVeOgTgeZOyAzNxejbkfOOPIcvuf/Tg8l1pEFLog==", "license": "MIT", "engines": { "node": ">=20" }, "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.32.2", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.2.tgz", "integrity": "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==", "license": "MIT", "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "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.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "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.1" }, "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/@types/node": { "version": "20.19.43", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", "dev": true, "license": "MIT", "dependencies": { "undici-types": "~6.21.0" } }, "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.20.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", "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.4.0", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" }, "engines": { "node": ">=18" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "node_modules/body-parser/node_modules/content-type": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", "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/content-disposition": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", "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.3", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", "license": "MIT", "engines": { "node": ">= 0.8" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "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.2", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", "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.1.1", "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", "license": "MIT", "engines": { "node": ">=18.0.0" } }, "node_modules/express": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", "license": "MIT", "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.3.0", "content-disposition": "^2.0.1", "content-type": "^2.0.0", "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.8", "qs": "^6.16.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.1.0", "vary": "^1.1.2" }, "engines": { "node": ">= 18" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "node_modules/express-rate-limit": { "version": "8.7.5", "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.5.tgz", "integrity": "sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA==", "license": "MIT", "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "engines": { "node": ">= 16" }, "funding": { "url": "https://github.com/sponsors/express-rate-limit" }, "peerDependencies": { "express": ">= 4.11" } }, "node_modules/express/node_modules/content-type": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", "engines": { "node": ">=18" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "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.9", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "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.4", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "license": "MIT", "dependencies": { "function-bind": "^1.1.2" }, "engines": { "node": ">= 0.4" } }, "node_modules/hono": { "version": "4.13.22", "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.22.tgz", "integrity": "sha512-wncKd5/40Pj8grx0RZ2fgNIicFEmVFwIHT5UFLTnphR8I6AQWFf9c2JoM6ZJ9g8y4pMzg3sNlCVNe0m2Yclg0Q==", "license": "MIT", "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.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", "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/ip-address": { "version": "10.7.6", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", "license": "MIT", "engines": { "node": ">= 12" } }, "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.2.18", "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.18.tgz", "integrity": "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg==", "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.1", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", "license": "MIT", "engines": { "node": ">= 0.8" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "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.1.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", "license": "MIT", "dependencies": { "content-type": "^2.1.0" }, "engines": { "node": ">=18" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "node_modules/negotiator/node_modules/content-type": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", "engines": { "node": ">=18" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "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.14.0", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", "license": "MIT", "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/on-finished": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", "license": "MIT", "dependencies": { "ee-first": "1.1.1" }, "engines": { "node": ">= 0.8" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "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.4.2", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", "license": "MIT", "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "node_modules/pkce-challenge": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.2.tgz", "integrity": "sha512-vCc54+qyIfKC5e2UN28AZKElwqjLINgiIV3RKI8pDu93TjaAJoB3QrgMzEBouy8yOKsXVXdAinO1QArJf9x5WA==", "license": "MIT", "engines": { "node": ">=16.20.0" } }, "node_modules/proxy-addr": { "version": "2.0.8", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "license": "MIT", "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" }, "engines": { "node": ">= 0.10" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "node_modules/qs": { "version": "6.17.1", "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" }, "engines": { "node": ">=0.6" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/range-parser": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", "license": "MIT", "engines": { "node": ">= 0.6" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "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.3.0", "resolved": "https://registry.npmjs.org/router/-/router-2.3.0.tgz", "integrity": "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==", "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" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "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.1", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "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.1", "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" }, "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.1.0", "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", "license": "MIT", "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" }, "engines": { "node": ">= 18" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "node_modules/type-is/node_modules/content-type": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", "engines": { "node": ">=18" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { "node": ">=14.17" } }, "node_modules/undici-types": { "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "dev": true, "license": "MIT" }, "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/zod": { "version": "4.6.7", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" } }, "node_modules/zod-to-json-schema": { "version": "3.25.2", "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", "license": "ISC", "peerDependencies": { "zod": "^3.25.28 || ^4" } } }}123456789101112131415161718192021MIT License
Copyright (c) 2022 - present, Yusuke Wada and Hono contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450# 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.
## Benchmarks
Hono is 3.1 times faster than Express.
Express v5:
```txt$ bombardier -d 10s --fasthttp http://localhost:3000/
Statistics Avg Stdev Max Reqs/sec 24380.41 1409.74 26604.88 Latency 5.12ms 2.95ms 305.21ms HTTP codes: 1xx - 0, 2xx - 243915, 3xx - 0, 4xx - 0, 5xx - 0 others - 0 Throughput: 6.98MB/s```
Hono + `@hono/node-server`:
```txt$ bombardier -d 10s --fasthttp http://localhost:3000/
Statistics Avg Stdev Max Reqs/sec 74428.96 3815.27 88228.32 Latency 1.68ms 621.25us 106.20ms HTTP codes: 1xx - 0, 2xx - 744378, 3xx - 0, 4xx - 0, 5xx - 0 others - 0 Throughput: 16.82MB/s```
## Requirements
It works on Node.js versions greater than 20.x.
## Installation
You can install it from the npm registry:
```shnpm install @hono/node-serverpnpm 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.
```tsimport { 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})```
## WebSocket
You can upgrade WebSocket connections with `upgradeWebSocket` from `@hono/node-server`.To enable this, install `ws` (and `@types/ws`) in your project, then create and provide a `WebSocketServer` as shown in the example below.
```tsimport { serve, upgradeWebSocket } from '@hono/node-server'import { WebSocketServer } from 'ws'import { Hono } from 'hono'
const app = new Hono()
app.get( '/ws', upgradeWebSocket(() => ({ onMessage(event, ws) { ws.send(event.data) }, })))
const wss = new WebSocketServer({ noServer: true })serve({ fetch: app.fetch, websocket: { server: wss },})```
For example, run it using `ts-node`. Then an HTTP server will be launched. The default port is `3000`.
```shts-node ./index.ts```
Open `http://localhost:3000` with your browser.
## Options
### `port`
```tsserve({ fetch: app.fetch, port: 8787, // Port number, default is 3000})```
### `createServer`
```tsimport { 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`.
```tsserve({ 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`.
```tsserve({ fetch: app.fetch, autoCleanupIncoming: false,})```
### `websocket`
provide a websocket server to enable websocket support.
```tsimport { serve, upgradeWebSocket } from '@hono/node-server'import { WebSocketServer } from 'ws'
// ...const wss = new WebSocketServer({ noServer: true })
serve({ fetch: app.fetch, websocket: { server: wss },})```
## 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.
```tsimport { 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.
```tsimport { 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:
```tsapp.use('/static/*', serveStatic({ root: './static' }))```
Notice that `root` here is not relative to `src/index.ts`, rather to `my-hono-project`.
Only `GET` and `HEAD` requests are served. Requests with other methods are passed to the next middleware.
### Options
#### `allowPercentInPath`
By default, `serveStatic` skips request paths that still contain `%` after routing. This prevents a second decoding step from serving a file under a different path than the one checked by route middleware. Set `allowPercentInPath: true` to keep the previous behavior when serving files whose names contain percent signs.
If you restrict access to only some paths under `root` (for example, `/static/admin/*`), enabling this option may let requests bypass those restrictions. Apply access control to the same route pattern as `serveStatic` (for example, `/static/*`), before the static middleware:
```tsapp.use('/static/*', authMiddleware)app.use('/static/*', serveStatic({ root: './static', allowPercentInPath: true }))```
#### `rewriteRequestPath`
If you want to serve files in `./.foojs` with the request path `/__foo/*`, you can write like the following.
```tsapp.use( '/__foo/*', serveStatic({ root: './.foojs/', rewriteRequestPath: (path: string) => path.replace(/^\/__foo/, ''), }))```
#### `onFound`
You can specify handling when the requested file is found with `onFound`.
```tsapp.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.
```tsapp.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.
```tsapp.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`.
```tsimport { 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.
```tsimport { 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.
```tstype HttpBindings = { incoming: IncomingMessage outgoing: ServerResponse}
type Http2Bindings = { incoming: Http2ServerRequest outgoing: Http2ServerResponse}```
## Early Hints Middleware
You can send HTTP 103 Early Hints to instruct browsers to preload or preconnect resources before the final response is prepared. The middleware is supported under Node.js bindings (HTTP/1.1 and HTTP/2).
### Usage
Import `earlyHints` from `@hono/node-server/early-hints`:
#### Static links
```tsimport { serve } from '@hono/node-server'import { earlyHints } from '@hono/node-server/early-hints'import { Hono } from 'hono'
const app = new Hono()
app.use( earlyHints({ link: '</styles.css>; rel=preload; as=style', }))
app.get('/', (c) => { return c.html('<!DOCTYPE html><html><body><h1>Hello Hono!</h1></body></html>')})
serve(app)```
#### Dynamic links
```tsapp.use( earlyHints({ link: (c) => c.req.query('theme') === 'dark' ? '</dark.css>; rel=preload; as=style' : '</light.css>; rel=preload; as=style', }))```
> [!NOTE]> Early Hints are sent only for requests that look like document navigations. If `Sec-Fetch-Mode` or `Sec-Fetch-Dest` is present with a value other than `navigate` or `document`, for example a `fetch()` or XHR call from a browser, a subresource request, or an iframe navigation, the middleware skips the hints and continues to the handler. Requests without these headers, such as `curl` or `fetch()` from a JavaScript runtime, are treated as navigations and do receive Early Hints.
## 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.
```tsimport { 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.
```tsimport { 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 - <https://hono.dev>- Hono GitHub repository - <https://github.com/honojs/hono>
## Authors
- Yusuke Wada <https://github.com/yusukebe>- Taku Amano <https://github.com/usualoma>
## License
MIT12345678910111213141516171819202122Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
//#region src/conninfo.ts/*** ConnInfo Helper for Node.js* @param c Context* @returns ConnInfo*/const 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 } };};
//#endregionexports.getConnInfo = getConnInfo;1234567891011import { GetConnInfo } from "hono/conninfo";
//#region src/conninfo.d.ts/** * ConnInfo Helper for Node.js * @param c Context * @returns ConnInfo */declare const getConnInfo: GetConnInfo;//#endregionexport { getConnInfo };1234567891011import { GetConnInfo } from "hono/conninfo";
//#region src/conninfo.d.ts/** * ConnInfo Helper for Node.js * @param c Context * @returns ConnInfo */declare const getConnInfo: GetConnInfo;//#endregionexport { getConnInfo };1234567891011121314151617181920//#region src/conninfo.ts/*** ConnInfo Helper for Node.js* @param c Context* @returns ConnInfo*/const 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 } };};
//#endregionexport { getConnInfo };12345//#region src/utils/response/constants.tsconst X_ALREADY_SENT = "x-hono-already-sent";
//#endregionexport { X_ALREADY_SENT as t };1234567891011
//#region src/utils/response/constants.tsconst X_ALREADY_SENT = "x-hono-already-sent";
//#endregionObject.defineProperty(exports, 'X_ALREADY_SENT', { enumerable: true, get: function () { return X_ALREADY_SENT; }});1234567891011121314151617181920212223242526272829303132333435Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
//#region src/early-hints.ts/*** Early Hints middleware for Node.js* Automatically sends a 103 Early Hints informational response with the specified Link header(s).** @param options EarlyHintsOptions* @returns MiddlewareHandler*/const earlyHints = (options) => { let warned = false; return async (c, next) => { const mode = c.req.header("Sec-Fetch-Mode"); const dest = c.req.header("Sec-Fetch-Dest"); if (mode && mode !== "navigate" || dest && dest !== "document") return next(); const env = c.env || {}; const outgoing = ("server" in env ? env.server : env)?.outgoing; if (typeof outgoing?.writeEarlyHints !== "function") { if (!warned) { console.warn("Early Hints Middleware is not supported because writeEarlyHints is not defined."); warned = true; } return await next(); } if (!outgoing.headersSent) { const link = typeof options.link === "function" ? options.link(c) : options.link; if (link !== void 0 && (Array.isArray(link) ? link.length > 0 : Boolean(link))) outgoing.writeEarlyHints({ link }); } await next(); };};
//#endregionexports.earlyHints = earlyHints;12345678910111213141516import { Context, Env, MiddlewareHandler } from "hono";
//#region src/early-hints.d.tstype EarlyHintsOptions<E extends Env = Env> = { link: string | string[] | ((c: Context<E>) => string | string[] | undefined);};/** * Early Hints middleware for Node.js * Automatically sends a 103 Early Hints informational response with the specified Link header(s). * * @param options EarlyHintsOptions * @returns MiddlewareHandler */declare const earlyHints: <E extends Env = any>(options: EarlyHintsOptions<E>) => MiddlewareHandler<E>;//#endregionexport { EarlyHintsOptions, earlyHints };12345678910111213141516import { Context, Env, MiddlewareHandler } from "hono";
//#region src/early-hints.d.tstype EarlyHintsOptions<E extends Env = Env> = { link: string | string[] | ((c: Context<E>) => string | string[] | undefined);};/** * Early Hints middleware for Node.js * Automatically sends a 103 Early Hints informational response with the specified Link header(s). * * @param options EarlyHintsOptions * @returns MiddlewareHandler */declare const earlyHints: <E extends Env = any>(options: EarlyHintsOptions<E>) => MiddlewareHandler<E>;//#endregionexport { EarlyHintsOptions, earlyHints };123456789101112131415161718192021222324252627282930313233//#region src/early-hints.ts/*** Early Hints middleware for Node.js* Automatically sends a 103 Early Hints informational response with the specified Link header(s).** @param options EarlyHintsOptions* @returns MiddlewareHandler*/const earlyHints = (options) => { let warned = false; return async (c, next) => { const mode = c.req.header("Sec-Fetch-Mode"); const dest = c.req.header("Sec-Fetch-Dest"); if (mode && mode !== "navigate" || dest && dest !== "document") return next(); const env = c.env || {}; const outgoing = ("server" in env ? env.server : env)?.outgoing; if (typeof outgoing?.writeEarlyHints !== "function") { if (!warned) { console.warn("Early Hints Middleware is not supported because writeEarlyHints is not defined."); warned = true; } return await next(); } if (!outgoing.headersSent) { const link = typeof options.link === "function" ? options.link(c) : options.link; if (link !== void 0 && (Array.isArray(link) ? link.length > 0 : Boolean(link))) outgoing.writeEarlyHints({ link }); } await next(); };};
//#endregionexport { earlyHints };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });const require_constants = require('./constants-BXAKTxRC.cjs');let node_http = require("node:http");let node_http2 = require("node:http2");let node_stream = require("node:stream");let hono_ws = require("hono/ws");
//#region src/error.tsvar RequestError = class extends Error { constructor(message, options) { super(message, options); this.name = "RequestError"; }};
//#endregion//#region src/headers.tsconst nonJoinedHeaders = new Set([ "age", "authorization", "content-length", "content-type", "etag", "expires", "from", "host", "if-modified-since", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "referer", "retry-after", "server", "user-agent"]);const validHeaderName = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;const isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;const normalizeHeaderValue = (value) => { if (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value; let start = 0; let end = value.length; while (start < end && isHttpWhitespace(value.charCodeAt(start))) start++; while (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--; return value.slice(start, end);};const forbiddenHeaderValue = /[\0\r\n]/;const GlobalHeaders = globalThis.Headers;const materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => { const headers = new HeadersCtor(); for (let i = 0; i < rawHeaders.length; i += 2) { const name = rawHeaders[i]; if (!name.startsWith(":")) headers.append(name, rawHeaders[i + 1]); } return headers;};var RequestHeaders = class { #incoming; #rawHeaders; #headers; #invalidValue; constructor(incoming) { this.#incoming = incoming; if (incoming instanceof node_http2.Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice(); } get #lazyRawHeaders() { return this.#rawHeaders ??= this.#incoming.rawHeaders.slice(); } get #native() { if (!this.#headers) { this.#headers = materializeHeaders(this.#lazyRawHeaders); this.#rawHeaders = void 0; } return this.#headers; } #normalizedName(name) { if (typeof name !== "string") return; if (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`); return name.toLowerCase(); } #lookupHttp1(lowerName) { const headers = this.#incoming instanceof node_http2.Http2ServerRequest ? void 0 : this.#incoming.headers; if (!headers || nonJoinedHeaders.has(lowerName) || lowerName === "set-cookie" || lowerName === "__proto__") return; if (!Object.hasOwn(headers, lowerName)) return null; const rawValue = headers[lowerName]; if (typeof rawValue === "string") { const value = normalizeHeaderValue(rawValue); return forbiddenHeaderValue.test(value) ? void 0 : value; } } #lookup(rawHeaders, lowerName) { const separator = lowerName === "cookie" ? "; " : ", "; let value = null; for (let i = 0; i < rawHeaders.length; i += 2) { const rawName = rawHeaders[i]; if (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) { const rawValue = normalizeHeaderValue(rawHeaders[i + 1]); if (forbiddenHeaderValue.test(rawValue)) { this.#invalidValue = true; return; } value = value === null ? rawValue : value + separator + rawValue; } } return value; } append(name, value) { this.#native.append(name, value); } delete(name) { this.#native.delete(name); } get(name) { const lowerName = this.#normalizedName(name); if (lowerName && !this.#headers && !this.#invalidValue) { const http1Value = this.#lookupHttp1(lowerName); if (http1Value !== void 0) return http1Value; const value = this.#lookup(this.#lazyRawHeaders, lowerName); if (value !== void 0) return value; } return this.#native.get(name); } has(name) { const lowerName = this.#normalizedName(name); if (lowerName && !this.#headers && !this.#invalidValue) { const http1Value = this.#lookupHttp1(lowerName); if (http1Value !== void 0) return http1Value !== null; const value = this.#lookup(this.#lazyRawHeaders, lowerName); if (value !== void 0) return value !== null; } return this.#native.has(name); } set(name, value) { this.#native.set(name, value); } getSetCookie() { return this.#native.getSetCookie(); } keys() { return this.#native.keys(); } values() { return this.#native.values(); } entries() { return this.#native.entries(); } forEach(callback, thisArg) { this.#native.forEach((value, key) => { callback.call(thisArg, value, key, this); }); } [Symbol.iterator]() { return this.entries(); }};Object.defineProperty(RequestHeaders.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) { return `Headers (lightweight) ${inspectFn(Object.fromEntries(this), { ...options, depth: depth == null ? null : depth - 1 })}`;} });Object.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);
//#endregion//#region src/url.tsconst reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;const reDotSegment = /\/\.\.?(?:[/?#]|$)/;const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;const validateRequestTarget = (target) => { const backslash = target.indexOf("\\"); if (backslash !== -1) { const query = target.indexOf("?"); if (query === -1 || backslash < query) throw new RequestError("Backslash in request path"); }};const buildUrl = (scheme, host, incomingUrl) => { const url = `${scheme}://${host}${incomingUrl}`; if (!reValidHost.test(host)) { validateRequestTarget(incomingUrl); const urlObj = new URL(url); if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header"); return urlObj.href; } else if (incomingUrl.length === 0) return url + "/"; else { if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL"); if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) { validateRequestTarget(incomingUrl); return new URL(url).href; } return url; }};
//#endregion//#region src/request.tsconst toRequestError = (e) => { if (e instanceof RequestError) return e; return new RequestError(e.message, { cause: e });};const GlobalRequest = global.Request;var Request$1 = class Request$1 extends GlobalRequest { static [Symbol.hasInstance](instance) { if (this === Request$1) return instance instanceof GlobalRequest || Function.prototype[Symbol.hasInstance].call(this, instance); return Function.prototype[Symbol.hasInstance].call(this, instance); } constructor(input, options) { if (typeof input === "object" && getRequestCache in input) { const hasReplacementBody = options !== void 0 && "body" in options && options.body != null; if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used."); input = input[getRequestCache](); } if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half"; super(input, options); }};const wrapBodyStream = Symbol("wrapBodyStream");const byteExactEncodings = new Set([ "latin1", "binary", "hex", "base64", "base64url"]);const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof node_http2.Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);const recordBodyBufferedBeforeDisconnect = (incoming) => { if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return; const incomingWithRecovery = incoming; incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;};const readBodyBufferedBeforeDisconnect = (incoming, chunks) => { if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return; const incomingWithRecovery = incoming; if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey]; let result; const errored = incoming.errored; if (errored && errored.code !== "ECONNRESET") result = errored; else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError(); else { const bodyChunks = chunks ?? []; let chunk; while ((chunk = incoming.read()) !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding)); const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks); result = buffer; const contentLength = incoming.headers["content-length"]; if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) { const expectedLength = Number(contentLength); if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError(); } } incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result; return result;};const enqueueBufferedBody = (controller, buffered) => { if (buffered instanceof Error) { controller.error(buffered); return; } if (buffered.length > 0) controller.enqueue(buffered); controller.close();};const newRequestFromIncoming = (method, url, headers, incoming, abortController) => { const init = { method, headers, signal: abortController.signal }; if (method === "TRACE") { init.method = "GET"; const req = new Request$1(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 { if (!reader) { const buffered = readBodyBufferedBeforeDisconnect(incoming); if (buffered !== void 0) { enqueueBufferedBody(controller, buffered); return; } } reader ||= 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 { const buffered = readBodyBufferedBeforeDisconnect(incoming); if (buffered !== void 0) init.body = new ReadableStream({ start(controller) { enqueueBufferedBody(controller, buffered); } }); else init.body = node_stream.Readable.toWeb(incoming); } return new Request$1(url, init);};const getRequestCache = Symbol("getRequestCache");const requestCache = Symbol("requestCache");const incomingKey = Symbol("incomingKey");const urlKey = Symbol("urlKey");const methodKey = Symbol("methodKey");const headersKey = Symbol("headersKey");const abortControllerKey = Symbol("abortControllerKey");const getAbortController = Symbol("getAbortController");const abortRequest = Symbol("abortRequest");const bodyBufferKey = Symbol("bodyBuffer");const bodyReadPromiseKey = Symbol("bodyReadPromise");const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");const bodyLockReaderKey = Symbol("bodyLockReader");const abortReasonKey = Symbol("abortReason");const newBodyUnusableError = () => { return /* @__PURE__ */ new TypeError("Body is unusable");};const rejectBodyUnusable = () => { return Promise.reject(newBodyUnusableError());};const textDecoder = new TextDecoder();const consumeBodyDirectOnce = (request) => { if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable(); request[bodyConsumedDirectlyKey] = true;};const toArrayBuffer = (buf) => { return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);};const contentType = (request) => { return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";};const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;const normalizeIncomingMethod = (method) => { if (typeof method !== "string" || method.length === 0) return "GET"; switch (method) { case "DELETE": case "GET": case "HEAD": case "OPTIONS": case "PATCH": case "POST": case "PUT": case "QUERY": return method; } const upper = method.toUpperCase(); switch (upper) { case "DELETE": case "GET": case "HEAD": case "OPTIONS": case "POST": case "PUT": return upper; default: return method; }};const validateDirectReadMethod = (method) => { if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`); const normalized = method.toUpperCase(); if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);};const readBodyWithFastPath = (request, method, fromBuffer) => { if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable(); const methodName = request.method; if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method](); const methodValidationError = validateDirectReadMethod(methodName); if (methodValidationError) return Promise.reject(methodValidationError); if (request[requestCache]) { if (methodName !== "TRACE") return request[requestCache][method](); } const alreadyUsedError = consumeBodyDirectOnce(request); if (alreadyUsedError) return alreadyUsedError; const raw = readRawBodyIfAvailable(request); if (raw) { const result = Promise.resolve(fromBuffer(raw, request)); request[bodyBufferKey] = void 0; return result; } return readBodyDirect(request).then((buf) => { const result = fromBuffer(buf, request); request[bodyBufferKey] = void 0; return result; });};const readRawBodyIfAvailable = (request) => { const incoming = request[incomingKey]; if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;};const normalizeAbortError = (request, incoming) => { if (incoming.errored) return incoming.errored; const reason = request[abortReasonKey]; if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason)); return /* @__PURE__ */ new Error("Client connection prematurely closed.");};const readBodyDirect = (request) => { if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]); if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey]; const incoming = request[incomingKey]; if (incoming.readableDidRead) return rejectBodyUnusable(); const buffered = readBodyBufferedBeforeDisconnect(incoming); if (buffered !== void 0) { if (buffered instanceof Error) return Promise.reject(buffered); request[bodyBufferKey] = buffered; return Promise.resolve(buffered); } const promise = new Promise((resolve, reject) => { const chunks = []; let settled = false; const finish = (callback) => { if (settled) return; settled = true; cleanup(); callback(); }; const recoverCompleteBodyAfterDisconnect = (error) => { const streamError = incoming.errored ?? error; if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false; finish(() => { const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks); if (recovered instanceof Error) reject(recovered); else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming)); else { request[bodyBufferKey] = recovered; resolve(recovered); } }); return true; }; const onData = (chunk) => { chunks.push(toBufferChunk(chunk, incoming.readableEncoding)); }; const onEnd = () => { finish(() => { const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks); request[bodyBufferKey] = buffer; resolve(buffer); }); }; const onError = (error) => { if (recoverCompleteBodyAfterDisconnect(error)) return; finish(() => { reject(error); }); }; const onClose = () => { if (incoming.readableEnded) { onEnd(); return; } if (recoverCompleteBodyAfterDisconnect()) return; finish(() => { reject(normalizeAbortError(request, incoming)); }); }; const cleanup = () => { incoming.off("data", onData); incoming.off("end", onEnd); incoming.off("error", onError); incoming.off("close", onClose); request[bodyReadPromiseKey] = void 0; }; incoming.on("data", onData); incoming.on("end", onEnd); incoming.on("error", onError); incoming.on("close", onClose); queueMicrotask(() => { if (settled) return; if (incoming.readableEnded) onEnd(); else if (incoming.errored) onError(incoming.errored); else if (incoming.destroyed) onClose(); }); }); request[bodyReadPromiseKey] = promise; return promise;};const requestPrototype = { get method() { return this[methodKey]; }, get url() { return this[urlKey]; }, get headers() { return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); }, [abortRequest](reason) { if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason; const abortController = this[abortControllerKey]; if (abortController && !abortController.signal.aborted) abortController.abort(reason); }, [getAbortController]() { this[abortControllerKey] ||= new AbortController(); if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]); return this[abortControllerKey]; }, [getRequestCache]() { const abortController = this[getAbortController](); if (this[requestCache]) return this[requestCache]; const method = this.method; if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) { this[bodyBufferKey] = void 0; const init = { method: method === "TRACE" ? "GET" : method, headers: this.headers, signal: abortController.signal }; if (method !== "TRACE") { init.body = new ReadableStream({ start(c) { c.close(); } }); init.duplex = "half"; } const req = new Request$1(this[urlKey], init); if (method === "TRACE") Object.defineProperty(req, "method", { get() { return "TRACE"; } }); return this[requestCache] = req; } return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController); }, get body() { if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body; const request = this[getRequestCache](); if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader(); return request.body; }, get bodyUsed() { if (this[bodyConsumedDirectlyKey]) return true; if (this[requestCache]) return this[requestCache].bodyUsed; return false; }};Object.defineProperty(requestPrototype, "signal", { get() { return this[getAbortController]().signal;} });[ "cache", "credentials", "destination", "duplex", "integrity", "mode", "redirect", "referrer", "referrerPolicy", "keepalive"].forEach((k) => { Object.defineProperty(requestPrototype, k, { get() { return this[getRequestCache]()[k]; } });});["clone", "formData"].forEach((k) => { Object.defineProperty(requestPrototype, k, { value: function() { if (this[bodyConsumedDirectlyKey]) { if (k === "clone") throw newBodyUnusableError(); return rejectBodyUnusable(); } return this[getRequestCache]()[k](); } });});Object.defineProperty(requestPrototype, "text", { value: function() { return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));} });Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() { return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));} });Object.defineProperty(requestPrototype, "blob", { value: function() { return readBodyWithFastPath(this, "blob", (buf, request) => { const type = contentType(request); const init = type ? { headers: { "content-type": type } } : void 0; return new Response(buf, init).blob(); });} });Object.defineProperty(requestPrototype, "bytes", { value: function() { return this.arrayBuffer().then((buf) => new Uint8Array(buf));} });Object.defineProperty(requestPrototype, "json", { value: function() { if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable(); return this.text().then(JSON.parse);} });Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) { return `Request (lightweight) ${inspectFn({ method: this.method, url: this.url, headers: this.headers, nativeRequest: this[requestCache] }, { ...options, depth: depth == null ? null : depth - 1 })}`;} });Object.setPrototypeOf(requestPrototype, Request$1.prototype);const newRequest = (incoming, defaultHostname) => { const req = Object.create(requestPrototype); req[incomingKey] = incoming; req[methodKey] = normalizeIncomingMethod(incoming.method); const incomingUrl = incoming.url || ""; if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { if (incoming instanceof node_http2.Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); try { validateRequestTarget(incomingUrl); req[urlKey] = new URL(incomingUrl).href; } catch (e) { throw new RequestError("Invalid absolute URL", { cause: e }); } return req; } const host = (incoming instanceof node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; if (!host) throw new RequestError("Missing host header"); let scheme; if (incoming instanceof 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"; try { req[urlKey] = buildUrl(scheme, host, incomingUrl); } catch (e) { if (e instanceof RequestError) throw e; else throw new RequestError("Invalid URL", { cause: e }); } return req;};
//#endregion//#region src/response.tsconst defaultContentType = "text/plain; charset=UTF-8";const responseCache = Symbol("responseCache");const getResponseCache = Symbol("getResponseCache");const cacheKey = Symbol("cache");const GlobalResponse = global.Response;var Response$1 = class Response$1 { #body; #init; static [Symbol.hasInstance](instance) { if (this === Response$1) return instance instanceof GlobalResponse || Function.prototype[Symbol.hasInstance].call(this, instance); return Function.prototype[Symbol.hasInstance].call(this, instance); } [getResponseCache]() { const cache = this[cacheKey]; const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0; delete this[cacheKey]; return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? { status: this.#init?.status, statusText: this.#init?.statusText, headers: liveHeaders } : this.#init); } constructor(body, init) { let headers; this.#body = body; if (init instanceof GlobalResponse) { const cachedGlobalResponse = init[responseCache]; if (cachedGlobalResponse) { this.#init = cachedGlobalResponse; this[getResponseCache](); return; } this.#init = #init in init ? init.#init : init; headers = new Headers(init.headers); } else this.#init = init; if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [ init?.status || 200, body ?? null, headers || init?.headers ]; } get headers() { const cache = this[cacheKey]; if (cache) { if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType })); 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$1.prototype, k, { get() { return this[getResponseCache]()[k]; } });});[ "arrayBuffer", "blob", "bytes", "clone", "formData", "json", "text"].forEach((k) => { Object.defineProperty(Response$1.prototype, k, { value: function() { return this[getResponseCache]()[k](); } });});Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) { return `Response (lightweight) ${inspectFn({ status: this.status, headers: this.headers, ok: this.ok, nativeResponse: this[responseCache] }, { ...options, depth: depth == null ? null : depth - 1 })}`;} });Object.setPrototypeOf(Response$1, GlobalResponse);Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;const parseRedirectUrl = (url) => { if (url instanceof URL) return url.href; if (validRedirectUrl.test(url)) return url; return new URL(url).href;};const validRedirectStatuses = new Set([ 301, 302, 303, 307, 308]);Object.defineProperty(Response$1, "redirect", { value: function redirect(url, status = 302) { if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code"); return new Response$1(null, { status, headers: { location: parseRedirectUrl(url) } }); }, writable: true, configurable: true});Object.defineProperty(Response$1, "json", { value: function json(data, init) { const body = JSON.stringify(data); if (body === void 0) throw new TypeError("The data is not JSON serializable"); const initHeaders = init?.headers; let headers; if (initHeaders) { headers = new Headers(initHeaders); if (!headers.has("content-type")) headers.set("content-type", "application/json"); } else headers = { "content-type": "application/json" }; return new Response$1(body, { status: init?.status ?? 200, statusText: init?.statusText, headers }); }, writable: true, configurable: true});
//#endregion//#region src/utils.tsasync 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(() => {}); }; const stream = writable.stream; if (writable.destroyed || stream?.closed || stream?.destroyed) { cancel(); return reader.closed; } 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 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) { stream.cancel().catch(() => {}); return; } return writeFromReadableStreamDefaultReader(stream.getReader(), writable);}const buildOutgoingHttpHeaders = (headers, defaultContentType) => { const res = {}; if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0); if (headers.has("set-cookie")) { 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; } else for (const [k, v] of headers) res[k] = v; if (defaultContentType) res["content-type"] ??= defaultContentType; return res;};
//#endregion//#region src/listener.tsconst outgoingEnded = Symbol("outgoingEnded");const incomingDraining = Symbol("incomingDraining");const DRAIN_TIMEOUT_MS = 500;const MAX_DRAIN_BYTES = 64 * 1024 * 1024;const drainIncoming = (incoming) => { const incomingWithDrainState = incoming; if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return; incomingWithDrainState[incomingDraining] = true; if (incoming instanceof node_http2.Http2ServerRequest) { try { incoming.stream?.close?.(node_http2.constants.NGHTTP2_NO_ERROR); } catch {} return; } let bytesRead = 0; const cleanup = () => { clearTimeout(timer); incoming.off("data", onData); incoming.off("end", cleanup); incoming.off("error", cleanup); }; const forceClose = () => { cleanup(); const socket = incoming.socket; if (socket && !socket.destroyed) { if (typeof socket.destroySoon === "function") socket.destroySoon(); else if (typeof socket.destroy === "function") socket.destroy(); } }; const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS); timer.unref?.(); const onData = (chunk) => { bytesRead += chunk.length; if (bytesRead > MAX_DRAIN_BYTES) forceClose(); }; incoming.on("data", onData); incoming.on("end", cleanup); incoming.on("error", cleanup); incoming.resume();};const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => { if (incoming.errored) { recordBodyBufferedBeforeDisconnect(incoming); req[abortRequest](incoming.errored.toString()); } else if (!outgoing.writableFinished || incoming instanceof node_http2.Http2ServerRequest && incoming.aborted) { recordBodyBufferedBeforeDisconnect(incoming); req[abortRequest]("Client connection prematurely closed."); } if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => { if (!incoming.readableEnded) setTimeout(() => { drainIncoming(incoming); }); });};const isImmediateCacheableResponse = (res) => { if (!(cacheKey in res)) return false; const body = res[cacheKey][1]; return body === null || typeof body === "string" || body instanceof Uint8Array;};const handleRequestError = () => new Response(null, { status: 400 });const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });const 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) { if (outgoing instanceof node_http.ServerResponse) outgoing._contentLength = null; outgoing.writeHead(500, { "Content-Type": "text/plain" }); } outgoing.end(`Error: ${err.message}`); outgoing.destroy(err); }};const flushHeaders = (outgoing) => { if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();};const trySetContentLength = (outgoing, status, length) => { const http1 = outgoing; if (http1._contentLength === null && http1._hasBody && http1.useChunkedEncodingByDefault && !http1._removedContLen && status >= 200 && status !== 204 && status !== 304 && !outgoing.hasHeader("content-length") && !outgoing.hasHeader("transfer-encoding") && !outgoing.hasHeader("trailer")) { http1._contentLength = length; return true; } return false;};const writeDefaultHeaders = (outgoing, status, length) => { if (trySetContentLength(outgoing, status, length)) outgoing.writeHead(status, { "Content-Type": defaultContentType }); else outgoing.writeHead(status, { "Content-Type": defaultContentType, "Content-Length": length });};const responseViaCache = async (res, outgoing) => { let [status, body, header] = res[cacheKey]; if (!header) { if (body === null) { outgoing.writeHead(status); outgoing.end(); } else if (typeof body === "string") { writeDefaultHeaders(outgoing, status, Buffer.byteLength(body)); outgoing.end(body); } else if (body instanceof Uint8Array) { writeDefaultHeaders(outgoing, status, body.byteLength); outgoing.end(body); } else if (body instanceof Blob) { writeDefaultHeaders(outgoing, status, body.size); outgoing.end(new Uint8Array(await body.arrayBuffer())); } else { outgoing.writeHead(status, { "Content-Type": defaultContentType }); flushHeaders(outgoing); await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing)); } outgoing[outgoingEnded]?.(); return; } let hasContentLength = false; let plainHeaders = false; let canAutoLength = true; if (header instanceof Headers) { hasContentLength = header.has("content-length"); header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType); } else if (Array.isArray(header)) { const headerObj = new Headers(header); hasContentLength = headerObj.has("content-length"); header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType); } else { plainHeaders = true; for (const key in header) { if (key.length === 14 && key.toLowerCase() === "content-length") { hasContentLength = true; break; } if (key.length === 17 && key.toLowerCase() === "transfer-encoding" || key.length === 7 && key.toLowerCase() === "trailer") canAutoLength = false; } } if (!hasContentLength) { let length; if (typeof body === "string") length = Buffer.byteLength(body); else if (body instanceof Uint8Array) length = body.byteLength; else if (body instanceof Blob) length = body.size; if (length !== void 0 && (!plainHeaders || !canAutoLength || !trySetContentLength(outgoing, status, length))) { if (plainHeaders) header = { ...header }; header["Content-Length"] = length; } } outgoing.writeHead(status, header); if (body == null) outgoing.end(); else 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]?.();};const isPromise = (res) => typeof res.then === "function";const 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, res.body === null ? void 0 : defaultContentType); 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); 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[require_constants.X_ALREADY_SENT]) {} else { outgoing.writeHead(res.status, resHeaderRecord); outgoing.end(); } outgoing[outgoingEnded]?.();};const getRequestListener = (fetchCallback, options = {}) => { const autoCleanupIncoming = options.autoCleanupIncoming ?? true; if (options.overrideGlobalObjects !== false && global.Request !== Request$1) { Object.defineProperty(global, "Request", { value: Request$1 }); Object.defineProperty(global, "Response", { value: Response$1 }); } return async (incoming, outgoing) => { let res, req; let needsBodyCleanup = false; let closeHandlerAttached = false; const ensureCloseHandler = () => { if (!req || closeHandlerAttached) return; closeHandlerAttached = true; outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup)); }; try { req = newRequest(incoming, options.hostname); needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD"); if (needsBodyCleanup) { incoming[wrapBodyStream] = true; if (incoming instanceof node_http2.Http2ServerRequest) outgoing[outgoingEnded] = () => { if (!incoming.readableEnded) setTimeout(() => { if (!incoming.readableEnded) setTimeout(() => { incoming.destroy(); outgoing.destroy(); }); }); }; } res = fetchCallback(req, { incoming, outgoing }); if (!isPromise(res) && isImmediateCacheableResponse(res)) { if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => { if (!incoming.readableEnded) drainIncoming(incoming); }); return responseViaCache(res, outgoing); } ensureCloseHandler(); } catch (e) { if (!res) if (options.errorHandler) { ensureCloseHandler(); 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); } };};
//#endregion//#region src/websocket.ts/*** @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent*/const CloseEvent = globalThis.CloseEvent ?? class extends Event { #eventInitDict; constructor(type, eventInitDict = {}) { super(type, eventInitDict); this.#eventInitDict = eventInitDict; } get wasClean() { return this.#eventInitDict.wasClean ?? false; } get code() { return this.#eventInitDict.code ?? 0; } get reason() { return this.#eventInitDict.reason ?? ""; }};/*** Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.* @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent*/const ErrorEvent = globalThis.ErrorEvent ?? class extends Event { #eventInitDict; constructor(type, eventInitDict = {}) { super(type, eventInitDict); this.#eventInitDict = eventInitDict; } get message() { return this.#eventInitDict.message ?? ""; } get filename() { return this.#eventInitDict.filename ?? ""; } get lineno() { return this.#eventInitDict.lineno ?? 0; } get colno() { return this.#eventInitDict.colno ?? 0; } get error() { return this.#eventInitDict.error ?? null; }};const generateConnectionSymbol = () => Symbol("connection");const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");const responseHeadersToSkip = new Set([ "connection", "content-length", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "sec-websocket-accept", "sec-websocket-extensions", "sec-websocket-protocol"]);const appendResponseHeaders = (headers, responseHeaders) => { if (!responseHeaders) return; responseHeaders.forEach((value, key) => { if (responseHeadersToSkip.has(key.toLowerCase())) return; headers.push(`${key}: ${value}`); });};const rejectUpgradeRequest = (socket, status, responseHeaders) => { if (socket.destroyed) return; const responseLines = ["Connection: close", "Content-Length: 0"]; appendResponseHeaders(responseLines, responseHeaders); socket.end(`HTTP/1.1 ${status.toString()} ${node_http.STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r`);};const createUpgradeRequest = (request) => { const protocol = request.socket.encrypted ? "https" : "http"; const incomingUrl = request.url ?? "/"; let url; if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { validateRequestTarget(incomingUrl); url = new URL(incomingUrl).href; } else url = buildUrl(protocol, request.headers.host ?? "localhost", incomingUrl); const headers = new Headers(); for (const key in request.headers) { const value = request.headers[key]; if (!value) continue; headers.append(key, Array.isArray(value) ? value[0] : value); } return new Request(url, { headers });};const setupWebSocket = (options) => { const { server, fetchCallback, wss } = options; const waiterMap = /* @__PURE__ */ new Map(); wss.on("connection", (ws, request) => { const waiter = waiterMap.get(request); if (waiter) { waiter.resolve(ws); waiterMap.delete(request); } }); const rejectWaiter = (request) => { const waiter = waiterMap.get(request); if (waiter) { waiterMap.delete(request); waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted")); } }; const waitForWebSocket = (request, connectionSymbol) => { return new Promise((resolve, reject) => { waiterMap.set(request, { resolve, reject, connectionSymbol }); }); }; server.on("upgrade", async (request, socket, head) => { const ignoreSocketError = () => {}; socket.on("error", ignoreSocketError); if (request.headers.upgrade?.toLowerCase() !== "websocket") { if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 400); return; } const reclaimWaiterOnClose = () => rejectWaiter(request); socket.once("close", reclaimWaiterOnClose); const env = { incoming: request, outgoing: void 0, wss, [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket }; let status = 400; let responseHeaders; try { const response = await fetchCallback(createUpgradeRequest(request), env); if (response instanceof Response) { status = response.status; responseHeaders = response.headers; } } catch (error) { if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, error instanceof RequestError ? 400 : 500); return; } if (socket.destroyed) { rejectWaiter(request); return; } const waiter = waiterMap.get(request); if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) { rejectWaiter(request); if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders); return; } const addResponseHeaders = (headers) => { appendResponseHeaders(headers, responseHeaders); }; wss.on("headers", addResponseHeaders); try { wss.handleUpgrade(request, socket, head, (ws) => { socket.off("close", reclaimWaiterOnClose); socket.off("error", ignoreSocketError); wss.emit("connection", ws, request); }); } finally { wss.off("headers", addResponseHeaders); } }); server.on("close", () => { wss.close(); });};const upgradeWebSocket = (0, hono_ws.defineWebSocketHelper)(async (c, events, options) => { if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return; const env = c.env; const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL]; if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 }); const connectionSymbol = generateConnectionSymbol(); env[CONNECTION_SYMBOL_KEY] = connectionSymbol; (async () => { let ws; try { ws = await waitForWebSocket(env.incoming, connectionSymbol); } catch { return; } const messagesReceivedInStarting = []; const bufferMessage = (data, isBinary) => { messagesReceivedInStarting.push([data, isBinary]); }; ws.on("message", bufferMessage); const ctx = { binaryType: "arraybuffer", close(code, reason) { ws.close(code, reason); }, protocol: ws.protocol, raw: ws, get readyState() { return ws.readyState; }, send(source, opts) { ws.send(source, { compress: opts?.compress }); }, url: new URL(c.req.url) }; try { events?.onOpen?.(new Event("open"), ctx); } catch (e) { (options?.onError ?? console.error)(e); } const handleMessage = (data, isBinary) => { const datas = Array.isArray(data) ? data : [data]; for (const data of datas) try { events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === "string" ? data : Buffer.from(data).toString("utf-8") }), ctx); } catch (e) { (options?.onError ?? console.error)(e); } }; ws.off("message", bufferMessage); for (const message of messagesReceivedInStarting) handleMessage(...message); ws.on("message", (data, isBinary) => { handleMessage(data, isBinary); }); ws.on("close", (code, reason) => { try { events?.onClose?.(new CloseEvent("close", { code, reason: reason.toString() }), ctx); } catch (e) { (options?.onError ?? console.error)(e); } }); ws.on("error", (error) => { try { events?.onError?.(new ErrorEvent("error", { error }), ctx); } catch (e) { (options?.onError ?? console.error)(e); } }); })(); return new Response();});
//#endregion//#region src/server.tsconst createAdaptorServer = (options) => { const fetchCallback = options.fetch; const requestListener = getRequestListener(fetchCallback, { hostname: options.hostname, overrideGlobalObjects: options.overrideGlobalObjects, autoCleanupIncoming: options.autoCleanupIncoming }); const server = (options.createServer || node_http.createServer)(options.serverOptions || {}, requestListener); if (options.websocket && options.websocket.server) { if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option"); setupWebSocket({ server, fetchCallback, wss: options.websocket.server }); } return server;};const serve = (options, listeningListener) => { const server = createAdaptorServer(options); server.listen(options?.port ?? 3e3, options.hostname, () => { const serverInfo = server.address(); listeningListener && listeningListener(serverInfo); }); return server;};
//#endregionexports.RequestError = RequestError;exports.createAdaptorServer = createAdaptorServer;exports.getRequestListener = getRequestListener;exports.serve = serve;exports.upgradeWebSocket = upgradeWebSocket;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import { AddressInfo } from "node:net";import { IncomingMessage, Server, ServerOptions, ServerResponse, createServer } from "node:http";import { Http2SecureServer, Http2Server, Http2ServerRequest, Http2ServerResponse, SecureServerOptions, ServerOptions as ServerOptions$1, createSecureServer, createServer as createServer$1 } from "node:http2";import { ServerOptions as ServerOptions$2, createServer as createServer$2 } from "node:https";import { Duplex } from "node:stream";import { UpgradeWebSocket } from "hono/ws";
//#region src/websocket-types.d.tstype WSReadyState = 0 | 1 | 2 | 3;type WebSocketData = string | ArrayBuffer | Uint8Array | readonly Uint8Array[];type WebSocketSendOptions = { compress?: boolean;};interface WebSocketLike { protocol: string; readyState: WSReadyState; close(code?: number, reason?: string): void; send(data: string | ArrayBuffer | ArrayBufferView, options?: WebSocketSendOptions): void; on(event: 'message', listener: (data: WebSocketData, isBinary: boolean) => void): this; on(event: 'close', listener: (code: number, reason: Uint8Array) => void): this; on(event: 'error', listener: (error: unknown) => void): this; off(event: 'message', listener: (data: WebSocketData, isBinary: boolean) => void): this;}interface WebSocketServerLike { options: { noServer?: boolean; }; on(event: 'connection', listener: (ws: WebSocketLike, request: IncomingMessage) => void): this; on(event: 'headers', listener: (headers: string[]) => void): this; off(event: 'headers', listener: (headers: string[]) => void): this; emit(event: 'connection', ws: WebSocketLike, request: IncomingMessage): boolean; handleUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer, callback: (ws: WebSocketLike) => void): void; close(): void;}//#endregion//#region src/types.d.tstype HttpBindings = { incoming: IncomingMessage; outgoing: ServerResponse;};type Http2Bindings = { incoming: Http2ServerRequest; outgoing: Http2ServerResponse;};type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise<unknown> | unknown;type ServerType = Server | Http2Server | Http2SecureServer;type createHttpOptions = { serverOptions?: ServerOptions; createServer?: typeof createServer;};type createHttpsOptions = { serverOptions?: ServerOptions$2; createServer?: typeof createServer$2;};type createHttp2Options = { serverOptions?: ServerOptions$1; createServer?: typeof createServer$1;};type createSecureHttp2Options = { serverOptions?: SecureServerOptions; createServer?: typeof createSecureServer;};type ServerOptions$3 = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options;type Options = { fetch: FetchCallback; overrideGlobalObjects?: boolean; autoCleanupIncoming?: boolean; port?: number; hostname?: string; websocket?: { server: WebSocketServerLike; };} & ServerOptions$3;type CustomErrorHandler = (err: unknown) => void | Response | Promise<void | Response>;//#endregion//#region src/server.d.tsdeclare const createAdaptorServer: (options: Options) => ServerType;declare const serve: (options: Options, listeningListener?: (info: AddressInfo) => void) => ServerType;//#endregion//#region src/websocket.d.tstype UpgradeWebSocketOptions = { onError: (err: unknown) => void;};declare const upgradeWebSocket: UpgradeWebSocket<WebSocketLike, UpgradeWebSocketOptions>;//#endregion//#region src/listener.d.tsdeclare const getRequestListener: (fetchCallback: FetchCallback, options?: { hostname?: string; errorHandler?: CustomErrorHandler; overrideGlobalObjects?: boolean; autoCleanupIncoming?: boolean;}) => (incoming: IncomingMessage | Http2ServerRequest, outgoing: ServerResponse | Http2ServerResponse) => Promise<void>;//#endregion//#region src/error.d.tsdeclare class RequestError extends Error { constructor(message: string, options?: { cause?: unknown; });}//#endregionexport { type Http2Bindings, type HttpBindings, RequestError, type ServerType, type WebSocketData, type WebSocketLike, type WebSocketServerLike, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import { IncomingMessage, Server, ServerOptions, ServerResponse, createServer } from "node:http";import { Http2SecureServer, Http2Server, Http2ServerRequest, Http2ServerResponse, SecureServerOptions, ServerOptions as ServerOptions$1, createSecureServer, createServer as createServer$1 } from "node:http2";import { Duplex } from "node:stream";import { UpgradeWebSocket } from "hono/ws";import { AddressInfo } from "node:net";import { ServerOptions as ServerOptions$2, createServer as createServer$2 } from "node:https";
//#region src/websocket-types.d.tstype WSReadyState = 0 | 1 | 2 | 3;type WebSocketData = string | ArrayBuffer | Uint8Array | readonly Uint8Array[];type WebSocketSendOptions = { compress?: boolean;};interface WebSocketLike { protocol: string; readyState: WSReadyState; close(code?: number, reason?: string): void; send(data: string | ArrayBuffer | ArrayBufferView, options?: WebSocketSendOptions): void; on(event: 'message', listener: (data: WebSocketData, isBinary: boolean) => void): this; on(event: 'close', listener: (code: number, reason: Uint8Array) => void): this; on(event: 'error', listener: (error: unknown) => void): this; off(event: 'message', listener: (data: WebSocketData, isBinary: boolean) => void): this;}interface WebSocketServerLike { options: { noServer?: boolean; }; on(event: 'connection', listener: (ws: WebSocketLike, request: IncomingMessage) => void): this; on(event: 'headers', listener: (headers: string[]) => void): this; off(event: 'headers', listener: (headers: string[]) => void): this; emit(event: 'connection', ws: WebSocketLike, request: IncomingMessage): boolean; handleUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer, callback: (ws: WebSocketLike) => void): void; close(): void;}//#endregion//#region src/types.d.tstype HttpBindings = { incoming: IncomingMessage; outgoing: ServerResponse;};type Http2Bindings = { incoming: Http2ServerRequest; outgoing: Http2ServerResponse;};type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise<unknown> | unknown;type ServerType = Server | Http2Server | Http2SecureServer;type createHttpOptions = { serverOptions?: ServerOptions; createServer?: typeof createServer;};type createHttpsOptions = { serverOptions?: ServerOptions$2; createServer?: typeof createServer$2;};type createHttp2Options = { serverOptions?: ServerOptions$1; createServer?: typeof createServer$1;};type createSecureHttp2Options = { serverOptions?: SecureServerOptions; createServer?: typeof createSecureServer;};type ServerOptions$3 = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options;type Options = { fetch: FetchCallback; overrideGlobalObjects?: boolean; autoCleanupIncoming?: boolean; port?: number; hostname?: string; websocket?: { server: WebSocketServerLike; };} & ServerOptions$3;type CustomErrorHandler = (err: unknown) => void | Response | Promise<void | Response>;//#endregion//#region src/server.d.tsdeclare const createAdaptorServer: (options: Options) => ServerType;declare const serve: (options: Options, listeningListener?: (info: AddressInfo) => void) => ServerType;//#endregion//#region src/websocket.d.tstype UpgradeWebSocketOptions = { onError: (err: unknown) => void;};declare const upgradeWebSocket: UpgradeWebSocket<WebSocketLike, UpgradeWebSocketOptions>;//#endregion//#region src/listener.d.tsdeclare const getRequestListener: (fetchCallback: FetchCallback, options?: { hostname?: string; errorHandler?: CustomErrorHandler; overrideGlobalObjects?: boolean; autoCleanupIncoming?: boolean;}) => (incoming: IncomingMessage | Http2ServerRequest, outgoing: ServerResponse | Http2ServerResponse) => Promise<void>;//#endregion//#region src/error.d.tsdeclare class RequestError extends Error { constructor(message: string, options?: { cause?: unknown; });}//#endregionexport { type Http2Bindings, type HttpBindings, RequestError, type ServerType, type WebSocketData, type WebSocketLike, type WebSocketServerLike, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381import { t as X_ALREADY_SENT } from "./constants-BLSFu_RU.mjs";import { STATUS_CODES, ServerResponse, createServer } from "node:http";import { Http2ServerRequest, constants } from "node:http2";import { Readable } from "node:stream";import { defineWebSocketHelper } from "hono/ws";
//#region src/error.tsvar RequestError = class extends Error { constructor(message, options) { super(message, options); this.name = "RequestError"; }};
//#endregion//#region src/headers.tsconst nonJoinedHeaders = new Set([ "age", "authorization", "content-length", "content-type", "etag", "expires", "from", "host", "if-modified-since", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "referer", "retry-after", "server", "user-agent"]);const validHeaderName = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;const isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;const normalizeHeaderValue = (value) => { if (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value; let start = 0; let end = value.length; while (start < end && isHttpWhitespace(value.charCodeAt(start))) start++; while (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--; return value.slice(start, end);};const forbiddenHeaderValue = /[\0\r\n]/;const GlobalHeaders = globalThis.Headers;const materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => { const headers = new HeadersCtor(); for (let i = 0; i < rawHeaders.length; i += 2) { const name = rawHeaders[i]; if (!name.startsWith(":")) headers.append(name, rawHeaders[i + 1]); } return headers;};var RequestHeaders = class { #incoming; #rawHeaders; #headers; #invalidValue; constructor(incoming) { this.#incoming = incoming; if (incoming instanceof Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice(); } get #lazyRawHeaders() { return this.#rawHeaders ??= this.#incoming.rawHeaders.slice(); } get #native() { if (!this.#headers) { this.#headers = materializeHeaders(this.#lazyRawHeaders); this.#rawHeaders = void 0; } return this.#headers; } #normalizedName(name) { if (typeof name !== "string") return; if (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`); return name.toLowerCase(); } #lookupHttp1(lowerName) { const headers = this.#incoming instanceof Http2ServerRequest ? void 0 : this.#incoming.headers; if (!headers || nonJoinedHeaders.has(lowerName) || lowerName === "set-cookie" || lowerName === "__proto__") return; if (!Object.hasOwn(headers, lowerName)) return null; const rawValue = headers[lowerName]; if (typeof rawValue === "string") { const value = normalizeHeaderValue(rawValue); return forbiddenHeaderValue.test(value) ? void 0 : value; } } #lookup(rawHeaders, lowerName) { const separator = lowerName === "cookie" ? "; " : ", "; let value = null; for (let i = 0; i < rawHeaders.length; i += 2) { const rawName = rawHeaders[i]; if (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) { const rawValue = normalizeHeaderValue(rawHeaders[i + 1]); if (forbiddenHeaderValue.test(rawValue)) { this.#invalidValue = true; return; } value = value === null ? rawValue : value + separator + rawValue; } } return value; } append(name, value) { this.#native.append(name, value); } delete(name) { this.#native.delete(name); } get(name) { const lowerName = this.#normalizedName(name); if (lowerName && !this.#headers && !this.#invalidValue) { const http1Value = this.#lookupHttp1(lowerName); if (http1Value !== void 0) return http1Value; const value = this.#lookup(this.#lazyRawHeaders, lowerName); if (value !== void 0) return value; } return this.#native.get(name); } has(name) { const lowerName = this.#normalizedName(name); if (lowerName && !this.#headers && !this.#invalidValue) { const http1Value = this.#lookupHttp1(lowerName); if (http1Value !== void 0) return http1Value !== null; const value = this.#lookup(this.#lazyRawHeaders, lowerName); if (value !== void 0) return value !== null; } return this.#native.has(name); } set(name, value) { this.#native.set(name, value); } getSetCookie() { return this.#native.getSetCookie(); } keys() { return this.#native.keys(); } values() { return this.#native.values(); } entries() { return this.#native.entries(); } forEach(callback, thisArg) { this.#native.forEach((value, key) => { callback.call(thisArg, value, key, this); }); } [Symbol.iterator]() { return this.entries(); }};Object.defineProperty(RequestHeaders.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) { return `Headers (lightweight) ${inspectFn(Object.fromEntries(this), { ...options, depth: depth == null ? null : depth - 1 })}`;} });Object.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);
//#endregion//#region src/url.tsconst reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;const reDotSegment = /\/\.\.?(?:[/?#]|$)/;const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;const validateRequestTarget = (target) => { const backslash = target.indexOf("\\"); if (backslash !== -1) { const query = target.indexOf("?"); if (query === -1 || backslash < query) throw new RequestError("Backslash in request path"); }};const buildUrl = (scheme, host, incomingUrl) => { const url = `${scheme}://${host}${incomingUrl}`; if (!reValidHost.test(host)) { validateRequestTarget(incomingUrl); const urlObj = new URL(url); if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header"); return urlObj.href; } else if (incomingUrl.length === 0) return url + "/"; else { if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL"); if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) { validateRequestTarget(incomingUrl); return new URL(url).href; } return url; }};
//#endregion//#region src/request.tsconst toRequestError = (e) => { if (e instanceof RequestError) return e; return new RequestError(e.message, { cause: e });};const GlobalRequest = global.Request;var Request$1 = class Request$1 extends GlobalRequest { static [Symbol.hasInstance](instance) { if (this === Request$1) return instance instanceof GlobalRequest || Function.prototype[Symbol.hasInstance].call(this, instance); return Function.prototype[Symbol.hasInstance].call(this, instance); } constructor(input, options) { if (typeof input === "object" && getRequestCache in input) { const hasReplacementBody = options !== void 0 && "body" in options && options.body != null; if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used."); input = input[getRequestCache](); } if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half"; super(input, options); }};const wrapBodyStream = Symbol("wrapBodyStream");const byteExactEncodings = new Set([ "latin1", "binary", "hex", "base64", "base64url"]);const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);const recordBodyBufferedBeforeDisconnect = (incoming) => { if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return; const incomingWithRecovery = incoming; incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;};const readBodyBufferedBeforeDisconnect = (incoming, chunks) => { if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return; const incomingWithRecovery = incoming; if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey]; let result; const errored = incoming.errored; if (errored && errored.code !== "ECONNRESET") result = errored; else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError(); else { const bodyChunks = chunks ?? []; let chunk; while ((chunk = incoming.read()) !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding)); const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks); result = buffer; const contentLength = incoming.headers["content-length"]; if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) { const expectedLength = Number(contentLength); if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError(); } } incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result; return result;};const enqueueBufferedBody = (controller, buffered) => { if (buffered instanceof Error) { controller.error(buffered); return; } if (buffered.length > 0) controller.enqueue(buffered); controller.close();};const newRequestFromIncoming = (method, url, headers, incoming, abortController) => { const init = { method, headers, signal: abortController.signal }; if (method === "TRACE") { init.method = "GET"; const req = new Request$1(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 { if (!reader) { const buffered = readBodyBufferedBeforeDisconnect(incoming); if (buffered !== void 0) { enqueueBufferedBody(controller, buffered); return; } } 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 { const buffered = readBodyBufferedBeforeDisconnect(incoming); if (buffered !== void 0) init.body = new ReadableStream({ start(controller) { enqueueBufferedBody(controller, buffered); } }); else init.body = Readable.toWeb(incoming); } return new Request$1(url, init);};const getRequestCache = Symbol("getRequestCache");const requestCache = Symbol("requestCache");const incomingKey = Symbol("incomingKey");const urlKey = Symbol("urlKey");const methodKey = Symbol("methodKey");const headersKey = Symbol("headersKey");const abortControllerKey = Symbol("abortControllerKey");const getAbortController = Symbol("getAbortController");const abortRequest = Symbol("abortRequest");const bodyBufferKey = Symbol("bodyBuffer");const bodyReadPromiseKey = Symbol("bodyReadPromise");const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");const bodyLockReaderKey = Symbol("bodyLockReader");const abortReasonKey = Symbol("abortReason");const newBodyUnusableError = () => { return /* @__PURE__ */ new TypeError("Body is unusable");};const rejectBodyUnusable = () => { return Promise.reject(newBodyUnusableError());};const textDecoder = new TextDecoder();const consumeBodyDirectOnce = (request) => { if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable(); request[bodyConsumedDirectlyKey] = true;};const toArrayBuffer = (buf) => { return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);};const contentType = (request) => { return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";};const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;const normalizeIncomingMethod = (method) => { if (typeof method !== "string" || method.length === 0) return "GET"; switch (method) { case "DELETE": case "GET": case "HEAD": case "OPTIONS": case "PATCH": case "POST": case "PUT": case "QUERY": return method; } const upper = method.toUpperCase(); switch (upper) { case "DELETE": case "GET": case "HEAD": case "OPTIONS": case "POST": case "PUT": return upper; default: return method; }};const validateDirectReadMethod = (method) => { if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`); const normalized = method.toUpperCase(); if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);};const readBodyWithFastPath = (request, method, fromBuffer) => { if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable(); const methodName = request.method; if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method](); const methodValidationError = validateDirectReadMethod(methodName); if (methodValidationError) return Promise.reject(methodValidationError); if (request[requestCache]) { if (methodName !== "TRACE") return request[requestCache][method](); } const alreadyUsedError = consumeBodyDirectOnce(request); if (alreadyUsedError) return alreadyUsedError; const raw = readRawBodyIfAvailable(request); if (raw) { const result = Promise.resolve(fromBuffer(raw, request)); request[bodyBufferKey] = void 0; return result; } return readBodyDirect(request).then((buf) => { const result = fromBuffer(buf, request); request[bodyBufferKey] = void 0; return result; });};const readRawBodyIfAvailable = (request) => { const incoming = request[incomingKey]; if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;};const normalizeAbortError = (request, incoming) => { if (incoming.errored) return incoming.errored; const reason = request[abortReasonKey]; if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason)); return /* @__PURE__ */ new Error("Client connection prematurely closed.");};const readBodyDirect = (request) => { if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]); if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey]; const incoming = request[incomingKey]; if (incoming.readableDidRead) return rejectBodyUnusable(); const buffered = readBodyBufferedBeforeDisconnect(incoming); if (buffered !== void 0) { if (buffered instanceof Error) return Promise.reject(buffered); request[bodyBufferKey] = buffered; return Promise.resolve(buffered); } const promise = new Promise((resolve, reject) => { const chunks = []; let settled = false; const finish = (callback) => { if (settled) return; settled = true; cleanup(); callback(); }; const recoverCompleteBodyAfterDisconnect = (error) => { const streamError = incoming.errored ?? error; if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false; finish(() => { const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks); if (recovered instanceof Error) reject(recovered); else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming)); else { request[bodyBufferKey] = recovered; resolve(recovered); } }); return true; }; const onData = (chunk) => { chunks.push(toBufferChunk(chunk, incoming.readableEncoding)); }; const onEnd = () => { finish(() => { const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks); request[bodyBufferKey] = buffer; resolve(buffer); }); }; const onError = (error) => { if (recoverCompleteBodyAfterDisconnect(error)) return; finish(() => { reject(error); }); }; const onClose = () => { if (incoming.readableEnded) { onEnd(); return; } if (recoverCompleteBodyAfterDisconnect()) return; finish(() => { reject(normalizeAbortError(request, incoming)); }); }; const cleanup = () => { incoming.off("data", onData); incoming.off("end", onEnd); incoming.off("error", onError); incoming.off("close", onClose); request[bodyReadPromiseKey] = void 0; }; incoming.on("data", onData); incoming.on("end", onEnd); incoming.on("error", onError); incoming.on("close", onClose); queueMicrotask(() => { if (settled) return; if (incoming.readableEnded) onEnd(); else if (incoming.errored) onError(incoming.errored); else if (incoming.destroyed) onClose(); }); }); request[bodyReadPromiseKey] = promise; return promise;};const requestPrototype = { get method() { return this[methodKey]; }, get url() { return this[urlKey]; }, get headers() { return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); }, [abortRequest](reason) { if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason; const abortController = this[abortControllerKey]; if (abortController && !abortController.signal.aborted) abortController.abort(reason); }, [getAbortController]() { this[abortControllerKey] ||= new AbortController(); if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]); return this[abortControllerKey]; }, [getRequestCache]() { const abortController = this[getAbortController](); if (this[requestCache]) return this[requestCache]; const method = this.method; if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) { this[bodyBufferKey] = void 0; const init = { method: method === "TRACE" ? "GET" : method, headers: this.headers, signal: abortController.signal }; if (method !== "TRACE") { init.body = new ReadableStream({ start(c) { c.close(); } }); init.duplex = "half"; } const req = new Request$1(this[urlKey], init); if (method === "TRACE") Object.defineProperty(req, "method", { get() { return "TRACE"; } }); return this[requestCache] = req; } return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController); }, get body() { if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body; const request = this[getRequestCache](); if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader(); return request.body; }, get bodyUsed() { if (this[bodyConsumedDirectlyKey]) return true; if (this[requestCache]) return this[requestCache].bodyUsed; return false; }};Object.defineProperty(requestPrototype, "signal", { get() { return this[getAbortController]().signal;} });[ "cache", "credentials", "destination", "duplex", "integrity", "mode", "redirect", "referrer", "referrerPolicy", "keepalive"].forEach((k) => { Object.defineProperty(requestPrototype, k, { get() { return this[getRequestCache]()[k]; } });});["clone", "formData"].forEach((k) => { Object.defineProperty(requestPrototype, k, { value: function() { if (this[bodyConsumedDirectlyKey]) { if (k === "clone") throw newBodyUnusableError(); return rejectBodyUnusable(); } return this[getRequestCache]()[k](); } });});Object.defineProperty(requestPrototype, "text", { value: function() { return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));} });Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() { return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));} });Object.defineProperty(requestPrototype, "blob", { value: function() { return readBodyWithFastPath(this, "blob", (buf, request) => { const type = contentType(request); const init = type ? { headers: { "content-type": type } } : void 0; return new Response(buf, init).blob(); });} });Object.defineProperty(requestPrototype, "bytes", { value: function() { return this.arrayBuffer().then((buf) => new Uint8Array(buf));} });Object.defineProperty(requestPrototype, "json", { value: function() { if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable(); return this.text().then(JSON.parse);} });Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) { return `Request (lightweight) ${inspectFn({ method: this.method, url: this.url, headers: this.headers, nativeRequest: this[requestCache] }, { ...options, depth: depth == null ? null : depth - 1 })}`;} });Object.setPrototypeOf(requestPrototype, Request$1.prototype);const newRequest = (incoming, defaultHostname) => { const req = Object.create(requestPrototype); req[incomingKey] = incoming; req[methodKey] = normalizeIncomingMethod(incoming.method); const incomingUrl = incoming.url || ""; if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); try { validateRequestTarget(incomingUrl); req[urlKey] = new URL(incomingUrl).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"; try { req[urlKey] = buildUrl(scheme, host, incomingUrl); } catch (e) { if (e instanceof RequestError) throw e; else throw new RequestError("Invalid URL", { cause: e }); } return req;};
//#endregion//#region src/response.tsconst defaultContentType = "text/plain; charset=UTF-8";const responseCache = Symbol("responseCache");const getResponseCache = Symbol("getResponseCache");const cacheKey = Symbol("cache");const GlobalResponse = global.Response;var Response$1 = class Response$1 { #body; #init; static [Symbol.hasInstance](instance) { if (this === Response$1) return instance instanceof GlobalResponse || Function.prototype[Symbol.hasInstance].call(this, instance); return Function.prototype[Symbol.hasInstance].call(this, instance); } [getResponseCache]() { const cache = this[cacheKey]; const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0; delete this[cacheKey]; return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? { status: this.#init?.status, statusText: this.#init?.statusText, headers: liveHeaders } : this.#init); } constructor(body, init) { let headers; this.#body = body; if (init instanceof GlobalResponse) { const cachedGlobalResponse = init[responseCache]; if (cachedGlobalResponse) { this.#init = cachedGlobalResponse; this[getResponseCache](); return; } this.#init = #init in init ? init.#init : init; headers = new Headers(init.headers); } else this.#init = init; if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [ init?.status || 200, body ?? null, headers || init?.headers ]; } get headers() { const cache = this[cacheKey]; if (cache) { if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType })); 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$1.prototype, k, { get() { return this[getResponseCache]()[k]; } });});[ "arrayBuffer", "blob", "bytes", "clone", "formData", "json", "text"].forEach((k) => { Object.defineProperty(Response$1.prototype, k, { value: function() { return this[getResponseCache]()[k](); } });});Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) { return `Response (lightweight) ${inspectFn({ status: this.status, headers: this.headers, ok: this.ok, nativeResponse: this[responseCache] }, { ...options, depth: depth == null ? null : depth - 1 })}`;} });Object.setPrototypeOf(Response$1, GlobalResponse);Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;const parseRedirectUrl = (url) => { if (url instanceof URL) return url.href; if (validRedirectUrl.test(url)) return url; return new URL(url).href;};const validRedirectStatuses = new Set([ 301, 302, 303, 307, 308]);Object.defineProperty(Response$1, "redirect", { value: function redirect(url, status = 302) { if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code"); return new Response$1(null, { status, headers: { location: parseRedirectUrl(url) } }); }, writable: true, configurable: true});Object.defineProperty(Response$1, "json", { value: function json(data, init) { const body = JSON.stringify(data); if (body === void 0) throw new TypeError("The data is not JSON serializable"); const initHeaders = init?.headers; let headers; if (initHeaders) { headers = new Headers(initHeaders); if (!headers.has("content-type")) headers.set("content-type", "application/json"); } else headers = { "content-type": "application/json" }; return new Response$1(body, { status: init?.status ?? 200, statusText: init?.statusText, headers }); }, writable: true, configurable: true});
//#endregion//#region src/utils.tsasync 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(() => {}); }; const stream = writable.stream; if (writable.destroyed || stream?.closed || stream?.destroyed) { cancel(); return reader.closed; } 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 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) { stream.cancel().catch(() => {}); return; } return writeFromReadableStreamDefaultReader(stream.getReader(), writable);}const buildOutgoingHttpHeaders = (headers, defaultContentType) => { const res = {}; if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0); if (headers.has("set-cookie")) { 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; } else for (const [k, v] of headers) res[k] = v; if (defaultContentType) res["content-type"] ??= defaultContentType; return res;};
//#endregion//#region src/listener.tsconst outgoingEnded = Symbol("outgoingEnded");const incomingDraining = Symbol("incomingDraining");const DRAIN_TIMEOUT_MS = 500;const MAX_DRAIN_BYTES = 64 * 1024 * 1024;const drainIncoming = (incoming) => { const incomingWithDrainState = incoming; if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return; incomingWithDrainState[incomingDraining] = true; if (incoming instanceof Http2ServerRequest) { try { incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR); } catch {} return; } let bytesRead = 0; const cleanup = () => { clearTimeout(timer); incoming.off("data", onData); incoming.off("end", cleanup); incoming.off("error", cleanup); }; const forceClose = () => { cleanup(); const socket = incoming.socket; if (socket && !socket.destroyed) { if (typeof socket.destroySoon === "function") socket.destroySoon(); else if (typeof socket.destroy === "function") socket.destroy(); } }; const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS); timer.unref?.(); const onData = (chunk) => { bytesRead += chunk.length; if (bytesRead > MAX_DRAIN_BYTES) forceClose(); }; incoming.on("data", onData); incoming.on("end", cleanup); incoming.on("error", cleanup); incoming.resume();};const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => { if (incoming.errored) { recordBodyBufferedBeforeDisconnect(incoming); req[abortRequest](incoming.errored.toString()); } else if (!outgoing.writableFinished || incoming instanceof Http2ServerRequest && incoming.aborted) { recordBodyBufferedBeforeDisconnect(incoming); req[abortRequest]("Client connection prematurely closed."); } if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => { if (!incoming.readableEnded) setTimeout(() => { drainIncoming(incoming); }); });};const isImmediateCacheableResponse = (res) => { if (!(cacheKey in res)) return false; const body = res[cacheKey][1]; return body === null || typeof body === "string" || body instanceof Uint8Array;};const handleRequestError = () => new Response(null, { status: 400 });const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });const 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) { if (outgoing instanceof ServerResponse) outgoing._contentLength = null; outgoing.writeHead(500, { "Content-Type": "text/plain" }); } outgoing.end(`Error: ${err.message}`); outgoing.destroy(err); }};const flushHeaders = (outgoing) => { if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();};const trySetContentLength = (outgoing, status, length) => { const http1 = outgoing; if (http1._contentLength === null && http1._hasBody && http1.useChunkedEncodingByDefault && !http1._removedContLen && status >= 200 && status !== 204 && status !== 304 && !outgoing.hasHeader("content-length") && !outgoing.hasHeader("transfer-encoding") && !outgoing.hasHeader("trailer")) { http1._contentLength = length; return true; } return false;};const writeDefaultHeaders = (outgoing, status, length) => { if (trySetContentLength(outgoing, status, length)) outgoing.writeHead(status, { "Content-Type": defaultContentType }); else outgoing.writeHead(status, { "Content-Type": defaultContentType, "Content-Length": length });};const responseViaCache = async (res, outgoing) => { let [status, body, header] = res[cacheKey]; if (!header) { if (body === null) { outgoing.writeHead(status); outgoing.end(); } else if (typeof body === "string") { writeDefaultHeaders(outgoing, status, Buffer.byteLength(body)); outgoing.end(body); } else if (body instanceof Uint8Array) { writeDefaultHeaders(outgoing, status, body.byteLength); outgoing.end(body); } else if (body instanceof Blob) { writeDefaultHeaders(outgoing, status, body.size); outgoing.end(new Uint8Array(await body.arrayBuffer())); } else { outgoing.writeHead(status, { "Content-Type": defaultContentType }); flushHeaders(outgoing); await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing)); } outgoing[outgoingEnded]?.(); return; } let hasContentLength = false; let plainHeaders = false; let canAutoLength = true; if (header instanceof Headers) { hasContentLength = header.has("content-length"); header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType); } else if (Array.isArray(header)) { const headerObj = new Headers(header); hasContentLength = headerObj.has("content-length"); header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType); } else { plainHeaders = true; for (const key in header) { if (key.length === 14 && key.toLowerCase() === "content-length") { hasContentLength = true; break; } if (key.length === 17 && key.toLowerCase() === "transfer-encoding" || key.length === 7 && key.toLowerCase() === "trailer") canAutoLength = false; } } if (!hasContentLength) { let length; if (typeof body === "string") length = Buffer.byteLength(body); else if (body instanceof Uint8Array) length = body.byteLength; else if (body instanceof Blob) length = body.size; if (length !== void 0 && (!plainHeaders || !canAutoLength || !trySetContentLength(outgoing, status, length))) { if (plainHeaders) header = { ...header }; header["Content-Length"] = length; } } outgoing.writeHead(status, header); if (body == null) outgoing.end(); else 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]?.();};const isPromise = (res) => typeof res.then === "function";const 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, res.body === null ? void 0 : defaultContentType); 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); 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]?.();};const getRequestListener = (fetchCallback, options = {}) => { const autoCleanupIncoming = options.autoCleanupIncoming ?? true; if (options.overrideGlobalObjects !== false && global.Request !== Request$1) { Object.defineProperty(global, "Request", { value: Request$1 }); Object.defineProperty(global, "Response", { value: Response$1 }); } return async (incoming, outgoing) => { let res, req; let needsBodyCleanup = false; let closeHandlerAttached = false; const ensureCloseHandler = () => { if (!req || closeHandlerAttached) return; closeHandlerAttached = true; outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup)); }; try { req = newRequest(incoming, options.hostname); needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD"); if (needsBodyCleanup) { incoming[wrapBodyStream] = true; if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => { if (!incoming.readableEnded) setTimeout(() => { if (!incoming.readableEnded) setTimeout(() => { incoming.destroy(); outgoing.destroy(); }); }); }; } res = fetchCallback(req, { incoming, outgoing }); if (!isPromise(res) && isImmediateCacheableResponse(res)) { if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => { if (!incoming.readableEnded) drainIncoming(incoming); }); return responseViaCache(res, outgoing); } ensureCloseHandler(); } catch (e) { if (!res) if (options.errorHandler) { ensureCloseHandler(); 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); } };};
//#endregion//#region src/websocket.ts/*** @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent*/const CloseEvent = globalThis.CloseEvent ?? class extends Event { #eventInitDict; constructor(type, eventInitDict = {}) { super(type, eventInitDict); this.#eventInitDict = eventInitDict; } get wasClean() { return this.#eventInitDict.wasClean ?? false; } get code() { return this.#eventInitDict.code ?? 0; } get reason() { return this.#eventInitDict.reason ?? ""; }};/*** Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.* @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent*/const ErrorEvent = globalThis.ErrorEvent ?? class extends Event { #eventInitDict; constructor(type, eventInitDict = {}) { super(type, eventInitDict); this.#eventInitDict = eventInitDict; } get message() { return this.#eventInitDict.message ?? ""; } get filename() { return this.#eventInitDict.filename ?? ""; } get lineno() { return this.#eventInitDict.lineno ?? 0; } get colno() { return this.#eventInitDict.colno ?? 0; } get error() { return this.#eventInitDict.error ?? null; }};const generateConnectionSymbol = () => Symbol("connection");const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");const responseHeadersToSkip = new Set([ "connection", "content-length", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "sec-websocket-accept", "sec-websocket-extensions", "sec-websocket-protocol"]);const appendResponseHeaders = (headers, responseHeaders) => { if (!responseHeaders) return; responseHeaders.forEach((value, key) => { if (responseHeadersToSkip.has(key.toLowerCase())) return; headers.push(`${key}: ${value}`); });};const rejectUpgradeRequest = (socket, status, responseHeaders) => { if (socket.destroyed) return; const responseLines = ["Connection: close", "Content-Length: 0"]; appendResponseHeaders(responseLines, responseHeaders); socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r`);};const createUpgradeRequest = (request) => { const protocol = request.socket.encrypted ? "https" : "http"; const incomingUrl = request.url ?? "/"; let url; if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { validateRequestTarget(incomingUrl); url = new URL(incomingUrl).href; } else url = buildUrl(protocol, request.headers.host ?? "localhost", incomingUrl); const headers = new Headers(); for (const key in request.headers) { const value = request.headers[key]; if (!value) continue; headers.append(key, Array.isArray(value) ? value[0] : value); } return new Request(url, { headers });};const setupWebSocket = (options) => { const { server, fetchCallback, wss } = options; const waiterMap = /* @__PURE__ */ new Map(); wss.on("connection", (ws, request) => { const waiter = waiterMap.get(request); if (waiter) { waiter.resolve(ws); waiterMap.delete(request); } }); const rejectWaiter = (request) => { const waiter = waiterMap.get(request); if (waiter) { waiterMap.delete(request); waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted")); } }; const waitForWebSocket = (request, connectionSymbol) => { return new Promise((resolve, reject) => { waiterMap.set(request, { resolve, reject, connectionSymbol }); }); }; server.on("upgrade", async (request, socket, head) => { const ignoreSocketError = () => {}; socket.on("error", ignoreSocketError); if (request.headers.upgrade?.toLowerCase() !== "websocket") { if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 400); return; } const reclaimWaiterOnClose = () => rejectWaiter(request); socket.once("close", reclaimWaiterOnClose); const env = { incoming: request, outgoing: void 0, wss, [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket }; let status = 400; let responseHeaders; try { const response = await fetchCallback(createUpgradeRequest(request), env); if (response instanceof Response) { status = response.status; responseHeaders = response.headers; } } catch (error) { if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, error instanceof RequestError ? 400 : 500); return; } if (socket.destroyed) { rejectWaiter(request); return; } const waiter = waiterMap.get(request); if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) { rejectWaiter(request); if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders); return; } const addResponseHeaders = (headers) => { appendResponseHeaders(headers, responseHeaders); }; wss.on("headers", addResponseHeaders); try { wss.handleUpgrade(request, socket, head, (ws) => { socket.off("close", reclaimWaiterOnClose); socket.off("error", ignoreSocketError); wss.emit("connection", ws, request); }); } finally { wss.off("headers", addResponseHeaders); } }); server.on("close", () => { wss.close(); });};const upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => { if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return; const env = c.env; const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL]; if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 }); const connectionSymbol = generateConnectionSymbol(); env[CONNECTION_SYMBOL_KEY] = connectionSymbol; (async () => { let ws; try { ws = await waitForWebSocket(env.incoming, connectionSymbol); } catch { return; } const messagesReceivedInStarting = []; const bufferMessage = (data, isBinary) => { messagesReceivedInStarting.push([data, isBinary]); }; ws.on("message", bufferMessage); const ctx = { binaryType: "arraybuffer", close(code, reason) { ws.close(code, reason); }, protocol: ws.protocol, raw: ws, get readyState() { return ws.readyState; }, send(source, opts) { ws.send(source, { compress: opts?.compress }); }, url: new URL(c.req.url) }; try { events?.onOpen?.(new Event("open"), ctx); } catch (e) { (options?.onError ?? console.error)(e); } const handleMessage = (data, isBinary) => { const datas = Array.isArray(data) ? data : [data]; for (const data of datas) try { events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === "string" ? data : Buffer.from(data).toString("utf-8") }), ctx); } catch (e) { (options?.onError ?? console.error)(e); } }; ws.off("message", bufferMessage); for (const message of messagesReceivedInStarting) handleMessage(...message); ws.on("message", (data, isBinary) => { handleMessage(data, isBinary); }); ws.on("close", (code, reason) => { try { events?.onClose?.(new CloseEvent("close", { code, reason: reason.toString() }), ctx); } catch (e) { (options?.onError ?? console.error)(e); } }); ws.on("error", (error) => { try { events?.onError?.(new ErrorEvent("error", { error }), ctx); } catch (e) { (options?.onError ?? console.error)(e); } }); })(); return new Response();});
//#endregion//#region src/server.tsconst createAdaptorServer = (options) => { const fetchCallback = options.fetch; const requestListener = getRequestListener(fetchCallback, { hostname: options.hostname, overrideGlobalObjects: options.overrideGlobalObjects, autoCleanupIncoming: options.autoCleanupIncoming }); const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener); if (options.websocket && options.websocket.server) { if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option"); setupWebSocket({ server, fetchCallback, wss: options.websocket.server }); } return server;};const serve = (options, listeningListener) => { const server = createAdaptorServer(options); server.listen(options?.port ?? 3e3, options.hostname, () => { const serverInfo = server.address(); listeningListener && listeningListener(serverInfo); }); return server;};
//#endregionexport { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });const require_utils_stream = require('./utils/stream.cjs');let hono_utils_mime = require("hono/utils/mime");let node_fs = require("node:fs");let node_path = require("node:path");
//#region src/serve-static.tsconst 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;const ENCODINGS = { br: ".br", zstd: ".zst", gzip: ".gz"};const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);const getStats = (path) => { let stats; try { stats = (0, node_fs.statSync)(path); } catch {} return stats;};const BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\d*)-(\d*)$/;const parseByteRange = (range) => { const match = range.match(BYTE_RANGE_PATTERN); if (!match) return; const [, start, end] = match; if (start === "") return { type: "suffix", length: Number(end) }; if (end === "") return { type: "open-ended", start: Number(start) }; return { type: "bounded", start: Number(start), end: Number(end) };};const resolveByteRange = (spec, size) => { if (size === 0) return; if (spec.type === "suffix") { if (spec.length === 0) return; return { start: Math.max(size - spec.length, 0), end: size - 1 }; } const end = spec.type === "bounded" ? Math.min(spec.end, size - 1) : size - 1; if (spec.start >= size || spec.start > end) return; return { start: spec.start, end };};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 serveStatic = (options = { root: "" }) => { const root = options.root || ""; const optionPath = options.path; if (root !== "" && !(0, 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(); if (c.req.method !== "GET" && c.req.method !== "HEAD") return next(); let filename; if (optionPath) filename = optionPath; else try { filename = tryDecodeURI(c.req.path); if (c.req.path.includes("%") && (!options.allowPercentInPath || filename !== c.req.path.replace(/%25/g, "%"))) throw new Error(); if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) throw new Error(); } catch { await options.onNotFound?.(c.req.path, c); return next(); } let path = (0, 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, node_path.join)(path, indexFile); stats = getStats(path); } if (!stats) { await options.onNotFound?.(path, c); return next(); } const mimeType = (0, hono_utils_mime.getMimeType)(path); c.header("Content-Type", mimeType || "application/octet-stream"); if (options.precompressed && (!mimeType || mimeType === "application/octet-stream" || 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") || ""; c.header("Last-Modified", stats.mtime.toUTCString()); if (c.req.method === "HEAD") { 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(require_utils_stream.createStreamBody((0, node_fs.createReadStream)(path)), 200); } else { c.header("Accept-Ranges", "bytes"); const resolvedRange = resolveByteRange(parseByteRange(range) ?? { type: "open-ended", start: 0 }, size); if (!resolvedRange) { c.header("Content-Range", `bytes */${size}`); result = c.body(null, 416); } else { const { start, end } = resolvedRange; const chunkSize = end - start + 1; const stream = (0, node_fs.createReadStream)(path, { start, end }); c.header("Content-Length", chunkSize.toString()); c.header("Content-Range", `bytes ${start}-${end}/${size}`); result = c.body(require_utils_stream.createStreamBody(stream), 206); } } await options.onFound?.(path, c); return result; };};
//#endregionexports.serveStatic = serveStatic;12345678910111213141516171819import { Context, Env, MiddlewareHandler } from "hono";
//#region src/serve-static.d.tstype ServeStaticOptions<E extends Env = Env> = { /** * Root path. Relative path is based on current working directory from which the app was started. */ root?: string; path?: string; index?: string; precompressed?: boolean; /** Allow percent signs in the routed request path. Defaults to false. */ allowPercentInPath?: boolean; rewriteRequestPath?: (path: string, c: Context<E>) => string; onFound?: (path: string, c: Context<E>) => void | Promise<void>; onNotFound?: (path: string, c: Context<E>) => void | Promise<void>;};declare const serveStatic: <E extends Env = any>(options?: ServeStaticOptions<E>) => MiddlewareHandler<E>;//#endregionexport { ServeStaticOptions, serveStatic };12345678910111213141516171819import { Context, Env, MiddlewareHandler } from "hono";
//#region src/serve-static.d.tstype ServeStaticOptions<E extends Env = Env> = { /** * Root path. Relative path is based on current working directory from which the app was started. */ root?: string; path?: string; index?: string; precompressed?: boolean; /** Allow percent signs in the routed request path. Defaults to false. */ allowPercentInPath?: boolean; rewriteRequestPath?: (path: string, c: Context<E>) => string; onFound?: (path: string, c: Context<E>) => void | Promise<void>; onNotFound?: (path: string, c: Context<E>) => void | Promise<void>;};declare const serveStatic: <E extends Env = any>(options?: ServeStaticOptions<E>) => MiddlewareHandler<E>;//#endregionexport { ServeStaticOptions, serveStatic };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152import { createStreamBody } from "./utils/stream.mjs";import { getMimeType } from "hono/utils/mime";import { createReadStream, existsSync, statSync } from "node:fs";import { join } from "node:path";
//#region src/serve-static.tsconst 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;const ENCODINGS = { br: ".br", zstd: ".zst", gzip: ".gz"};const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);const getStats = (path) => { let stats; try { stats = statSync(path); } catch {} return stats;};const BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\d*)-(\d*)$/;const parseByteRange = (range) => { const match = range.match(BYTE_RANGE_PATTERN); if (!match) return; const [, start, end] = match; if (start === "") return { type: "suffix", length: Number(end) }; if (end === "") return { type: "open-ended", start: Number(start) }; return { type: "bounded", start: Number(start), end: Number(end) };};const resolveByteRange = (spec, size) => { if (size === 0) return; if (spec.type === "suffix") { if (spec.length === 0) return; return { start: Math.max(size - spec.length, 0), end: size - 1 }; } const end = spec.type === "bounded" ? Math.min(spec.end, size - 1) : size - 1; if (spec.start >= size || spec.start > end) return; return { start: spec.start, end };};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 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(); if (c.req.method !== "GET" && c.req.method !== "HEAD") return next(); let filename; if (optionPath) filename = optionPath; else try { filename = tryDecodeURI(c.req.path); if (c.req.path.includes("%") && (!options.allowPercentInPath || filename !== c.req.path.replace(/%25/g, "%"))) throw new Error(); if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.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 || mimeType === "application/octet-stream" || 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") || ""; c.header("Last-Modified", stats.mtime.toUTCString()); if (c.req.method === "HEAD") { 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"); const resolvedRange = resolveByteRange(parseByteRange(range) ?? { type: "open-ended", start: 0 }, size); if (!resolvedRange) { c.header("Content-Range", `bytes */${size}`); result = c.body(null, 416); } else { const { start, end } = resolvedRange; const chunkSize = end - start + 1; const stream = createReadStream(path, { start, end }); c.header("Content-Length", chunkSize.toString()); c.header("Content-Range", `bytes ${start}-${end}/${size}`); result = c.body(createStreamBody(stream), 206); } } await options.onFound?.(path, c); return result; };};
//#endregionexport { serveStatic };12345678Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });const require_constants = require('../constants-BXAKTxRC.cjs');
//#region src/utils/response.tsconst RESPONSE_ALREADY_SENT = new Response(null, { headers: { [require_constants.X_ALREADY_SENT]: "true" } });
//#endregionexports.RESPONSE_ALREADY_SENT = RESPONSE_ALREADY_SENT;1234//#region src/utils/response.d.tsdeclare const RESPONSE_ALREADY_SENT: Response;//#endregionexport { RESPONSE_ALREADY_SENT };1234//#region src/utils/response.d.tsdeclare const RESPONSE_ALREADY_SENT: Response;//#endregionexport { RESPONSE_ALREADY_SENT };1234567import { t as X_ALREADY_SENT } from "../constants-BLSFu_RU.mjs";
//#region src/utils/response.tsconst RESPONSE_ALREADY_SENT = new Response(null, { headers: { [X_ALREADY_SENT]: "true" } });
//#endregionexport { RESPONSE_ALREADY_SENT };1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });let node_stream = require("node:stream");let node_process = require("node:process");
//#region src/utils/stream.tsconst pr54206Applied = () => { const [major, minor] = node_process.versions.node.split(".").map((component) => parseInt(component)); return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;};const useReadableToWeb = pr54206Applied();const createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => { if (useNativeReadableToWeb) return node_stream.Readable.toWeb(stream); let controller; let settled = false; const cleanup = () => { stream.off("data", onData); stream.off("error", onError); stream.off("end", onTerminate); stream.off("close", onTerminate); }; const settle = (callback) => { if (settled) return; settled = true; cleanup(); callback?.(); }; const onData = (chunk) => { if (settled || !controller) return; controller.enqueue(chunk); if ((controller.desiredSize ?? 0) <= 0) stream.pause(); }; const onError = (error) => { settle(() => { controller?.error(error); }); }; const onTerminate = () => { settle(() => { controller?.close(); }); }; return new ReadableStream({ start(streamController) { controller = streamController; stream.on("data", onData); stream.on("error", onError); stream.on("end", onTerminate); stream.on("close", onTerminate); stream.pause(); }, pull() { if (!settled) stream.resume(); }, cancel() { settle(); const ignoreError = () => {}; stream.on("error", ignoreError); stream.once("close", () => stream.off("error", ignoreError)); stream.destroy(); } });};
//#endregionexports.createStreamBody = createStreamBody;123456import { ReadStream } from "node:fs";
//#region src/utils/stream.d.tsdeclare const createStreamBody: (stream: ReadStream, useNativeReadableToWeb?: boolean) => ReadableStream<Uint8Array>;//#endregionexport { createStreamBody };123456import { ReadStream } from "node:fs";
//#region src/utils/stream.d.tsdeclare const createStreamBody: (stream: ReadStream, useNativeReadableToWeb?: boolean) => ReadableStream<Uint8Array>;//#endregionexport { createStreamBody };12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import { Readable } from "node:stream";import { versions } from "node:process";
//#region src/utils/stream.tsconst pr54206Applied = () => { const [major, minor] = versions.node.split(".").map((component) => parseInt(component)); return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;};const useReadableToWeb = pr54206Applied();const createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => { if (useNativeReadableToWeb) return Readable.toWeb(stream); let controller; let settled = false; const cleanup = () => { stream.off("data", onData); stream.off("error", onError); stream.off("end", onTerminate); stream.off("close", onTerminate); }; const settle = (callback) => { if (settled) return; settled = true; cleanup(); callback?.(); }; const onData = (chunk) => { if (settled || !controller) return; controller.enqueue(chunk); if ((controller.desiredSize ?? 0) <= 0) stream.pause(); }; const onError = (error) => { settle(() => { controller?.error(error); }); }; const onTerminate = () => { settle(() => { controller?.close(); }); }; return new ReadableStream({ start(streamController) { controller = streamController; stream.on("data", onData); stream.on("error", onError); stream.on("end", onTerminate); stream.on("close", onTerminate); stream.pause(); }, pull() { if (!settled) stream.resume(); }, cancel() { settle(); const ignoreError = () => {}; stream.on("error", ignoreError); stream.once("close", () => stream.off("error", ignoreError)); stream.destroy(); } });};
//#endregionexport { createStreamBody };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128{ "name": "@hono/node-server", "version": "2.1.11", "description": "Node.js Adapter for Hono", "main": "dist/index.mjs", "type": "module", "types": "dist/index.d.mts", "files": [ "dist" ], "exports": { ".": { "import": { "types": "./dist/index.d.mts", "default": "./dist/index.mjs" }, "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } }, "./serve-static": { "import": { "types": "./dist/serve-static.d.mts", "default": "./dist/serve-static.mjs" }, "require": { "types": "./dist/serve-static.d.cts", "default": "./dist/serve-static.cjs" } }, "./utils/*": { "import": { "types": "./dist/utils/*.d.mts", "default": "./dist/utils/*.mjs" }, "require": { "types": "./dist/utils/*.d.cts", "default": "./dist/utils/*.cjs" } }, "./conninfo": { "import": { "types": "./dist/conninfo.d.mts", "default": "./dist/conninfo.mjs" }, "require": { "types": "./dist/conninfo.d.cts", "default": "./dist/conninfo.cjs" } }, "./early-hints": { "import": { "types": "./dist/early-hints.d.mts", "default": "./dist/early-hints.mjs" }, "require": { "types": "./dist/early-hints.d.cts", "default": "./dist/early-hints.cjs" } } }, "typesVersions": { "*": { ".": [ "./dist/index.d.mts" ], "serve-static": [ "./dist/serve-static.d.mts" ], "utils/*": [ "./dist/utils/*.d.mts" ], "conninfo": [ "./dist/conninfo.d.mts" ], "early-hints": [ "./dist/early-hints.d.mts" ] } }, "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/honojs/node-server.git" }, "homepage": "https://github.com/honojs/node-server", "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)", "publishConfig": { "registry": "https://registry.npmjs.org", "access": "public", "provenance": true }, "engines": { "node": ">=20" }, "devDependencies": { "@hono/eslint-config": "^1.0.1", "@types/node": "^20.10.0", "@types/ws": "^8.18.1", "@whatwg-node/fetch": "^0.9.14", "eslint": "^9.10.0", "hono": "^4.13.9", "np": "^11.2.1", "prettier": "^3.2.4", "publint": "^0.3.18", "tsdown": "^0.20.3", "typescript": "^5.3.2", "vitest": "^4.0.18", "ws": "^8.19.0" }, "peerDependencies": { "hono": "^4 || ^5.0.0-0" }, "scripts": { "test": "vitest", "build": "tsdown --external hono", "watch": "tsdown --watch", "postbuild": "publint", "prerelease": "pnpm run build && pnpm run test --run", "release": "np --no-publish", "typecheck": "tsc --noEmit", "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}\"" }}123456789101112131415161718192021MIT License
Copyright (c) 2024 Anthropic, PBC
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178# MCP TypeScript SDK [](https://www.npmjs.com/package/@modelcontextprotocol/sdk) [](https://github.com/modelcontextprotocol/typescript-sdk/blob/v1.x/LICENSE)
> **This is v1.x of the MCP TypeScript SDK, the maintenance line.** It implements the MCP spec up to 2025-11-25. Support for the [2026-07-28 spec](https://modelcontextprotocol.io/specification/2026-07-28) is not planned for v1.x: it is in v2, the current stable release, which> ships as separate packages, [`@modelcontextprotocol/server`](https://www.npmjs.com/package/@modelcontextprotocol/server) and [`@modelcontextprotocol/client`](https://www.npmjs.com/package/@modelcontextprotocol/client). See the> [v2 documentation](https://ts.sdk.modelcontextprotocol.io/v2/) and the [migration guide](https://ts.sdk.modelcontextprotocol.io/v2/migration/upgrade-to-v2).>> **Staying on v1.x?** It continues to receive bug fixes and security updates for at least six months after the v2 release (2026-07-27). The v1 documentation is at <https://ts.sdk.modelcontextprotocol.io/>.
<details><summary>Table of Contents</summary>
- [Overview](#overview)- [Installation](#installation)- [Quick Start](#quick-start)- [Core Concepts](#core-concepts)- [Examples](#examples)- [Documentation](#documentation)- [Contributing](#contributing)- [License](#license)
</details>
## 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 2025-11-25 MCP specification](https://modelcontextprotocol.io/specification/2025-11-25), 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
```bashnpm 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/protocol.md](docs/protocol.md) – protocol features: ping, progress, cancellation, pagination, capability negotiation, and JSON Schema. - [docs/faq.md](docs/faq.md) – environment and troubleshooting FAQs (including Node.js Web Crypto support).- External references: - [V1 API reference](https://modelcontextprotocol.github.io/typescript-sdk/) - [V2 API reference](https://modelcontextprotocol.github.io/typescript-sdk/v2/) - [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 <https://github.com/modelcontextprotocol/typescript-sdk>.
## License
This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231/** * 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<string, unknown>; alg: string; audience?: string | URL; lifetimeSeconds?: number; claims?: Record<string, unknown>;}): 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; /** * Space-separated scopes values requested by the client. */ scope?: string; /** * The issuer URL of the authorization server these credentials were registered with. * When set, `auth()` only presents them to that authorization server and throws if the * MCP server advertises a different URL (one trailing slash aside). * * Omitting it is deprecated: the credentials then go to whichever authorization server * the MCP server advertises first. */ expectedIssuer?: 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', * expectedIssuer: 'https://auth.example.com' * }); * * const transport = new StreamableHTTPClientTransport(serverUrl, { * authProvider: provider * }); */export declare class ClientCredentialsProvider implements OAuthClientProvider { private _tokens?; private _clientInfo; private _clientMetadata; constructor(options: ClientCredentialsProviderOptions & { expectedIssuer: string; }); /** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */ 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<string, unknown>; /** * 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; /** * Space-separated scopes values requested by the client. */ scope?: string; /** * The issuer URL of the authorization server these credentials were registered with. * When set, `auth()` only presents them to that authorization server and throws if the * MCP server advertises a different URL (one trailing slash aside). * * Omitting it is deprecated: the credentials then go to whichever authorization server * the MCP server advertises first. */ expectedIssuer?: string;}/** * 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', * expectedIssuer: 'https://auth.example.com' * }); * * const transport = new StreamableHTTPClientTransport(serverUrl, { * authProvider: provider * }); */export declare class PrivateKeyJwtProvider implements OAuthClientProvider { private _tokens?; private _clientInfo; private _clientMetadata; addClientAuthentication: AddClientAuthentication; constructor(options: PrivateKeyJwtProviderOptions & { expectedIssuer: string; }); /** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */ 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; /** * Space-separated scopes values requested by the client. */ scope?: string; /** * The issuer URL of the authorization server these credentials were registered with. * When set, `auth()` only presents them to that authorization server and throws if the * MCP server advertises a different URL (one trailing slash aside). * * Omitting it is deprecated: the credentials then go to whichever authorization server * the MCP server advertises first. */ expectedIssuer?: 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 & { expectedIssuer: string; }); /** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */ 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.map1{"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;AAoBD;;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AAc;IAC9B,OAAO,CAAC,WAAW,CAAyB;IAC5C,OAAO,CAAC,eAAe,CAAsB;IAC7C,uBAAuB,EAAE,uBAAuB,CAAC;gBAErC,OAAO,EAAE,kCAAkC,GAAG;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE;IACpF,uGAAuG;gBAC3F,OAAO,EAAE,kCAAkC;IAqBvD,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"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320"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'); };}/** * The `issuer` stamp for constructor-supplied client information. Omitting `expectedIssuer` is * deprecated: nothing else says which authorization server such credentials belong to. */function checkedExpectedIssuer(expectedIssuer) { if (expectedIssuer === undefined) { // eslint-disable-next-line no-console console.warn('[mcp-sdk] Omitting `expectedIssuer` is deprecated. Without it, the MCP server decides which authorization ' + "server receives this client's credentials; pass your authorization server's issuer URL as " + '`expectedIssuer` so they are only sent there.'); } else if (typeof expectedIssuer !== 'string' || !expectedIssuer) { throw new Error("expectedIssuer must be the authorization server's issuer URL"); } return expectedIssuer;}/** * 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', * expectedIssuer: 'https://auth.example.com' * }); * * const transport = new StreamableHTTPClientTransport(serverUrl, { * authProvider: provider * }); */class ClientCredentialsProvider { constructor(options) { this._clientInfo = { client_id: options.clientId, client_secret: options.clientSecret, issuer: checkedExpectedIssuer(options.expectedIssuer) }; this._clientMetadata = { client_name: options.clientName ?? 'client-credentials-client', redirect_uris: [], grant_types: ['client_credentials'], token_endpoint_auth_method: 'client_secret_basic', scope: options.scope }; } 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', * expectedIssuer: 'https://auth.example.com' * }); * * const transport = new StreamableHTTPClientTransport(serverUrl, { * authProvider: provider * }); */class PrivateKeyJwtProvider { constructor(options) { this._clientInfo = { client_id: options.clientId, issuer: checkedExpectedIssuer(options.expectedIssuer) }; this._clientMetadata = { client_name: options.clientName ?? 'private-key-jwt-client', redirect_uris: [], grant_types: ['client_credentials'], token_endpoint_auth_method: 'private_key_jwt', scope: options.scope }; 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, issuer: checkedExpectedIssuer(options.expectedIssuer) }; this._clientMetadata = { client_name: options.clientName ?? 'static-private-key-jwt-client', redirect_uris: [], grant_types: ['client_credentials'], token_endpoint_auth_method: 'private_key_jwt', scope: options.scope }; 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.map1{"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;YAC3C,MAAM,IAAI,SAAS,CACf,qNAAqN,CACxN,CAAC;QACN,CAAC;QAED,MAAM,IAAI,GAAG,wDAAa,MAA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AC7C,IAAI,CAAC,uBAAuB,GAAG,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE;YACtD,MAAM,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;AAtED,kEAsEC"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473import { 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<void>;/** * 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<string>; /** * Loads information about this OAuth client, as registered already with the * server, or returns `undefined` if the client is not registered with the * server. * * A provider that returns pre-registered credentials should include `issuer`, the URL of * the authorization server they were registered with; {@linkcode auth} then does not * present them to any other. */ clientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>; /** * 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). * * The object carries `issuer`, the authorization server it was obtained from. Store it * unchanged so that {@linkcode auth} does not reuse the registration with a different one. * Client information stored without `issuer` is passed here, with it, after its first successful use. */ saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise<void>; /** * Loads any existing OAuth tokens for the current session, or returns * `undefined` if there are no saved tokens. */ tokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>; /** * Stores new OAuth tokens for the current session, after a successful * authorization. * * The object carries `issuer`, the authorization server that issued the tokens. Store it * unchanged so that {@linkcode auth} does not present the refresh token to a different one. */ saveTokens(tokens: OAuthTokens): void | Promise<void>; /** * Invoked to redirect the user agent to the given URL to begin the authorization flow. */ redirectToAuthorization(authorizationUrl: URL): void | Promise<void>; /** * Saves a PKCE code verifier for the current session, before redirecting to * the authorization flow. */ saveCodeVerifier(codeVerifier: string): void | Promise<void>; /** * Loads the PKCE code verifier for the current session, necessary to validate * the authorization result. */ codeVerifier(): string | Promise<string>; /** * 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<URL | undefined>; /** * 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' | 'discovery'): void | Promise<void>; /** * 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<URLSearchParams | undefined> | undefined; /** * Saves the OAuth discovery state after RFC 9728 and authorization server metadata * discovery. Providers can persist this state to avoid redundant discovery requests * on subsequent {@linkcode auth} calls. * * This state can also be provided out-of-band (e.g., from a previous session or * external configuration) to bootstrap the OAuth flow without discovery. * * Called by {@linkcode auth} after successful discovery. */ saveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>; /** * Returns previously saved discovery state, or `undefined` if none is cached. * * When available, {@linkcode auth} restores the discovery state (authorization server * URL, resource metadata, etc.) instead of performing RFC 9728 discovery, reducing * latency on subsequent calls. * * Providers should clear cached discovery state on repeated authentication failures * (via {@linkcode invalidateCredentials} with scope `'discovery'` or `'all'`) to allow * re-discovery in case the authorization server has changed. */ discoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;}/** * Discovery state that can be persisted across sessions by an {@linkcode OAuthClientProvider}. * * Contains the results of RFC 9728 protected resource metadata discovery and * authorization server metadata discovery. Persisting this state avoids * redundant discovery HTTP requests on subsequent {@linkcode auth} calls. */export interface OAuthDiscoveryState extends OAuthServerInfo { /** The URL at which the protected resource metadata was found, if available. */ resourceMetadataUrl?: string;}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<OAuthError>;/** * 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<AuthResult>;/** * 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;/** * Selects the RFC 8707 resource indicator for an MCP server: the provider's * {@linkcode OAuthClientProvider.validateResourceURL | validateResourceURL} result when * implemented, otherwise the protected resource metadata's `resource` (checked against the * server URL with `checkResourceAllowed`), or `undefined` when there is no metadata. * * The result is a parsed `URL`, so a pathless indicator such as `https://example.com` has * the `href` `https://example.com/`. {@linkcode auth} therefore sends the metadata string * verbatim instead of this URL's `href` (#1968); callers that emit the `resource` * parameter themselves should do the same. */export declare function selectResourceURL(serverUrl: string | URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise<URL | undefined>;/** * 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<OAuthProtectedResourceMetadata>;/** * 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<OAuthMetadata | undefined>;/** * 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<AuthorizationServerMetadata | undefined>;/** * Result of {@linkcode discoverOAuthServerInfo}. */export interface OAuthServerInfo { /** * The authorization server URL, either discovered via RFC 9728 * or derived from the MCP server URL as a fallback. */ authorizationServerUrl: string; /** * The authorization server metadata (endpoints, capabilities), * or `undefined` if metadata discovery failed. */ authorizationServerMetadata?: AuthorizationServerMetadata; /** * The OAuth 2.0 Protected Resource Metadata from RFC 9728, * or `undefined` if the server does not support it. */ resourceMetadata?: OAuthProtectedResourceMetadata;}/** * Discovers the authorization server for an MCP server following * {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected * Resource Metadata), with fallback to treating the server URL as the * authorization server. * * This function combines two discovery steps into one call: * 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the * authorization server URL (RFC 9728). * 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery). * * Use this when you need the authorization server metadata for operations outside the * {@linkcode auth} orchestrator, such as token refresh or token revocation. * * @param serverUrl - The MCP resource server URL * @param opts - Optional configuration * @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint * @param opts.fetchFn - Custom fetch function for HTTP requests * @returns Authorization server URL, metadata, and resource metadata (if available) */export declare function discoverOAuthServerInfo(serverUrl: string | URL, opts?: { resourceMetadataUrl?: URL; fetchFn?: FetchLike;}): Promise<OAuthServerInfo>;/** * 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?: string | 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?: string | URL; addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; fetchFn?: FetchLike;}): Promise<OAuthTokens>;/** * 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?: string | URL; addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; fetchFn?: FetchLike;}): Promise<OAuthTokens>;/** * 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?: string | URL; /** Authorization code for the default authorization_code grant flow */ authorizationCode?: string; fetchFn?: FetchLike;}): Promise<OAuthTokens>;/** * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. * * If `scope` is provided, it overrides `clientMetadata.scope` in the registration * request body. This allows callers to apply the Scope Selection Strategy (SEP-835) * consistently across both DCR and the subsequent authorization request. */export declare function registerClient(authorizationServerUrl: string | URL, { metadata, clientMetadata, scope, fetchFn }: { metadata?: AuthorizationServerMetadata; clientMetadata: OAuthClientMetadata; scope?: string; fetchFn?: FetchLike;}): Promise<OAuthClientInformationFull>;export {};//# sourceMappingURL=auth.d.ts.map1{"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,EAAyC,MAAM,wBAAwB,CAAC;AAE1F;;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;;;;;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AC;IACrB,QAAQ,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;IACxB,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,MAAM,GAAG,GAAG,CAAC;IACxB,uEAAuE;IACvE,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,OAAO,CAAC,EAAE,SAAS,CAAC;CAClB,GACP,OAAO,CAAC,WAAW,CAAC,CA2CtB;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAChC,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,EACI,QAAQ,EACR,cAAc,EACd,KAAK,EACL,OAAO,EACV,EAAE;IACC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,cAAc,EAAE,mBAAmB,CAAC;IACpC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,0BAA0B,CAAC,CA6BrC"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046"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.discoverOAuthServerInfo = discoverOAuthServerInfo;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");const transport_js_1 = require("../shared/transport.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; // Prefer the method returned by the server during client registration, if valid. // When server metadata is present we also require the method to be listed as supported; // when supportedMethods is empty (metadata omitted the field) the DCR hint stands alone. if ('token_endpoint_auth_method' in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) { return clientInformation.token_endpoint_auth_method; } // If server metadata omits token_endpoint_auth_methods_supported, RFC 8414 §2 says the // default is client_secret_basic. RFC 6749 §2.3.1 also requires servers to support HTTP // Basic authentication for clients with a secret, making it the safest default. if (supportedMethods.length === 0) { return hasClientSecret ? 'client_secret_basic' : 'none'; } // 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 redirect = input instanceof Response ? (0, transport_js_1.unfollowedRedirect)(input, input.url) : undefined; const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}${redirect ?? `Invalid OAuth error response: ${error}. Raw body: ${body}`}`; return new errors_js_1.ServerError(errorMessage); }}/** * Compares two authorization server identifiers, tolerating a single trailing `/` * difference (`String(new URL(...))` is slash-suffixed, advertised values often are not). */function issuersMatch(a, b) { let [x, y] = [a, b]; try { // Two URLs are compared as parsed, so the spelling of scheme, host or default port does not matter. [x, y] = [new URL(a).href, new URL(b).href]; } catch { // Not two URLs: compared as written. } return x === y || (x.endsWith('/') && x.slice(0, -1) === y) || (y.endsWith('/') && y.slice(0, -1) === x);}/** * {@linkcode auth} stamps everything it passes to `saveClientInformation` / `saveTokens` with * `issuer`, the authorization server URL used for discovery. This returns `stored` unless its * stamp names a different authorization server, in which case the caller behaves as if nothing * were stored. A value without a stamp (saved by an earlier version) is returned as-is, and * is stamped once this authorization server has accepted it. */function discardIfIssuerMismatch(stored, issuer) { // `null`: a `JSON.parse(storage.getItem(...))`-style getter with nothing stored. if (!stored) return undefined; // A stamp that is not a string (raw storage) counts as no stamp. if (typeof stored.issuer !== 'string') return stored.issuer == null ? stored : { ...stored, issuer: undefined }; return issuersMatch(stored.issuer, issuer) ? stored : undefined;}// `issuer` is added by the client when it stores a value; authorization server responses are parsed without it.const TokenResponseSchema = auth_js_2.OAuthTokensSchema.omit({ issuer: true });const RegistrationResponseSchema = auth_js_2.OAuthClientInformationFullSchema.omit({ issuer: true });function boundElsewhereError(stored, issuer) { return new Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. ` + 'Clear the stored client information, or correct `expectedIssuer`, if the authorization server has moved.');}/** * 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 }) { // Check if the provider has cached discovery state to skip discovery const cachedState = await provider.discoveryState?.(); let resourceMetadata; let authorizationServerUrl; let metadata; // If resourceMetadataUrl is not provided, try to load it from cached state // This handles browser redirects where the URL was saved before navigation let effectiveResourceMetadataUrl = resourceMetadataUrl; if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) { effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl); } if (cachedState?.authorizationServerUrl) { // Restore discovery state from cache authorizationServerUrl = cachedState.authorizationServerUrl; resourceMetadata = cachedState.resourceMetadata; metadata = cachedState.authorizationServerMetadata ?? (await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn })); // If resource metadata wasn't cached, try to fetch it for selectResourceURL if (!resourceMetadata) { try { resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn); } catch { // RFC 9728 not available — selectResourceURL will handle undefined } } // Re-save if we enriched the cached state with missing metadata if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) { await provider.saveDiscoveryState?.({ authorizationServerUrl: String(authorizationServerUrl), resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), resourceMetadata, authorizationServerMetadata: metadata }); } } else { // Full discovery via RFC 9728 const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn }); authorizationServerUrl = serverInfo.authorizationServerUrl; metadata = serverInfo.authorizationServerMetadata; resourceMetadata = serverInfo.resourceMetadata; // Persist discovery state for future use // TODO: resourceMetadataUrl is only populated when explicitly provided via options // or loaded from cached state. The URL derived internally by // discoverOAuthProtectedResourceMetadata() is not captured back here. await provider.saveDiscoveryState?.({ authorizationServerUrl: String(authorizationServerUrl), resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), resourceMetadata, authorizationServerMetadata: metadata }); } // Binding key for stored credentials: the authorization server URL that discovery used // (advertised by the resource server, restored from discoveryState(), or the legacy // resource-origin fallback). `metadata.issuer` is deliberately not used: this version does // not check that the metadata document echoes the URL it was fetched from. const issuer = String(authorizationServerUrl); // Send the metadata's resource indicator verbatim: `selectResourceURL` returns a parsed // `URL`, and `URL.href` appends "/" to a pathless indicator such as `https://example.com`, // which exact-match authorization servers reject (#1968). A URL returned by the // provider's own `validateResourceURL` is used as returned. const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata); const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource; // Apply scope selection strategy (SEP-835): // 1. WWW-Authenticate scope (passed via `scope` param) // 2. PRM scopes_supported // 3. Client metadata scope (user-configured fallback) // The resolved scope is used consistently for both DCR and the authorization request. const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope; // Handle client registration if needed. Client information stamped for a different // authorization server reads back as `undefined`, so the flow re-registers exactly as if // nothing were stored. const storedClientInformation = await Promise.resolve(provider.clientInformation()); let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer); const canRegisterAgain = provider.saveClientInformation !== undefined && !!provider.redirectUrl; if (storedClientInformation && !clientInformation && !canRegisterAgain) { // Pre-registered credentials, or a non-interactive client running on configured // credentials: neither can be re-created by registering with this authorization server. throw boundElsewhereError(storedClientInformation, issuer); } // Saved by an earlier version: bound to the first authorization server that accepts it. const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : undefined; const bindClientInformation = async () => { try { if (unstampedClientInformation) await provider.saveClientInformation?.({ ...unstampedClientInformation, issuer }); } catch { // A provider that only expects this call after a registration keeps working, unbound. } }; 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, issuer }; 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, scope: resolvedScope, fetchFn }); clientInformation = { ...fullInformation, issuer }; await provider.saveClientInformation(clientInformation); } } // 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 bindClientInformation(); await provider.saveTokens({ ...tokens, issuer }); return 'AUTHORIZED'; } // A refresh token stamped for a different authorization server reads back as `undefined`, // so it is never posted to this one's token endpoint. const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer); if (tokens?.refresh_token && tokens.issuer == null) { // eslint-disable-next-line no-console console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that " + 'does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and ' + 'saveClientInformation() receive unchanged.'); } // 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 bindClientInformation(); await provider.saveTokens({ ...newTokens, issuer }); 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: resolvedScope, 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; }}/** * Selects the RFC 8707 resource indicator for an MCP server: the provider's * {@linkcode OAuthClientProvider.validateResourceURL | validateResourceURL} result when * implemented, otherwise the protected resource metadata's `resource` (checked against the * server URL with `checkResourceAllowed`), or `undefined` when there is no metadata. * * The result is a parsed `URL`, so a pathless indicator such as `https://example.com` has * the `href` `https://example.com/`. {@linkcode auth} therefore sends the metadata string * verbatim instead of this URL's `href` (#1968); callers that emit the `resource` * parameter themselves should do the same. */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 (0, transport_js_1.fetchWithinOrigin)(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.ok && 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, or a redirect that was not followed. if (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;}/** * Discovers the authorization server for an MCP server following * {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected * Resource Metadata), with fallback to treating the server URL as the * authorization server. * * This function combines two discovery steps into one call: * 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the * authorization server URL (RFC 9728). * 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery). * * Use this when you need the authorization server metadata for operations outside the * {@linkcode auth} orchestrator, such as token refresh or token revocation. * * @param serverUrl - The MCP resource server URL * @param opts - Optional configuration * @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint * @param opts.fetchFn - Custom fetch function for HTTP requests * @returns Authorization server URL, metadata, and resource metadata (if available) */async function discoverOAuthServerInfo(serverUrl, opts) { let resourceMetadata; let authorizationServerUrl; try { resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn); if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { authorizationServerUrl = resourceMetadata.authorization_servers[0]; } } catch { // RFC 9728 not supported -- fall back to treating the server URL as the authorization server } // If we don't get a valid authorization server from protected resource metadata, // fall back to the legacy MCP spec behavior: MCP server base URL acts as the authorization server if (!authorizationServerUrl) { authorizationServerUrl = String(new URL('/', serverUrl)); } const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn }); return { authorizationServerUrl, authorizationServerMetadata, resourceMetadata };}function resourceIndicatorToString(resource) { return typeof resource === 'string' ? resource : resource.href;}/** * 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', resourceIndicatorToString(resource)); } 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', resourceIndicatorToString(resource)); } 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 (0, transport_js_1.fetchWithinOrigin)(fetchFn ?? fetch)(tokenUrl, { method: 'POST', headers, body: tokenRequestParams }); if (!response.ok) { throw await parseErrorResponse(response); } return TokenResponseSchema.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 } = {}) { // Nothing is sent to an authorization server other than the one the client information is stamped for. const readClientInformation = async () => { const storedClientInformation = await provider.clientInformation(); const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl)); if (storedClientInformation && !checked) { throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl)); } return checked; }; let clientInformation = await readClientInformation(); 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); } // A provider may fill in its client information while the request is prepared. clientInformation ?? (clientInformation = await readClientInformation()); return executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication: provider.addClientAuthentication, resource, fetchFn });}/** * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. * * If `scope` is provided, it overrides `clientMetadata.scope` in the registration * request body. This allows callers to apply the Scope Selection Strategy (SEP-835) * consistently across both DCR and the subsequent authorization request. */async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, 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 (0, transport_js_1.fetchWithinOrigin)(fetchFn ?? fetch)(registrationUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...clientMetadata, ...(scope !== undefined ? { scope } : {}) }) }); if (!response.ok) { throw await parseErrorResponse(response); } return RegistrationResponseSchema.parse(await response.json());}//# sourceMappingURL=auth.js.map1{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":";;;;;;AAiRA,wDAqCC;AA+ED,gDAeC;AAiDD,oBAyBC;AA4OD,gCAQC;AAaD,8CAuBC;AAKD,oEA8BC;AA8BD,gEAsBC;AAQD,wFAoBC;AAgGD,sDAsCC;AAQD,gDAgDC;A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,QAAQ,CAAC,EAAE,EAAE,CAAC;QACf,MAAM,MAAM,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,0BAA0B,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;AACnE,CAAC"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591import { 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<typeof CustomRequestSchema> * type CustomNotification = z.infer<typeof CustomNotificationSchema> * type CustomResult = z.infer<typeof CustomResultSchema> * * // Create typed client * const client = new Client<CustomRequest, CustomNotification, CustomResult>({ * name: "CustomClient", * version: "1.0.0" * }) * ``` */export declare class Client<RequestT extends Request = Request, NotificationT extends Notification = Notification, ResultT extends Result = Result> extends Protocol<ClientRequest | RequestT, ClientNotification | NotificationT, ClientResult | ResultT> { 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<RequestT, NotificationT, ResultT>; }; /** * 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<T extends AnyObjectSchema>(requestSchema: T, handler: (request: SchemaOutput<T>, extra: RequestHandlerExtra<ClientRequest | RequestT, ClientNotification | NotificationT>) => ClientResult | ResultT | Promise<ClientResult | ResultT>): void; protected assertCapability(capability: keyof ServerCapabilities, method: string): void; connect(transport: Transport, options?: RequestOptions): Promise<void>; /** * 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<string, unknown> | undefined; } | { type: "image"; data: string; mimeType: string; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: Record<string, unknown> | undefined; } | { type: "audio"; data: string; mimeType: string; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: Record<string, unknown> | undefined; } | { type: "resource"; resource: { uri: string; text: string; mimeType?: string | undefined; _meta?: Record<string, unknown> | undefined; } | { uri: string; blob: string; mimeType?: string | undefined; _meta?: Record<string, unknown> | undefined; }; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: Record<string, unknown> | undefined; } | { uri: string; name: string; type: "resource_link"; description?: string | undefined; mimeType?: string | undefined; size?: number | 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; size?: number | 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<string, unknown> | undefined; } | { uri: string; blob: string; mimeType?: string | undefined; _meta?: Record<string, unknown> | 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<string, unknown> | undefined; } | { type: "image"; data: string; mimeType: string; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: Record<string, unknown> | undefined; } | { type: "audio"; data: string; mimeType: string; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: Record<string, unknown> | undefined; } | { type: "resource"; resource: { uri: string; text: string; mimeType?: string | undefined; _meta?: Record<string, unknown> | undefined; } | { uri: string; blob: string; mimeType?: string | undefined; _meta?: Record<string, unknown> | undefined; }; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: Record<string, unknown> | undefined; } | { uri: string; name: string; type: "resource_link"; description?: string | undefined; mimeType?: string | undefined; size?: number | 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<string, unknown> | 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<string, object> | undefined; required?: string[] | undefined; }; name: string; description?: string | undefined; outputSchema?: { [x: string]: unknown; type: "object"; properties?: Record<string, object> | 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<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; }>; /** * Set up a single list changed handler. * @internal */ private _setupListChangedHandler; sendRootsListChanged(): Promise<void>;}//# sourceMappingURL=index.d.ts.map1{"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,KAAK,MAAM,EACd,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAuC,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AACvG,OAAO,EAAE,eAAe,EAAE,YAAY,EAA8C,MAAM,yBAAyB,CAAC;AACpH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAiD1E;;;;;;;;;GASG;AACH,wBAAgB,4BAA4B,CAAC,YAAY,EAAE,kBAAkB,CAAC,aAAa,CAAC,GAAG;IAC3F,gBAAgB,E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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618"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<typeof CustomRequestSchema> * type CustomNotification = z.infer<typeof CustomNotificationSchema> * type CustomResult = z.infer<typeof CustomResultSchema> * * // Create typed client * const client = new Client<CustomRequest, CustomNotification, CustomResult>({ * 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'); } const methodValue = (0, zod_compat_js_1.getLiteralValue)(methodSchema); 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.map1{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":";;;AAoHA,oEAgBC;AApID,uDAA+G;AAG/G,0CAiDqB;AACrB,mEAAuE;AAEvE,2DAAoH;AAEpH,+DAA0E;AAC1E,iEAAoH;AAEpH;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,MAAkC,EAAE,IAAa;IAC/E,IAAI,CAAC,MAAM,IAAI,IAAI,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO;IAEjE,2BAA2B;IAC3B,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,UAAU,IAAI,OAAO,MAAM,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;QACzF,MAAM,GAAG,GAAG,IAA+B,CAAC;QAC5C,MAAM,KAAK,GAAG,MAAM,CAAC,UAAoE,CAAC;QAC1F,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACnC,MAAM,UAAU,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;YAC9B,+DAA+D;YAC/D,IAAI,GAAG,CAAC,GAAG,CAAC,KAAK,SAAS,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,UAAU,EAAE,SAAS,CAAC,EAAE,CAAC;gBACxF,GAAG,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,OAAO,CAAC;YAClC,CAAC;YACD,8CAA8C;YAC9C,IAAI,GAAG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C;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;AAvpBD,wBAupBC"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169import { 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<Response>) => Middleware;//# sourceMappingURL=middleware.d.ts.mapREADME.md+15
dist/index.js+210-11
node_modules/.bin/node-whichAdded+1
node_modules/.bin/tscAdded+1
node_modules/.bin/tsserverAdded+1
node_modules/.package-lock.jsonAdded+1251
node_modules/@hono/node-server/LICENSEAdded+21
node_modules/@hono/node-server/README.mdAdded+450
node_modules/@hono/node-server/dist/conninfo.cjsAdded+22
node_modules/@hono/node-server/dist/conninfo.d.ctsAdded+11
node_modules/@hono/node-server/dist/conninfo.d.mtsAdded+11
node_modules/@hono/node-server/dist/conninfo.mjsAdded+20
node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjsAdded+5
node_modules/@hono/node-server/dist/constants-BXAKTxRC.cjsAdded+11
node_modules/@hono/node-server/dist/early-hints.cjsAdded+35
node_modules/@hono/node-server/dist/early-hints.d.ctsAdded+16
node_modules/@hono/node-server/dist/early-hints.d.mtsAdded+16
node_modules/@hono/node-server/dist/early-hints.mjsAdded+33
node_modules/@hono/node-server/dist/index.cjsAdded+1386
node_modules/@hono/node-server/dist/index.d.ctsAdded+101
node_modules/@hono/node-server/dist/index.d.mtsAdded+101
node_modules/@hono/node-server/dist/index.mjsAdded+1381
node_modules/@hono/node-server/dist/serve-static.cjsAdded+153
node_modules/@hono/node-server/dist/serve-static.d.ctsAdded+19
node_modules/@hono/node-server/dist/serve-static.d.mtsAdded+19
node_modules/@hono/node-server/dist/serve-static.mjsAdded+152
node_modules/@hono/node-server/dist/utils/response.cjsAdded+8
node_modules/@hono/node-server/dist/utils/response.d.ctsAdded+4
node_modules/@hono/node-server/dist/utils/response.d.mtsAdded+4
node_modules/@hono/node-server/dist/utils/response.mjsAdded+7
node_modules/@hono/node-server/dist/utils/stream.cjsAdded+65
node_modules/@hono/node-server/dist/utils/stream.d.ctsAdded+6
node_modules/@hono/node-server/dist/utils/stream.d.mtsAdded+6
node_modules/@hono/node-server/dist/utils/stream.mjsAdded+64
node_modules/@hono/node-server/package.jsonAdded+128
node_modules/@modelcontextprotocol/sdk/LICENSEAdded+21
node_modules/@modelcontextprotocol/sdk/README.mdAdded+178
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.tsAdded+231
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts.mapAdded+1
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.jsAdded+320
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js.mapAdded+1
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.tsAdded+473
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts.mapAdded+1
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.jsAdded+1046
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js.mapAdded+1
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.tsAdded+591
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts.mapAdded+1
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.jsAdded+618
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js.mapAdded+1
node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.d.tsAdded+169