@mastra/deployer 1.58.0-alpha.9 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["Http2ServerRequest","Readable","#body","#init","stream","constants","#eventInitDict","STATUS_CODES","createServer","versions","Readable","stream","path","Readable","onError","headerCharRegex","checkInvalidHeaderChar","Writable","checkInvalidHeaderChar","Buffer","RE_TE_CHUNKED","Buffer","ViewerRegistry","MASTRA_FRAMEWORK_PUBLIC_KEY$1","MastraServer$1","process","HTTPException","Tool","Hono","InMemoryTaskStore","swaggerUI","normalizeStudioBase","path","injectStudioHtmlConfig","escapeStudioHtmlValue"],"sources":["../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/index.mjs","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/utils/stream.mjs","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/serve-static.mjs","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/swagger-ui/0.5.3/e2a67d786252daef9d3d1d955111365f4d3b8b4c3d7bbe3cd9046cc5c088d984/node_modules/@hono/swagger-ui/dist/index.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/utils/errors.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/http-incoming.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/utils/types.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/internal-http.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/internal-streams-state.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/http-common.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/http-outgoing.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/http-server.js","../../../../server-adapters/hono/dist/index.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/hono-openapi/1.3.1/053f98053f08198fa5b6e0d29547d4cd5182ae4dbab8de92581c6160e3026d7d/node_modules/hono-openapi/dist/index.js","../../src/server/handlers/agent-learning.ts","../../src/server/handlers/client.ts","../../src/server/handlers/error.ts","../../src/server/handlers/health.ts","../../src/server/handlers/restart-active-runs.ts","../../src/server/handlers/root.ts","../../src/server/welcome.ts","../../src/server/index.ts"],"sourcesContent":["//#region src/utils/response/constants.ts\nconst X_ALREADY_SENT = \"x-hono-already-sent\";\n\n//#endregion\nexport { X_ALREADY_SENT as t };","import { t as X_ALREADY_SENT } from \"./constants-BLSFu_RU.mjs\";\nimport { STATUS_CODES, createServer } from \"node:http\";\nimport { Http2ServerRequest, constants } from \"node:http2\";\nimport { Readable } from \"node:stream\";\nimport { defineWebSocketHelper } from \"hono/ws\";\n\n//#region src/error.ts\nvar RequestError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.name = \"RequestError\";\n\t}\n};\n\n//#endregion\n//#region src/url.ts\nconst reValidRequestUrl = /^\\/[!#$&-;=?-\\[\\]_a-z~]*$/;\nconst reDotSegment = /\\/\\.\\.?(?:[/?#]|$)/;\nconst reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\\d{3,4}|[6-9]\\d{3}))?$/;\nconst buildUrl = (scheme, host, incomingUrl) => {\n\tconst url = `${scheme}://${host}${incomingUrl}`;\n\tif (!reValidHost.test(host)) {\n\t\tconst urlObj = new URL(url);\n\t\tif (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(\":\") ? host.replace(/:\\d+$/, \"\") : host).toLowerCase()) throw new RequestError(\"Invalid host header\");\n\t\treturn urlObj.href;\n\t} else if (incomingUrl.length === 0) return url + \"/\";\n\telse {\n\t\tif (incomingUrl.charCodeAt(0) !== 47) throw new RequestError(\"Invalid URL\");\n\t\tif (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;\n\t\treturn url;\n\t}\n};\n\n//#endregion\n//#region src/request.ts\nconst toRequestError = (e) => {\n\tif (e instanceof RequestError) return e;\n\treturn new RequestError(e.message, { cause: e });\n};\nconst GlobalRequest = global.Request;\nvar Request$1 = class extends GlobalRequest {\n\tconstructor(input, options) {\n\t\tif (typeof input === \"object\" && getRequestCache in input) {\n\t\t\tconst hasReplacementBody = options !== void 0 && \"body\" in options && options.body != null;\n\t\t\tif (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError(\"Cannot construct a Request with a Request object that has already been used.\");\n\t\t\tinput = input[getRequestCache]();\n\t\t}\n\t\tif (typeof (options?.body)?.getReader !== \"undefined\") options.duplex ??= \"half\";\n\t\tsuper(input, options);\n\t}\n};\nconst newHeadersFromIncoming = (incoming) => {\n\tconst headerRecord = [];\n\tconst rawHeaders = incoming.rawHeaders;\n\tfor (let i = 0, len = rawHeaders.length; i < len; i += 2) {\n\t\tconst key = rawHeaders[i];\n\t\tif (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);\n\t}\n\treturn new Headers(headerRecord);\n};\nconst wrapBodyStream = Symbol(\"wrapBodyStream\");\nconst byteExactEncodings = new Set([\n\t\"latin1\",\n\t\"binary\",\n\t\"hex\",\n\t\"base64\",\n\t\"base64url\"\n]);\nconst isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);\nconst bodyBufferedBeforeDisconnectKey = Symbol(\"bodyBufferedBeforeDisconnect\");\nconst bodyBufferedLengthBeforeDisconnectKey = Symbol(\"bodyBufferedLengthBeforeDisconnect\");\nconst toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? \"utf8\");\nconst isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === \"function\" && isByteExactEncoding(incoming.readableEncoding);\nconst recordBodyBufferedBeforeDisconnect = (incoming) => {\n\tif (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;\n\tconst incomingWithRecovery = incoming;\n\tincomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;\n};\nconst readBodyBufferedBeforeDisconnect = (incoming, chunks) => {\n\tif (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;\n\tconst incomingWithRecovery = incoming;\n\tif (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];\n\tlet result;\n\tconst errored = incoming.errored;\n\tif (errored && errored.code !== \"ECONNRESET\") result = errored;\n\telse if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();\n\telse {\n\t\tconst bodyChunks = chunks ?? [];\n\t\tconst chunk = incoming.read();\n\t\tif (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));\n\t\tconst buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);\n\t\tresult = buffer;\n\t\tconst contentLength = incoming.headers[\"content-length\"];\n\t\tif (typeof contentLength === \"string\" && /^\\d+$/.test(contentLength)) {\n\t\t\tconst expectedLength = Number(contentLength);\n\t\t\tif (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();\n\t\t}\n\t}\n\tincomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;\n\treturn result;\n};\nconst enqueueBufferedBody = (controller, buffered) => {\n\tif (buffered instanceof Error) {\n\t\tcontroller.error(buffered);\n\t\treturn;\n\t}\n\tif (buffered.length > 0) controller.enqueue(buffered);\n\tcontroller.close();\n};\nconst newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n\tconst init = {\n\t\tmethod,\n\t\theaders,\n\t\tsignal: abortController.signal\n\t};\n\tif (method === \"TRACE\") {\n\t\tinit.method = \"GET\";\n\t\tconst req = new Request$1(url, init);\n\t\tObject.defineProperty(req, \"method\", { get() {\n\t\t\treturn \"TRACE\";\n\t\t} });\n\t\treturn req;\n\t}\n\tif (!(method === \"GET\" || method === \"HEAD\")) if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {\n\t\tcontroller.enqueue(incoming.rawBody);\n\t\tcontroller.close();\n\t} });\n\telse if (incoming[wrapBodyStream]) {\n\t\tlet reader;\n\t\tinit.body = new ReadableStream({ async pull(controller) {\n\t\t\ttry {\n\t\t\t\tif (!reader) {\n\t\t\t\t\tconst buffered = readBodyBufferedBeforeDisconnect(incoming);\n\t\t\t\t\tif (buffered !== void 0) {\n\t\t\t\t\t\tenqueueBufferedBody(controller, buffered);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treader ||= Readable.toWeb(incoming).getReader();\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t}\n\t\t} });\n\t} else {\n\t\tconst buffered = readBodyBufferedBeforeDisconnect(incoming);\n\t\tif (buffered !== void 0) init.body = new ReadableStream({ start(controller) {\n\t\t\tenqueueBufferedBody(controller, buffered);\n\t\t} });\n\t\telse init.body = Readable.toWeb(incoming);\n\t}\n\treturn new Request$1(url, init);\n};\nconst getRequestCache = Symbol(\"getRequestCache\");\nconst requestCache = Symbol(\"requestCache\");\nconst incomingKey = Symbol(\"incomingKey\");\nconst urlKey = Symbol(\"urlKey\");\nconst methodKey = Symbol(\"methodKey\");\nconst headersKey = Symbol(\"headersKey\");\nconst abortControllerKey = Symbol(\"abortControllerKey\");\nconst getAbortController = Symbol(\"getAbortController\");\nconst abortRequest = Symbol(\"abortRequest\");\nconst bodyBufferKey = Symbol(\"bodyBuffer\");\nconst bodyReadPromiseKey = Symbol(\"bodyReadPromise\");\nconst bodyConsumedDirectlyKey = Symbol(\"bodyConsumedDirectly\");\nconst bodyLockReaderKey = Symbol(\"bodyLockReader\");\nconst abortReasonKey = Symbol(\"abortReason\");\nconst newBodyUnusableError = () => {\n\treturn /* @__PURE__ */ new TypeError(\"Body is unusable\");\n};\nconst rejectBodyUnusable = () => {\n\treturn Promise.reject(newBodyUnusableError());\n};\nconst textDecoder = new TextDecoder();\nconst consumeBodyDirectOnce = (request) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\trequest[bodyConsumedDirectlyKey] = true;\n};\nconst toArrayBuffer = (buf) => {\n\treturn buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n};\nconst contentType = (request) => {\n\treturn (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get(\"content-type\") || \"\";\n};\nconst methodTokenRegExp = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst normalizeIncomingMethod = (method) => {\n\tif (typeof method !== \"string\" || method.length === 0) return \"GET\";\n\tswitch (method) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\": return method;\n\t}\n\tconst upper = method.toUpperCase();\n\tswitch (upper) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\": return upper;\n\t\tdefault: return method;\n\t}\n};\nconst validateDirectReadMethod = (method) => {\n\tif (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);\n\tconst normalized = method.toUpperCase();\n\tif (normalized === \"CONNECT\" || normalized === \"TRACK\" || normalized === \"TRACE\" && method !== \"TRACE\") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);\n};\nconst readBodyWithFastPath = (request, method, fromBuffer) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\tconst methodName = request.method;\n\tif (methodName === \"GET\" || methodName === \"HEAD\") return request[getRequestCache]()[method]();\n\tconst methodValidationError = validateDirectReadMethod(methodName);\n\tif (methodValidationError) return Promise.reject(methodValidationError);\n\tif (request[requestCache]) {\n\t\tif (methodName !== \"TRACE\") return request[requestCache][method]();\n\t}\n\tconst alreadyUsedError = consumeBodyDirectOnce(request);\n\tif (alreadyUsedError) return alreadyUsedError;\n\tconst raw = readRawBodyIfAvailable(request);\n\tif (raw) {\n\t\tconst result = Promise.resolve(fromBuffer(raw, request));\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t}\n\treturn readBodyDirect(request).then((buf) => {\n\t\tconst result = fromBuffer(buf, request);\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t});\n};\nconst readRawBodyIfAvailable = (request) => {\n\tconst incoming = request[incomingKey];\n\tif (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;\n};\nconst normalizeAbortError = (request, incoming) => {\n\tif (incoming.errored) return incoming.errored;\n\tconst reason = request[abortReasonKey];\n\tif (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));\n\treturn /* @__PURE__ */ new Error(\"Client connection prematurely closed.\");\n};\nconst readBodyDirect = (request) => {\n\tif (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);\n\tif (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];\n\tconst incoming = request[incomingKey];\n\tif (incoming.readableDidRead) return rejectBodyUnusable();\n\tconst buffered = readBodyBufferedBeforeDisconnect(incoming);\n\tif (buffered !== void 0) {\n\t\tif (buffered instanceof Error) return Promise.reject(buffered);\n\t\trequest[bodyBufferKey] = buffered;\n\t\treturn Promise.resolve(buffered);\n\t}\n\tconst promise = new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\tlet settled = false;\n\t\tconst finish = (callback) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tcallback();\n\t\t};\n\t\tconst recoverCompleteBodyAfterDisconnect = (error) => {\n\t\t\tconst streamError = incoming.errored ?? error;\n\t\t\tif (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== \"ECONNRESET\") return false;\n\t\t\tfinish(() => {\n\t\t\t\tconst recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);\n\t\t\t\tif (recovered instanceof Error) reject(recovered);\n\t\t\t\telse if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));\n\t\t\t\telse {\n\t\t\t\t\trequest[bodyBufferKey] = recovered;\n\t\t\t\t\tresolve(recovered);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn true;\n\t\t};\n\t\tconst onData = (chunk) => {\n\t\t\tchunks.push(toBufferChunk(chunk, incoming.readableEncoding));\n\t\t};\n\t\tconst onEnd = () => {\n\t\t\tfinish(() => {\n\t\t\t\tconst buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);\n\t\t\t\trequest[bodyBufferKey] = buffer;\n\t\t\t\tresolve(buffer);\n\t\t\t});\n\t\t};\n\t\tconst onError = (error) => {\n\t\t\tif (recoverCompleteBodyAfterDisconnect(error)) return;\n\t\t\tfinish(() => {\n\t\t\t\treject(error);\n\t\t\t});\n\t\t};\n\t\tconst onClose = () => {\n\t\t\tif (incoming.readableEnded) {\n\t\t\t\tonEnd();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (recoverCompleteBodyAfterDisconnect()) return;\n\t\t\tfinish(() => {\n\t\t\t\treject(normalizeAbortError(request, incoming));\n\t\t\t});\n\t\t};\n\t\tconst cleanup = () => {\n\t\t\tincoming.off(\"data\", onData);\n\t\t\tincoming.off(\"end\", onEnd);\n\t\t\tincoming.off(\"error\", onError);\n\t\t\tincoming.off(\"close\", onClose);\n\t\t\trequest[bodyReadPromiseKey] = void 0;\n\t\t};\n\t\tincoming.on(\"data\", onData);\n\t\tincoming.on(\"end\", onEnd);\n\t\tincoming.on(\"error\", onError);\n\t\tincoming.on(\"close\", onClose);\n\t\tqueueMicrotask(() => {\n\t\t\tif (settled) return;\n\t\t\tif (incoming.readableEnded) onEnd();\n\t\t\telse if (incoming.errored) onError(incoming.errored);\n\t\t\telse if (incoming.destroyed) onClose();\n\t\t});\n\t});\n\trequest[bodyReadPromiseKey] = promise;\n\treturn promise;\n};\nconst requestPrototype = {\n\tget method() {\n\t\treturn this[methodKey];\n\t},\n\tget url() {\n\t\treturn this[urlKey];\n\t},\n\tget headers() {\n\t\treturn this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n\t},\n\t[abortRequest](reason) {\n\t\tif (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;\n\t\tconst abortController = this[abortControllerKey];\n\t\tif (abortController && !abortController.signal.aborted) abortController.abort(reason);\n\t},\n\t[getAbortController]() {\n\t\tthis[abortControllerKey] ||= new AbortController();\n\t\tif (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);\n\t\treturn this[abortControllerKey];\n\t},\n\t[getRequestCache]() {\n\t\tconst abortController = this[getAbortController]();\n\t\tif (this[requestCache]) return this[requestCache];\n\t\tconst method = this.method;\n\t\tif (this[bodyConsumedDirectlyKey] && !(method === \"GET\" || method === \"HEAD\")) {\n\t\t\tthis[bodyBufferKey] = void 0;\n\t\t\tconst init = {\n\t\t\t\tmethod: method === \"TRACE\" ? \"GET\" : method,\n\t\t\t\theaders: this.headers,\n\t\t\t\tsignal: abortController.signal\n\t\t\t};\n\t\t\tif (method !== \"TRACE\") {\n\t\t\t\tinit.body = new ReadableStream({ start(c) {\n\t\t\t\t\tc.close();\n\t\t\t\t} });\n\t\t\t\tinit.duplex = \"half\";\n\t\t\t}\n\t\t\tconst req = new Request$1(this[urlKey], init);\n\t\t\tif (method === \"TRACE\") Object.defineProperty(req, \"method\", { get() {\n\t\t\t\treturn \"TRACE\";\n\t\t\t} });\n\t\t\treturn this[requestCache] = req;\n\t\t}\n\t\treturn this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);\n\t},\n\tget body() {\n\t\tif (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;\n\t\tconst request = this[getRequestCache]();\n\t\tif (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();\n\t\treturn request.body;\n\t},\n\tget bodyUsed() {\n\t\tif (this[bodyConsumedDirectlyKey]) return true;\n\t\tif (this[requestCache]) return this[requestCache].bodyUsed;\n\t\treturn false;\n\t}\n};\nObject.defineProperty(requestPrototype, \"signal\", { get() {\n\treturn this[getAbortController]().signal;\n} });\n[\n\t\"cache\",\n\t\"credentials\",\n\t\"destination\",\n\t\"integrity\",\n\t\"mode\",\n\t\"redirect\",\n\t\"referrer\",\n\t\"referrerPolicy\",\n\t\"keepalive\"\n].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { get() {\n\t\treturn this[getRequestCache]()[k];\n\t} });\n});\n[\"clone\", \"formData\"].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { value: function() {\n\t\tif (this[bodyConsumedDirectlyKey]) {\n\t\t\tif (k === \"clone\") throw newBodyUnusableError();\n\t\t\treturn rejectBodyUnusable();\n\t\t}\n\t\treturn this[getRequestCache]()[k]();\n\t} });\n});\nObject.defineProperty(requestPrototype, \"text\", { value: function() {\n\treturn readBodyWithFastPath(this, \"text\", (buf) => textDecoder.decode(buf));\n} });\nObject.defineProperty(requestPrototype, \"arrayBuffer\", { value: function() {\n\treturn readBodyWithFastPath(this, \"arrayBuffer\", (buf) => toArrayBuffer(buf));\n} });\nObject.defineProperty(requestPrototype, \"blob\", { value: function() {\n\treturn readBodyWithFastPath(this, \"blob\", (buf, request) => {\n\t\tconst type = contentType(request);\n\t\tconst init = type ? { headers: { \"content-type\": type } } : void 0;\n\t\treturn new Response(buf, init).blob();\n\t});\n} });\nObject.defineProperty(requestPrototype, \"json\", { value: function() {\n\tif (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\treturn this.text().then(JSON.parse);\n} });\nObject.defineProperty(requestPrototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Request (lightweight) ${inspectFn({\n\t\tmethod: this.method,\n\t\turl: this.url,\n\t\theaders: this.headers,\n\t\tnativeRequest: this[requestCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(requestPrototype, Request$1.prototype);\nconst newRequest = (incoming, defaultHostname) => {\n\tconst req = Object.create(requestPrototype);\n\treq[incomingKey] = incoming;\n\treq[methodKey] = normalizeIncomingMethod(incoming.method);\n\tconst incomingUrl = incoming.url || \"\";\n\tif (incomingUrl[0] !== \"/\" && (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n\t\tif (incoming instanceof Http2ServerRequest) throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n\t\ttry {\n\t\t\treq[urlKey] = new URL(incomingUrl).href;\n\t\t} catch (e) {\n\t\t\tthrow new RequestError(\"Invalid absolute URL\", { cause: e });\n\t\t}\n\t\treturn req;\n\t}\n\tconst host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n\tif (!host) throw new RequestError(\"Missing host header\");\n\tlet scheme;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\tscheme = incoming.scheme;\n\t\tif (!(scheme === \"http\" || scheme === \"https\")) throw new RequestError(\"Unsupported scheme\");\n\t} else scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n\ttry {\n\t\treq[urlKey] = buildUrl(scheme, host, incomingUrl);\n\t} catch (e) {\n\t\tif (e instanceof RequestError) throw e;\n\t\telse throw new RequestError(\"Invalid URL\", { cause: e });\n\t}\n\treturn req;\n};\n\n//#endregion\n//#region src/response.ts\nconst defaultContentType = \"text/plain; charset=UTF-8\";\nconst responseCache = Symbol(\"responseCache\");\nconst getResponseCache = Symbol(\"getResponseCache\");\nconst cacheKey = Symbol(\"cache\");\nconst GlobalResponse = global.Response;\nvar Response$1 = class Response$1 {\n\t#body;\n\t#init;\n\t[getResponseCache]() {\n\t\tconst cache = this[cacheKey];\n\t\tconst liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;\n\t\tdelete this[cacheKey];\n\t\treturn this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {\n\t\t\tstatus: this.#init?.status,\n\t\t\tstatusText: this.#init?.statusText,\n\t\t\theaders: liveHeaders\n\t\t} : this.#init);\n\t}\n\tconstructor(body, init) {\n\t\tlet headers;\n\t\tthis.#body = body;\n\t\tif (init instanceof Response$1) {\n\t\t\tconst cachedGlobalResponse = init[responseCache];\n\t\t\tif (cachedGlobalResponse) {\n\t\t\t\tthis.#init = cachedGlobalResponse;\n\t\t\t\tthis[getResponseCache]();\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tthis.#init = init.#init;\n\t\t\t\theaders = new Headers(init.headers);\n\t\t\t}\n\t\t} else this.#init = init;\n\t\tif (body == null || typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [\n\t\t\tinit?.status || 200,\n\t\t\tbody ?? null,\n\t\t\theaders || init?.headers\n\t\t];\n\t}\n\tget headers() {\n\t\tconst cache = this[cacheKey];\n\t\tif (cache) {\n\t\t\tif (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { \"content-type\": defaultContentType }));\n\t\t\treturn cache[2];\n\t\t}\n\t\treturn this[getResponseCache]().headers;\n\t}\n\tget status() {\n\t\treturn this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n\t}\n\tget ok() {\n\t\tconst status = this.status;\n\t\treturn status >= 200 && status < 300;\n\t}\n};\n[\n\t\"body\",\n\t\"bodyUsed\",\n\t\"redirected\",\n\t\"statusText\",\n\t\"trailers\",\n\t\"type\",\n\t\"url\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { get() {\n\t\treturn this[getResponseCache]()[k];\n\t} });\n});\n[\n\t\"arrayBuffer\",\n\t\"blob\",\n\t\"clone\",\n\t\"formData\",\n\t\"json\",\n\t\"text\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { value: function() {\n\t\treturn this[getResponseCache]()[k]();\n\t} });\n});\nObject.defineProperty(Response$1.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Response (lightweight) ${inspectFn({\n\t\tstatus: this.status,\n\t\theaders: this.headers,\n\t\tok: this.ok,\n\t\tnativeResponse: this[responseCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(Response$1, GlobalResponse);\nObject.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);\nconst validRedirectUrl = /^https?:\\/\\/[!#-;=?-[\\]_a-z~A-Z]+$/;\nconst parseRedirectUrl = (url) => {\n\tif (url instanceof URL) return url.href;\n\tif (validRedirectUrl.test(url)) return url;\n\treturn new URL(url).href;\n};\nconst validRedirectStatuses = new Set([\n\t301,\n\t302,\n\t303,\n\t307,\n\t308\n]);\nObject.defineProperty(Response$1, \"redirect\", {\n\tvalue: function redirect(url, status = 302) {\n\t\tif (!validRedirectStatuses.has(status)) throw new RangeError(\"Invalid status code\");\n\t\treturn new Response$1(null, {\n\t\t\tstatus,\n\t\t\theaders: { location: parseRedirectUrl(url) }\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\nObject.defineProperty(Response$1, \"json\", {\n\tvalue: function json(data, init) {\n\t\tconst body = JSON.stringify(data);\n\t\tif (body === void 0) throw new TypeError(\"The data is not JSON serializable\");\n\t\tconst initHeaders = init?.headers;\n\t\tlet headers;\n\t\tif (initHeaders) {\n\t\t\theaders = new Headers(initHeaders);\n\t\t\tif (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n\t\t} else headers = { \"content-type\": \"application/json\" };\n\t\treturn new Response$1(body, {\n\t\t\tstatus: init?.status ?? 200,\n\t\t\tstatusText: init?.statusText,\n\t\t\theaders\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\n\n//#endregion\n//#region src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n\treturn Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n\tconst cancel = (error) => {\n\t\treader.cancel(error).catch(() => {});\n\t};\n\twritable.on(\"close\", cancel);\n\twritable.on(\"error\", cancel);\n\t(currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n\treturn reader.closed.finally(() => {\n\t\twritable.off(\"close\", cancel);\n\t\twritable.off(\"error\", cancel);\n\t});\n\tfunction handleStreamError(error) {\n\t\tif (error) writable.destroy(error);\n\t}\n\tfunction onDrain() {\n\t\treader.read().then(flow, handleStreamError);\n\t}\n\tfunction flow({ done, value }) {\n\t\ttry {\n\t\t\tif (done) writable.end();\n\t\t\telse if (!writable.write(value)) writable.once(\"drain\", onDrain);\n\t\t\telse return reader.read().then(flow, handleStreamError);\n\t\t} catch (e) {\n\t\t\thandleStreamError(e);\n\t\t}\n\t}\n}\nfunction writeFromReadableStream(stream, writable) {\n\tif (stream.locked) throw new TypeError(\"ReadableStream is locked.\");\n\telse if (writable.destroyed) return;\n\treturn writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nconst buildOutgoingHttpHeaders = (headers, defaultContentType) => {\n\tconst res = {};\n\tif (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);\n\tif (headers.has(\"set-cookie\")) {\n\t\tconst cookies = [];\n\t\tfor (const [k, v] of headers) if (k === \"set-cookie\") cookies.push(v);\n\t\telse res[k] = v;\n\t\tif (cookies.length > 0) res[\"set-cookie\"] = cookies;\n\t} else for (const [k, v] of headers) res[k] = v;\n\tif (defaultContentType) res[\"content-type\"] ??= defaultContentType;\n\treturn res;\n};\n\n//#endregion\n//#region src/listener.ts\nconst outgoingEnded = Symbol(\"outgoingEnded\");\nconst incomingDraining = Symbol(\"incomingDraining\");\nconst DRAIN_TIMEOUT_MS = 500;\nconst MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nconst drainIncoming = (incoming) => {\n\tconst incomingWithDrainState = incoming;\n\tif (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;\n\tincomingWithDrainState[incomingDraining] = true;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\ttry {\n\t\t\tincoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);\n\t\t} catch {}\n\t\treturn;\n\t}\n\tlet bytesRead = 0;\n\tconst cleanup = () => {\n\t\tclearTimeout(timer);\n\t\tincoming.off(\"data\", onData);\n\t\tincoming.off(\"end\", cleanup);\n\t\tincoming.off(\"error\", cleanup);\n\t};\n\tconst forceClose = () => {\n\t\tcleanup();\n\t\tconst socket = incoming.socket;\n\t\tif (socket && !socket.destroyed) socket.destroySoon();\n\t};\n\tconst timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n\ttimer.unref?.();\n\tconst onData = (chunk) => {\n\t\tbytesRead += chunk.length;\n\t\tif (bytesRead > MAX_DRAIN_BYTES) forceClose();\n\t};\n\tincoming.on(\"data\", onData);\n\tincoming.on(\"end\", cleanup);\n\tincoming.on(\"error\", cleanup);\n\tincoming.resume();\n};\nconst makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {\n\tif (incoming.errored) {\n\t\trecordBodyBufferedBeforeDisconnect(incoming);\n\t\treq[abortRequest](incoming.errored.toString());\n\t} else if (!outgoing.writableFinished) {\n\t\trecordBodyBufferedBeforeDisconnect(incoming);\n\t\treq[abortRequest](\"Client connection prematurely closed.\");\n\t}\n\tif (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {\n\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\tdrainIncoming(incoming);\n\t\t});\n\t});\n};\nconst isImmediateCacheableResponse = (res) => {\n\tif (!(cacheKey in res)) return false;\n\tconst body = res[cacheKey][1];\n\treturn body === null || typeof body === \"string\" || body instanceof Uint8Array;\n};\nconst handleRequestError = () => new Response(null, { status: 400 });\nconst handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500 });\nconst handleResponseError = (e, outgoing) => {\n\tconst err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n\tif (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") console.info(\"The user aborted a request.\");\n\telse {\n\t\tconsole.error(e);\n\t\tif (!outgoing.headersSent) outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n\t\toutgoing.end(`Error: ${err.message}`);\n\t\toutgoing.destroy(err);\n\t}\n};\nconst flushHeaders = (outgoing) => {\n\tif (\"flushHeaders\" in outgoing && outgoing.writable) outgoing.flushHeaders();\n};\nconst responseViaCache = async (res, outgoing) => {\n\tlet [status, body, header] = res[cacheKey];\n\tif (!header) {\n\t\tif (body === null) {\n\t\t\toutgoing.writeHead(status);\n\t\t\toutgoing.end();\n\t\t} else if (typeof body === \"string\") {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": Buffer.byteLength(body)\n\t\t\t});\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Uint8Array) {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": body.byteLength\n\t\t\t});\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Blob) {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": body.size\n\t\t\t});\n\t\t\toutgoing.end(new Uint8Array(await body.arrayBuffer()));\n\t\t} else {\n\t\t\toutgoing.writeHead(status, { \"Content-Type\": defaultContentType });\n\t\t\tflushHeaders(outgoing);\n\t\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t\t}\n\t\toutgoing[outgoingEnded]?.();\n\t\treturn;\n\t}\n\tlet hasContentLength = false;\n\tif (header instanceof Headers) {\n\t\thasContentLength = header.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);\n\t} else if (Array.isArray(header)) {\n\t\tconst headerObj = new Headers(header);\n\t\thasContentLength = headerObj.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);\n\t} else for (const key in header) if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n\t\thasContentLength = true;\n\t\tbreak;\n\t}\n\tif (!hasContentLength) {\n\t\tif (typeof body === \"string\") header[\"Content-Length\"] = Buffer.byteLength(body);\n\t\telse if (body instanceof Uint8Array) header[\"Content-Length\"] = body.byteLength;\n\t\telse if (body instanceof Blob) header[\"Content-Length\"] = body.size;\n\t}\n\toutgoing.writeHead(status, header);\n\tif (body == null) outgoing.end();\n\telse if (typeof body === \"string\" || body instanceof Uint8Array) outgoing.end(body);\n\telse if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));\n\telse {\n\t\tflushHeaders(outgoing);\n\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst isPromise = (res) => typeof res.then === \"function\";\nconst responseViaResponseObject = async (res, outgoing, options = {}) => {\n\tif (isPromise(res)) if (options.errorHandler) try {\n\t\tres = await res;\n\t} catch (err) {\n\t\tconst errRes = await options.errorHandler(err);\n\t\tif (!errRes) return;\n\t\tres = errRes;\n\t}\n\telse res = await res.catch(handleFetchError);\n\tif (cacheKey in res) return responseViaCache(res, outgoing);\n\tconst resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);\n\tif (res.body) {\n\t\tconst reader = res.body.getReader();\n\t\tconst values = [];\n\t\tlet done = false;\n\t\tlet currentReadPromise = void 0;\n\t\tif (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n\t\t\tlet maxReadCount = 2;\n\t\t\tfor (let i = 0; i < maxReadCount; i++) {\n\t\t\t\tcurrentReadPromise ||= reader.read();\n\t\t\t\tconst chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t\tdone = true;\n\t\t\t\t});\n\t\t\t\tif (!chunk) {\n\t\t\t\t\tif (i === 1) {\n\t\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve));\n\t\t\t\t\t\tmaxReadCount = 3;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcurrentReadPromise = void 0;\n\t\t\t\tif (chunk.value) values.push(chunk.value);\n\t\t\t\tif (chunk.done) {\n\t\t\t\t\tdone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (done && !(\"content-length\" in resHeaderRecord)) resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n\t\t}\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\tvalues.forEach((value) => {\n\t\t\toutgoing.write(value);\n\t\t});\n\t\tif (done) outgoing.end();\n\t\telse {\n\t\t\tif (values.length === 0) flushHeaders(outgoing);\n\t\t\tawait writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n\t\t}\n\t} else if (resHeaderRecord[X_ALREADY_SENT]) {} else {\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\toutgoing.end();\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst getRequestListener = (fetchCallback, options = {}) => {\n\tconst autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n\tif (options.overrideGlobalObjects !== false && global.Request !== Request$1) {\n\t\tObject.defineProperty(global, \"Request\", { value: Request$1 });\n\t\tObject.defineProperty(global, \"Response\", { value: Response$1 });\n\t}\n\treturn async (incoming, outgoing) => {\n\t\tlet res, req;\n\t\tlet needsBodyCleanup = false;\n\t\tlet closeHandlerAttached = false;\n\t\tconst ensureCloseHandler = () => {\n\t\t\tif (!req || closeHandlerAttached) return;\n\t\t\tcloseHandlerAttached = true;\n\t\t\toutgoing.on(\"close\", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));\n\t\t};\n\t\ttry {\n\t\t\treq = newRequest(incoming, options.hostname);\n\t\t\tneedsBodyCleanup = autoCleanupIncoming && !(incoming.method === \"GET\" || incoming.method === \"HEAD\");\n\t\t\tif (needsBodyCleanup) {\n\t\t\t\tincoming[wrapBodyStream] = true;\n\t\t\t\tif (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {\n\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\t\tincoming.destroy();\n\t\t\t\t\t\t\toutgoing.destroy();\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}\n\t\t\tres = fetchCallback(req, {\n\t\t\t\tincoming,\n\t\t\t\toutgoing\n\t\t\t});\n\t\t\tif (!isPromise(res) && isImmediateCacheableResponse(res)) {\n\t\t\t\tif (needsBodyCleanup && !incoming.readableEnded) outgoing.once(\"finish\", () => {\n\t\t\t\t\tif (!incoming.readableEnded) drainIncoming(incoming);\n\t\t\t\t});\n\t\t\t\treturn responseViaCache(res, outgoing);\n\t\t\t}\n\t\t\tensureCloseHandler();\n\t\t} catch (e) {\n\t\t\tif (!res) if (options.errorHandler) {\n\t\t\t\tensureCloseHandler();\n\t\t\t\tres = await options.errorHandler(req ? e : toRequestError(e));\n\t\t\t\tif (!res) return;\n\t\t\t} else if (!req) res = handleRequestError();\n\t\t\telse res = handleFetchError(e);\n\t\t\telse return handleResponseError(e, outgoing);\n\t\t}\n\t\ttry {\n\t\t\treturn await responseViaResponseObject(res, outgoing, options);\n\t\t} catch (e) {\n\t\t\treturn handleResponseError(e, outgoing);\n\t\t}\n\t};\n};\n\n//#endregion\n//#region src/websocket.ts\n/**\n* @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent\n*/\nconst CloseEvent = globalThis.CloseEvent ?? class extends Event {\n\t#eventInitDict;\n\tconstructor(type, eventInitDict = {}) {\n\t\tsuper(type, eventInitDict);\n\t\tthis.#eventInitDict = eventInitDict;\n\t}\n\tget wasClean() {\n\t\treturn this.#eventInitDict.wasClean ?? false;\n\t}\n\tget code() {\n\t\treturn this.#eventInitDict.code ?? 0;\n\t}\n\tget reason() {\n\t\treturn this.#eventInitDict.reason ?? \"\";\n\t}\n};\n/**\n* Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.\n* @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent\n*/\nconst ErrorEvent = globalThis.ErrorEvent ?? class extends Event {\n\t#eventInitDict;\n\tconstructor(type, eventInitDict = {}) {\n\t\tsuper(type, eventInitDict);\n\t\tthis.#eventInitDict = eventInitDict;\n\t}\n\tget message() {\n\t\treturn this.#eventInitDict.message ?? \"\";\n\t}\n\tget filename() {\n\t\treturn this.#eventInitDict.filename ?? \"\";\n\t}\n\tget lineno() {\n\t\treturn this.#eventInitDict.lineno ?? 0;\n\t}\n\tget colno() {\n\t\treturn this.#eventInitDict.colno ?? 0;\n\t}\n\tget error() {\n\t\treturn this.#eventInitDict.error ?? null;\n\t}\n};\nconst generateConnectionSymbol = () => Symbol(\"connection\");\nconst CONNECTION_SYMBOL_KEY = Symbol(\"CONNECTION_SYMBOL_KEY\");\nconst WAIT_FOR_WEBSOCKET_SYMBOL = Symbol(\"WAIT_FOR_WEBSOCKET_SYMBOL\");\nconst responseHeadersToSkip = new Set([\n\t\"connection\",\n\t\"content-length\",\n\t\"keep-alive\",\n\t\"proxy-authenticate\",\n\t\"proxy-authorization\",\n\t\"te\",\n\t\"trailer\",\n\t\"transfer-encoding\",\n\t\"upgrade\",\n\t\"sec-websocket-accept\",\n\t\"sec-websocket-extensions\",\n\t\"sec-websocket-protocol\"\n]);\nconst appendResponseHeaders = (headers, responseHeaders) => {\n\tif (!responseHeaders) return;\n\tresponseHeaders.forEach((value, key) => {\n\t\tif (responseHeadersToSkip.has(key.toLowerCase())) return;\n\t\theaders.push(`${key}: ${value}`);\n\t});\n};\nconst rejectUpgradeRequest = (socket, status, responseHeaders) => {\n\tconst responseLines = [\"Connection: close\", \"Content-Length: 0\"];\n\tappendResponseHeaders(responseLines, responseHeaders);\n\tsocket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? \"\"}\\r\\n${responseLines.join(\"\\r\\n\")}\\r\\n\\r\n`);\n};\nconst createUpgradeRequest = (request) => {\n\tconst protocol = request.socket.encrypted ? \"https\" : \"http\";\n\tconst url = new URL(request.url ?? \"/\", `${protocol}://${request.headers.host ?? \"localhost\"}`);\n\tconst headers = new Headers();\n\tfor (const key in request.headers) {\n\t\tconst value = request.headers[key];\n\t\tif (!value) continue;\n\t\theaders.append(key, Array.isArray(value) ? value[0] : value);\n\t}\n\treturn new Request(url, { headers });\n};\nconst setupWebSocket = (options) => {\n\tconst { server, fetchCallback, wss } = options;\n\tconst waiterMap = /* @__PURE__ */ new Map();\n\twss.on(\"connection\", (ws, request) => {\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (waiter) {\n\t\t\twaiter.resolve(ws);\n\t\t\twaiterMap.delete(request);\n\t\t}\n\t});\n\tconst rejectWaiter = (request) => {\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (waiter) {\n\t\t\twaiterMap.delete(request);\n\t\t\twaiter.reject(/* @__PURE__ */ new Error(\"WebSocket handshake aborted\"));\n\t\t}\n\t};\n\tconst waitForWebSocket = (request, connectionSymbol) => {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\twaiterMap.set(request, {\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t\tconnectionSymbol\n\t\t\t});\n\t\t});\n\t};\n\tserver.on(\"upgrade\", async (request, socket, head) => {\n\t\tif (request.headers.upgrade?.toLowerCase() !== \"websocket\") return;\n\t\tconst env = {\n\t\t\tincoming: request,\n\t\t\toutgoing: void 0,\n\t\t\twss,\n\t\t\t[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket\n\t\t};\n\t\tlet status = 400;\n\t\tlet responseHeaders;\n\t\ttry {\n\t\t\tconst response = await fetchCallback(createUpgradeRequest(request), env);\n\t\t\tif (response instanceof Response) {\n\t\t\t\tstatus = response.status;\n\t\t\t\tresponseHeaders = response.headers;\n\t\t\t}\n\t\t} catch {\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, 500);\n\t\t\treturn;\n\t\t}\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {\n\t\t\trejectWaiter(request);\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, status, responseHeaders);\n\t\t\treturn;\n\t\t}\n\t\tconst addResponseHeaders = (headers) => {\n\t\t\tappendResponseHeaders(headers, responseHeaders);\n\t\t};\n\t\tconst reclaimWaiterOnClose = () => rejectWaiter(request);\n\t\tsocket.once(\"close\", reclaimWaiterOnClose);\n\t\twss.on(\"headers\", addResponseHeaders);\n\t\ttry {\n\t\t\twss.handleUpgrade(request, socket, head, (ws) => {\n\t\t\t\tsocket.off(\"close\", reclaimWaiterOnClose);\n\t\t\t\twss.emit(\"connection\", ws, request);\n\t\t\t});\n\t\t} finally {\n\t\t\twss.off(\"headers\", addResponseHeaders);\n\t\t}\n\t});\n\tserver.on(\"close\", () => {\n\t\twss.close();\n\t});\n};\nconst upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {\n\tif (c.req.header(\"upgrade\")?.toLowerCase() !== \"websocket\") return;\n\tconst env = c.env;\n\tconst waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];\n\tif (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });\n\tconst connectionSymbol = generateConnectionSymbol();\n\tenv[CONNECTION_SYMBOL_KEY] = connectionSymbol;\n\t(async () => {\n\t\tlet ws;\n\t\ttry {\n\t\t\tws = await waitForWebSocket(env.incoming, connectionSymbol);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tconst messagesReceivedInStarting = [];\n\t\tconst bufferMessage = (data, isBinary) => {\n\t\t\tmessagesReceivedInStarting.push([data, isBinary]);\n\t\t};\n\t\tws.on(\"message\", bufferMessage);\n\t\tconst ctx = {\n\t\t\tbinaryType: \"arraybuffer\",\n\t\t\tclose(code, reason) {\n\t\t\t\tws.close(code, reason);\n\t\t\t},\n\t\t\tprotocol: ws.protocol,\n\t\t\traw: ws,\n\t\t\tget readyState() {\n\t\t\t\treturn ws.readyState;\n\t\t\t},\n\t\t\tsend(source, opts) {\n\t\t\t\tws.send(source, { compress: opts?.compress });\n\t\t\t},\n\t\t\turl: new URL(c.req.url)\n\t\t};\n\t\ttry {\n\t\t\tevents?.onOpen?.(new Event(\"open\"), ctx);\n\t\t} catch (e) {\n\t\t\t(options?.onError ?? console.error)(e);\n\t\t}\n\t\tconst handleMessage = (data, isBinary) => {\n\t\t\tconst datas = Array.isArray(data) ? data : [data];\n\t\t\tfor (const data of datas) try {\n\t\t\t\tevents?.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);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t};\n\t\tws.off(\"message\", bufferMessage);\n\t\tfor (const message of messagesReceivedInStarting) handleMessage(...message);\n\t\tws.on(\"message\", (data, isBinary) => {\n\t\t\thandleMessage(data, isBinary);\n\t\t});\n\t\tws.on(\"close\", (code, reason) => {\n\t\t\ttry {\n\t\t\t\tevents?.onClose?.(new CloseEvent(\"close\", {\n\t\t\t\t\tcode,\n\t\t\t\t\treason: reason.toString()\n\t\t\t\t}), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t\tws.on(\"error\", (error) => {\n\t\t\ttry {\n\t\t\t\tevents?.onError?.(new ErrorEvent(\"error\", { error }), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t})();\n\treturn new Response();\n});\n\n//#endregion\n//#region src/server.ts\nconst createAdaptorServer = (options) => {\n\tconst fetchCallback = options.fetch;\n\tconst requestListener = getRequestListener(fetchCallback, {\n\t\thostname: options.hostname,\n\t\toverrideGlobalObjects: options.overrideGlobalObjects,\n\t\tautoCleanupIncoming: options.autoCleanupIncoming\n\t});\n\tconst server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);\n\tif (options.websocket && options.websocket.server) {\n\t\tif (options.websocket.server.options.noServer !== true) throw new Error(\"WebSocket server must be created with { noServer: true } option\");\n\t\tsetupWebSocket({\n\t\t\tserver,\n\t\t\tfetchCallback,\n\t\t\twss: options.websocket.server\n\t\t});\n\t}\n\treturn server;\n};\nconst serve = (options, listeningListener) => {\n\tconst server = createAdaptorServer(options);\n\tserver.listen(options?.port ?? 3e3, options.hostname, () => {\n\t\tconst serverInfo = server.address();\n\t\tlisteningListener && listeningListener(serverInfo);\n\t});\n\treturn server;\n};\n\n//#endregion\nexport { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };","import { Readable } from \"node:stream\";\nimport { versions } from \"node:process\";\n\n//#region src/utils/stream.ts\nconst pr54206Applied = () => {\n\tconst [major, minor] = versions.node.split(\".\").map((component) => parseInt(component));\n\treturn major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;\n};\nconst useReadableToWeb = pr54206Applied();\nconst createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => {\n\tif (useNativeReadableToWeb) return Readable.toWeb(stream);\n\tlet controller;\n\tlet settled = false;\n\tconst cleanup = () => {\n\t\tstream.off(\"data\", onData);\n\t\tstream.off(\"error\", onError);\n\t\tstream.off(\"end\", onTerminate);\n\t\tstream.off(\"close\", onTerminate);\n\t};\n\tconst settle = (callback) => {\n\t\tif (settled) return;\n\t\tsettled = true;\n\t\tcleanup();\n\t\tcallback?.();\n\t};\n\tconst onData = (chunk) => {\n\t\tif (settled || !controller) return;\n\t\tcontroller.enqueue(chunk);\n\t\tif ((controller.desiredSize ?? 0) <= 0) stream.pause();\n\t};\n\tconst onError = (error) => {\n\t\tsettle(() => {\n\t\t\tcontroller?.error(error);\n\t\t});\n\t};\n\tconst onTerminate = () => {\n\t\tsettle(() => {\n\t\t\tcontroller?.close();\n\t\t});\n\t};\n\treturn new ReadableStream({\n\t\tstart(streamController) {\n\t\t\tcontroller = streamController;\n\t\t\tstream.on(\"data\", onData);\n\t\t\tstream.on(\"error\", onError);\n\t\t\tstream.on(\"end\", onTerminate);\n\t\t\tstream.on(\"close\", onTerminate);\n\t\t\tstream.pause();\n\t\t},\n\t\tpull() {\n\t\t\tif (!settled) stream.resume();\n\t\t},\n\t\tcancel() {\n\t\t\tsettle();\n\t\t\tconst ignoreError = () => {};\n\t\t\tstream.on(\"error\", ignoreError);\n\t\t\tstream.once(\"close\", () => stream.off(\"error\", ignoreError));\n\t\t\tstream.destroy();\n\t\t}\n\t});\n};\n\n//#endregion\nexport { createStreamBody };","import { createStreamBody } from \"./utils/stream.mjs\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport { createReadStream, existsSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n//#region src/serve-static.ts\nconst 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;\nconst ENCODINGS = {\n\tbr: \".br\",\n\tzstd: \".zst\",\n\tgzip: \".gz\"\n};\nconst ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);\nconst getStats = (path) => {\n\tlet stats;\n\ttry {\n\t\tstats = statSync(path);\n\t} catch {}\n\treturn stats;\n};\nconst BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\\d*)-(\\d*)$/;\nconst parseByteRange = (range) => {\n\tconst match = range.match(BYTE_RANGE_PATTERN);\n\tif (!match) return;\n\tconst [, start, end] = match;\n\tif (start === \"\") return {\n\t\ttype: \"suffix\",\n\t\tlength: Number(end)\n\t};\n\tif (end === \"\") return {\n\t\ttype: \"open-ended\",\n\t\tstart: Number(start)\n\t};\n\treturn {\n\t\ttype: \"bounded\",\n\t\tstart: Number(start),\n\t\tend: Number(end)\n\t};\n};\nconst resolveByteRange = (spec, size) => {\n\tif (size === 0) return;\n\tif (spec.type === \"suffix\") {\n\t\tif (spec.length === 0) return;\n\t\treturn {\n\t\t\tstart: Math.max(size - spec.length, 0),\n\t\t\tend: size - 1\n\t\t};\n\t}\n\tconst end = spec.type === \"bounded\" ? Math.min(spec.end, size - 1) : size - 1;\n\tif (spec.start >= size || spec.start > end) return;\n\treturn {\n\t\tstart: spec.start,\n\t\tend\n\t};\n};\nconst tryDecode = (str, decoder) => {\n\ttry {\n\t\treturn decoder(str);\n\t} catch {\n\t\treturn str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n\t\t\ttry {\n\t\t\t\treturn decoder(match);\n\t\t\t} catch {\n\t\t\t\treturn match;\n\t\t\t}\n\t\t});\n\t}\n};\nconst tryDecodeURI = (str) => tryDecode(str, decodeURI);\nconst serveStatic = (options = { root: \"\" }) => {\n\tconst root = options.root || \"\";\n\tconst optionPath = options.path;\n\tif (root !== \"\" && !existsSync(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);\n\treturn async (c, next) => {\n\t\tif (c.finalized) return next();\n\t\tlet filename;\n\t\tif (optionPath) filename = optionPath;\n\t\telse try {\n\t\t\tfilename = tryDecodeURI(c.req.path);\n\t\t\tif (/(?:^|[\\/\\\\])\\.{1,2}(?:$|[\\/\\\\])|[\\/\\\\]{2,}|\\\\/.test(filename)) throw new Error();\n\t\t} catch {\n\t\t\tawait options.onNotFound?.(c.req.path, c);\n\t\t\treturn next();\n\t\t}\n\t\tlet path = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename);\n\t\tlet stats = getStats(path);\n\t\tif (stats && stats.isDirectory()) {\n\t\t\tconst indexFile = options.index ?? \"index.html\";\n\t\t\tpath = join(path, indexFile);\n\t\t\tstats = getStats(path);\n\t\t}\n\t\tif (!stats) {\n\t\t\tawait options.onNotFound?.(path, c);\n\t\t\treturn next();\n\t\t}\n\t\tconst mimeType = getMimeType(path);\n\t\tc.header(\"Content-Type\", mimeType || \"application/octet-stream\");\n\t\tif (options.precompressed && (!mimeType || mimeType === \"application/octet-stream\" || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {\n\t\t\tconst acceptEncodingSet = new Set(c.req.header(\"Accept-Encoding\")?.split(\",\").map((encoding) => encoding.trim()));\n\t\t\tfor (const encoding of ENCODINGS_ORDERED_KEYS) {\n\t\t\t\tif (!acceptEncodingSet.has(encoding)) continue;\n\t\t\t\tconst precompressedStats = getStats(path + ENCODINGS[encoding]);\n\t\t\t\tif (precompressedStats) {\n\t\t\t\t\tc.header(\"Content-Encoding\", encoding);\n\t\t\t\t\tc.header(\"Vary\", \"Accept-Encoding\", { append: true });\n\t\t\t\t\tstats = precompressedStats;\n\t\t\t\t\tpath = path + ENCODINGS[encoding];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet result;\n\t\tconst size = stats.size;\n\t\tconst range = c.req.header(\"range\") || \"\";\n\t\tc.header(\"Last-Modified\", stats.mtime.toUTCString());\n\t\tif (c.req.method == \"HEAD\" || c.req.method == \"OPTIONS\") {\n\t\t\tc.header(\"Content-Length\", size.toString());\n\t\t\tc.status(200);\n\t\t\tresult = c.body(null);\n\t\t} else if (!range) {\n\t\t\tc.header(\"Content-Length\", size.toString());\n\t\t\tresult = c.body(createStreamBody(createReadStream(path)), 200);\n\t\t} else {\n\t\t\tc.header(\"Accept-Ranges\", \"bytes\");\n\t\t\tconst resolvedRange = resolveByteRange(parseByteRange(range) ?? {\n\t\t\t\ttype: \"open-ended\",\n\t\t\t\tstart: 0\n\t\t\t}, size);\n\t\t\tif (!resolvedRange) {\n\t\t\t\tc.header(\"Content-Range\", `bytes */${size}`);\n\t\t\t\tresult = c.body(null, 416);\n\t\t\t} else {\n\t\t\t\tconst { start, end } = resolvedRange;\n\t\t\t\tconst chunkSize = end - start + 1;\n\t\t\t\tconst stream = createReadStream(path, {\n\t\t\t\t\tstart,\n\t\t\t\t\tend\n\t\t\t\t});\n\t\t\t\tc.header(\"Content-Length\", chunkSize.toString());\n\t\t\t\tc.header(\"Content-Range\", `bytes ${start}-${end}/${size}`);\n\t\t\t\tresult = c.body(createStreamBody(stream), 206);\n\t\t\t}\n\t\t}\n\t\tawait options.onFound?.(path, c);\n\t\treturn result;\n\t};\n};\n\n//#endregion\nexport { serveStatic };","import { html } from \"hono/html\";\n\n//#region src/swagger/renderer.ts\nconst RENDER_TYPE = {\n\tSTRING_ARRAY: \"string_array\",\n\tSTRING: \"string\",\n\tJSON_STRING: \"json_string\",\n\tRAW: \"raw\"\n};\nconst RENDER_TYPE_MAP = {\n\tconfigUrl: RENDER_TYPE.STRING,\n\tdeepLinking: RENDER_TYPE.RAW,\n\tpresets: RENDER_TYPE.STRING_ARRAY,\n\tplugins: RENDER_TYPE.STRING_ARRAY,\n\tspec: RENDER_TYPE.JSON_STRING,\n\turl: RENDER_TYPE.STRING,\n\turls: RENDER_TYPE.JSON_STRING,\n\tlayout: RENDER_TYPE.STRING,\n\tdocExpansion: RENDER_TYPE.STRING,\n\tmaxDisplayedTags: RENDER_TYPE.RAW,\n\toperationsSorter: RENDER_TYPE.RAW,\n\trequestInterceptor: RENDER_TYPE.RAW,\n\tresponseInterceptor: RENDER_TYPE.RAW,\n\tpersistAuthorization: RENDER_TYPE.RAW,\n\tdefaultModelsExpandDepth: RENDER_TYPE.RAW,\n\tdefaultModelExpandDepth: RENDER_TYPE.RAW,\n\tdefaultModelRendering: RENDER_TYPE.STRING,\n\tdisplayRequestDuration: RENDER_TYPE.RAW,\n\tfilter: RENDER_TYPE.RAW,\n\tshowExtensions: RENDER_TYPE.RAW,\n\tshowCommonExtensions: RENDER_TYPE.RAW,\n\tqueryConfigEnabled: RENDER_TYPE.RAW,\n\tdisplayOperationId: RENDER_TYPE.RAW,\n\ttagsSorter: RENDER_TYPE.RAW,\n\tonComplete: RENDER_TYPE.RAW,\n\tsyntaxHighlight: RENDER_TYPE.JSON_STRING,\n\ttryItOutEnabled: RENDER_TYPE.RAW,\n\trequestSnippetsEnabled: RENDER_TYPE.RAW,\n\trequestSnippets: RENDER_TYPE.JSON_STRING,\n\toauth2RedirectUrl: RENDER_TYPE.STRING,\n\tshowMutabledRequest: RENDER_TYPE.RAW,\n\trequest: RENDER_TYPE.JSON_STRING,\n\tsupportedSubmitMethods: RENDER_TYPE.JSON_STRING,\n\tvalidatorUrl: RENDER_TYPE.STRING,\n\twithCredentials: RENDER_TYPE.RAW,\n\tmodelPropertyMacro: RENDER_TYPE.RAW,\n\tparameterMacro: RENDER_TYPE.RAW\n};\nconst renderSwaggerUIOptions = (options) => {\n\treturn Object.entries(options).map(([k, v]) => {\n\t\tconst key = k;\n\t\tif (!RENDER_TYPE_MAP[key] || v === void 0) return \"\";\n\t\tswitch (RENDER_TYPE_MAP[key]) {\n\t\t\tcase RENDER_TYPE.STRING: return `${key}: '${v}'`;\n\t\t\tcase RENDER_TYPE.STRING_ARRAY:\n\t\t\t\tif (!Array.isArray(v)) return \"\";\n\t\t\t\treturn `${key}: [${v.map((ve) => `${ve}`).join(\",\")}]`;\n\t\t\tcase RENDER_TYPE.JSON_STRING: return `${key}: ${JSON.stringify(v)}`;\n\t\t\tcase RENDER_TYPE.RAW: return `${key}: ${v}`;\n\t\t\tdefault: return \"\";\n\t\t}\n\t}).filter((item) => item !== \"\").join(\",\");\n};\n\n//#endregion\n//#region src/swagger/resource.ts\nconst remoteAssets = ({ version }) => {\n\tconst url = `https://cdn.jsdelivr.net/npm/swagger-ui-dist${version !== void 0 ? `@${version}` : \"\"}`;\n\treturn {\n\t\tcss: [`${url}/swagger-ui.css`],\n\t\tjs: [`${url}/swagger-ui-bundle.js`]\n\t};\n};\n\n//#endregion\n//#region src/index.ts\nconst SwaggerUI = (options) => {\n\tconst asset = remoteAssets({ version: options?.version });\n\tdelete options.version;\n\tif (options.manuallySwaggerUIHtml) return options.manuallySwaggerUIHtml(asset);\n\tconst optionsStrings = renderSwaggerUIOptions(options);\n\treturn `\n <div>\n <div id=\"swagger-ui\"></div>\n ${asset.css.map((url) => html`<link rel=\"stylesheet\" href=\"${url}\" />`)}\n ${asset.js.map((url) => html`<script src=\"${url}\" crossorigin=\"anonymous\"><\\/script>`)}\n <script>\n window.onload = () => {\n window.ui = SwaggerUIBundle({\n dom_id: '#swagger-ui',${optionsStrings},\n })\n }\n <\\/script>\n </div>\n `;\n};\nconst middleware = (options) => async (c) => {\n\tconst title = options?.title ?? \"SwaggerUI\";\n\treturn c.html(`\n <!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta name=\"description\" content=\"SwaggerUI\" />\n <title>${title}</title>\n </head>\n <body>\n ${SwaggerUI(options)}\n </body>\n </html>\n `);\n};\n\n//#endregion\nexport { SwaggerUI, middleware as swaggerUI };\n//# sourceMappingURL=index.js.map","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\nimport util from \"node:util\";\n/* These items copied from Node.js: node/lib/internal/errors.js */\nconst classRegExp = /^([A-Z][a-z0-9]*)+$/;\n// Sorted by a rough estimate on most frequently used entries.\nconst kTypes = [\n \"string\",\n \"function\",\n \"number\",\n \"object\",\n // Accept 'Function' and 'Object' as alternative to the lower cased version.\n \"Function\",\n \"Object\",\n \"boolean\",\n \"bigint\",\n \"symbol\",\n];\n/**\n * Determine the specific type of a value for type-mismatch errors.\n * @param {*} value\n * @returns {string}\n */\nfunction determineSpecificType(value) {\n if (value == null) {\n return \"\" + value;\n }\n if (typeof value === \"function\" && value.name) {\n return `function ${value.name}`;\n }\n if (typeof value === \"object\") {\n if (value.constructor?.name) {\n return `an instance of ${value.constructor.name}`;\n }\n return `${util.inspect(value, { depth: -1 })}`;\n }\n let inspected = util.inspect(value, { colors: false });\n if (inspected.length > 28) {\n inspected = `${inspected.slice(0, 25)}...`;\n }\n return `type ${typeof value} (${inspected})`;\n}\n// The following classes are adaptations of a subset of the ERR_* classes\n// declared in Node.js in the file - node/lib/internal/errors.js.\nexport class ERR_HTTP_BODY_NOT_ALLOWED extends Error {\n constructor() {\n super(\"Adding content for this request method or response status is not allowed.\");\n }\n}\nexport class ERR_HTTP_CONTENT_LENGTH_MISMATCH extends Error {\n constructor(actual, expected) {\n super(`Response body's content-length of ${actual} byte(s) does not match the content-length of ${expected} byte(s) set in header`);\n }\n}\nexport class ERR_HTTP_HEADERS_SENT extends Error {\n constructor(arg) {\n super(`Cannot ${arg} headers after they are sent to the client`);\n }\n}\nexport class ERR_INVALID_ARG_VALUE extends TypeError /*, RangeError */ {\n constructor(name, value, reason = \"is invalid\") {\n let inspected = util.inspect(value);\n if (inspected.length > 128) {\n inspected = `${inspected.slice(0, 128)}...`;\n }\n const type = name.includes(\".\") ? \"property\" : \"argument\";\n super(`The ${type} '${name}' ${reason}. Received ${inspected}`);\n }\n}\nexport class ERR_INVALID_CHAR extends TypeError {\n constructor(name, field) {\n let msg = `Invalid character in ${name}`;\n if (field !== undefined) {\n msg += ` [\"${field}\"]`;\n }\n super(msg);\n }\n}\nexport class ERR_HTTP_INVALID_HEADER_VALUE extends TypeError {\n constructor(value, name) {\n super(`Invalid value \"${value}\" for header \"${name}\"`);\n }\n}\nexport class ERR_HTTP_INVALID_STATUS_CODE extends RangeError {\n originalStatusCode;\n constructor(originalStatusCode) {\n super(`Invalid status code: ${originalStatusCode}`);\n this.originalStatusCode = originalStatusCode;\n }\n}\nexport class ERR_HTTP_TRAILER_INVALID extends Error {\n constructor() {\n super(`Trailers are invalid with this transfer encoding`);\n }\n}\nexport class ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n // assert(typeof name === 'string', \"'name' must be a string\");\n if (!Array.isArray(expected)) {\n expected = [expected];\n }\n let msg = \"The \";\n if (name.endsWith(\" argument\")) {\n // For cases like 'first argument'\n msg += `${name} `;\n }\n else {\n const type = name.includes(\".\") ? \"property\" : \"argument\";\n msg += `\"${name}\" ${type} `;\n }\n msg += \"must be \";\n const types = [];\n const instances = [];\n const other = [];\n for (const value of expected) {\n // assert(typeof value === 'string',\n // 'All expected entries have to be of type string');\n if (kTypes.includes(value)) {\n types.push(value.toLowerCase());\n }\n else if (classRegExp.exec(value) !== null) {\n instances.push(value);\n }\n else {\n // assert(value !== 'object',\n // 'The value \"object\" should be written as \"Object\"');\n other.push(value);\n }\n }\n // Special handle `object` in case other instances are allowed to outline\n // the differences between each other.\n if (instances.length > 0) {\n const pos = types.indexOf(\"object\");\n if (pos !== -1) {\n types.splice(pos, 1);\n instances.push(\"Object\");\n }\n }\n if (types.length > 0) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}`;\n }\n else {\n msg += `of type ${types[0]}`;\n }\n if (instances.length > 0 || other.length > 0)\n msg += \" or \";\n }\n if (instances.length > 0) {\n if (instances.length > 2) {\n const last = instances.pop();\n msg += `an instance of ${instances.join(\", \")}, or ${last}`;\n }\n else {\n msg += `an instance of ${instances[0]}`;\n if (instances.length === 2) {\n msg += ` or ${instances[1]}`;\n }\n }\n if (other.length > 0)\n msg += \" or \";\n }\n if (other.length > 0) {\n if (other.length > 2) {\n const last = other.pop();\n msg += `one of ${other.join(\", \")}, or ${last}`;\n }\n else if (other.length === 2) {\n msg += `one of ${other[0]} or ${other[1]}`;\n }\n else {\n if (other[0].toLowerCase() !== other[0])\n msg += \"an \";\n msg += `${other[0]}`;\n }\n }\n msg += `. Received ${determineSpecificType(actual)}`;\n super(msg);\n }\n}\nexport class ERR_INVALID_HTTP_TOKEN extends TypeError {\n constructor(name, field) {\n super(`${name} must be a valid HTTP token [\"${field}\"]`);\n }\n}\nexport class ERR_METHOD_NOT_IMPLEMENTED extends Error {\n constructor(methodName) {\n super(`The ${methodName} method is not implemented`);\n }\n}\nexport class ERR_STREAM_ALREADY_FINISHED extends Error {\n constructor(methodName) {\n super(`Cannot call ${methodName} after a stream was finished`);\n }\n}\nexport class ERR_STREAM_CANNOT_PIPE extends Error {\n constructor() {\n super(`Cannot pipe, not readable`);\n }\n}\nexport class ERR_STREAM_DESTROYED extends Error {\n constructor(methodName) {\n super(`Cannot call ${methodName} after a stream was destroyed`);\n }\n}\nexport class ERR_STREAM_NULL_VALUES extends TypeError {\n constructor() {\n super(`May not write null values to stream`);\n }\n}\nexport class ERR_STREAM_WRITE_AFTER_END extends Error {\n constructor() {\n super(`write after end`);\n }\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n// This file modeled after Node.js - node/lib/_http_incoming.js\nimport { Readable } from \"node:stream\";\nimport { ERR_METHOD_NOT_IMPLEMENTED } from \"../utils/errors.js\";\nconst kHeaders = Symbol(\"kHeaders\");\nconst kHeadersDistinct = Symbol(\"kHeadersDistinct\");\nconst kHeadersCount = Symbol(\"kHeadersCount\");\nconst kTrailers = Symbol(\"kTrailers\");\nconst kTrailersDistinct = Symbol(\"kTrailersDistinct\");\nconst kTrailersCount = Symbol(\"kTrailersCount\");\n/**\n * This is an implementation of IncomingMessage from Node.js intended to run in\n * a WinterTC runtime. The 'Readable' interface of this class is wired to a 'Request'\n * object's 'body'.\n *\n * This instance can be used in normal ways, but it does not give access to the\n * underlying socket (because there isn't one. req.socket will always return null).\n *\n * Some code in this class is transplanted/adapted from node/lib/_http_incoming.js\n */\nexport class FetchIncomingMessage extends Readable {\n get socket() {\n // Difference from Node.js -\n // We don't really have a way to support direct access to the socket\n return null;\n }\n set socket(_val) {\n // Difference from Node.js -\n // We don't really have a way to support direct access to the socket\n throw new ERR_METHOD_NOT_IMPLEMENTED(\"socket\");\n }\n httpVersionMajor;\n httpVersionMinor;\n httpVersion;\n complete = false;\n [kHeaders] = null;\n [kHeadersDistinct] = null;\n [kHeadersCount] = 0;\n rawHeaders = [];\n [kTrailers] = null;\n [kTrailersDistinct] = null;\n [kTrailersCount] = 0;\n rawTrailers = [];\n joinDuplicateHeaders = false;\n aborted = false;\n upgrade = false;\n // request (server) only\n url = \"\";\n method;\n // TODO: Support ClientRequest\n // statusCode = null;\n // statusMessage = null;\n // client = socket;\n _consuming;\n _dumped;\n // The underlying ReadableStream\n _stream = null;\n constructor() {\n const streamOptions = {};\n // Difference from Node.js -\n // In Node.js, if the IncomingMessages is associated with a socket then\n // that socket's 'readableHighWaterMark' would be used to set\n // streamOptions.highWaterMark before calling parent constructor.\n super(streamOptions);\n this._readableState.readingMore = true;\n this._consuming = false;\n // Flag for when we decide that this message cannot possibly be\n // read by the user, so there's no point continuing to handle it.\n this._dumped = false;\n }\n get connection() {\n // Difference from Node.js -\n // We don't really have a way to support direct access to the socket\n return null;\n }\n set connection(_socket) {\n // Difference from Node.js -\n // We don't really have a way to support direct access to the socket\n console.error(\"No support for IncomingMessage.connection\");\n }\n get headers() {\n if (!this[kHeaders]) {\n this[kHeaders] = {};\n const src = this.rawHeaders;\n const dst = this[kHeaders];\n for (let n = 0; n < this[kHeadersCount]; n += 2) {\n this._addHeaderLine(src[n], src[n + 1], dst);\n }\n }\n return this[kHeaders];\n }\n set headers(val) {\n this[kHeaders] = val;\n }\n get headersDistinct() {\n if (!this[kHeadersDistinct]) {\n this[kHeadersDistinct] = {};\n const src = this.rawHeaders;\n const dst = this[kHeadersDistinct];\n for (let n = 0; n < this[kHeadersCount]; n += 2) {\n this._addHeaderLineDistinct(src[n], src[n + 1], dst);\n }\n }\n return this[kHeadersDistinct];\n }\n set headersDistinct(val) {\n this[kHeadersDistinct] = val;\n }\n get trailers() {\n if (!this[kTrailers]) {\n this[kTrailers] = {};\n const src = this.rawTrailers;\n const dst = this[kTrailers];\n for (let n = 0; n < this[kTrailersCount]; n += 2) {\n this._addHeaderLine(src[n], src[n + 1], dst);\n }\n }\n return this[kTrailers];\n }\n set trailers(val) {\n this[kTrailers] = val;\n }\n get trailersDistinct() {\n if (!this[kTrailersDistinct]) {\n this[kTrailersDistinct] = {};\n const src = this.rawTrailers;\n const dst = this[kTrailersDistinct];\n for (let n = 0; n < this[kTrailersCount]; n += 2) {\n this._addHeaderLineDistinct(src[n], src[n + 1], dst);\n }\n }\n return this[kTrailersDistinct];\n }\n set trailersDistinct(val) {\n this[kTrailersDistinct] = val;\n }\n setTimeout(msecs, callback) {\n // Difference from Node.js -\n // In Node.js, this is supposed to set the underlying socket to time out\n // after some time and then run a callback.\n // We do nothing here since we don't really have a way to support direct\n // access to the socket.\n return this;\n }\n async _read(n) {\n // As this is an implementation of stream.Readable, we provide a _read()\n // function that pumps the next chunk out of the underlying ReadableStream.\n if (!this._consuming) {\n this._readableState.readingMore = false;\n this._consuming = true;\n }\n // Difference from Node.js -\n // The Node.js implementation will already have its internal buffer\n // filled by the parserOnBody function.\n // For our implementation, we use the ReadableStream instance.\n if (this._stream == null) {\n // For GET and HEAD requests, the stream would be empty.\n // Simply signal that we're done.\n this.complete = true;\n this.push(null);\n return;\n }\n const reader = this._stream.getReader();\n try {\n const data = await reader.read();\n if (data.done) {\n // Done with stream, tell Readable we have no more data;\n this.complete = true;\n this.push(null);\n }\n else {\n this.push(data.value);\n }\n }\n catch (e) {\n this.destroy(e);\n }\n finally {\n reader.releaseLock();\n }\n }\n _destroy(err, cb) {\n if (!this.readableEnded || !this.complete) {\n this.aborted = true;\n this.emit(\"aborted\");\n }\n // Difference from Node.js -\n // Node.js would check for the existence of the socket and do some additional\n // cleanup.\n // By the way, I believe this name 'onError' is misleading, it is called\n // regardless of whether there was an error. The callback is expected to\n // check for the existence of the error to decide whether the result was\n // actually an error.\n setTimeout(onError, 0, this, err, cb);\n }\n _addHeaderLines(headers, n) {\n if (headers?.length) {\n let dest;\n if (this.complete) {\n this.rawTrailers = headers;\n this[kTrailersCount] = n;\n dest = this[kTrailers];\n }\n else {\n this.rawHeaders = headers;\n this[kHeadersCount] = n;\n dest = this[kHeaders];\n }\n if (dest) {\n for (let i = 0; i < n; i += 2) {\n this._addHeaderLine(headers[i], headers[i + 1], dest);\n }\n }\n }\n }\n // Add the given (field, value) pair to the message\n //\n // Per RFC2616, section 4.2 it is acceptable to join multiple instances of the\n // same header with a ', ' if the header in question supports specification of\n // multiple values this way. The one exception to this is the Cookie header,\n // which has multiple values joined with a '; ' instead. If a header's values\n // cannot be joined in either of these ways, we declare the first instance the\n // winner and drop the second. Extended header fields (those beginning with\n // 'x-') are always joined.\n _addHeaderLine(field, value, dest) {\n field = matchKnownFields(field);\n const flag = field.charCodeAt(0);\n if (flag === 0 || flag === 2) {\n field = field.slice(1);\n // Make a delimited list\n if (typeof dest[field] === \"string\") {\n dest[field] += (flag === 0 ? \", \" : \"; \") + value;\n }\n else {\n dest[field] = value;\n }\n }\n else if (flag === 1) {\n // Array header -- only Set-Cookie at the moment\n if (dest[\"set-cookie\"] !== undefined) {\n dest[\"set-cookie\"].push(value);\n }\n else {\n dest[\"set-cookie\"] = [value];\n }\n }\n else if (this.joinDuplicateHeaders) {\n // RFC 9110 https://www.rfc-editor.org/rfc/rfc9110#section-5.2\n // https://github.com/nodejs/node/issues/45699\n // allow authorization multiple fields\n // Make a delimited list\n if (dest[field] === undefined) {\n dest[field] = value;\n }\n else {\n dest[field] += \", \" + value;\n }\n }\n else if (dest[field] === undefined) {\n // Drop duplicates\n dest[field] = value;\n }\n }\n _addHeaderLineDistinct(field, value, dest) {\n field = field.toLowerCase();\n if (!dest[field]) {\n dest[field] = [value];\n }\n else {\n dest[field].push(value);\n }\n }\n // Call this instead of resume() if we want to just\n // dump all the data to /dev/null\n _dump() {\n if (!this._dumped) {\n this._dumped = true;\n // If there is buffered data, it may trigger 'data' events.\n // Remove 'data' event listeners explicitly.\n this.removeAllListeners(\"data\");\n this.resume();\n }\n }\n}\n/* These items copied from Node.js: node/lib/_http_incoming.js, because they are not exported from that file. */\n// This function is used to help avoid the lowercasing of a field name if it\n// matches a 'traditional cased' version of a field name. It then returns the\n// lowercased name to both avoid calling toLowerCase() a second time and to\n// indicate whether the field was a 'no duplicates' field. If a field is not a\n// 'no duplicates' field, a `0` byte is prepended as a flag. The one exception\n// to this is the Set-Cookie header which is indicated by a `1` byte flag, since\n// it is an 'array' field and thus is treated differently in _addHeaderLines().\n// TODO: perhaps http_parser could be returning both raw and lowercased versions\n// of known header names to avoid us having to call toLowerCase() for those\n// headers.\nfunction matchKnownFields(field, lowercased = false) {\n switch (field.length) {\n case 3:\n if (field === \"Age\" || field === \"age\")\n return \"age\";\n break;\n case 4:\n if (field === \"Host\" || field === \"host\")\n return \"host\";\n if (field === \"From\" || field === \"from\")\n return \"from\";\n if (field === \"ETag\" || field === \"etag\")\n return \"etag\";\n if (field === \"Date\" || field === \"date\")\n return \"\\u0000date\";\n if (field === \"Vary\" || field === \"vary\")\n return \"\\u0000vary\";\n break;\n case 6:\n if (field === \"Server\" || field === \"server\")\n return \"server\";\n if (field === \"Cookie\" || field === \"cookie\")\n return \"\\u0002cookie\";\n if (field === \"Origin\" || field === \"origin\")\n return \"\\u0000origin\";\n if (field === \"Expect\" || field === \"expect\")\n return \"\\u0000expect\";\n if (field === \"Accept\" || field === \"accept\")\n return \"\\u0000accept\";\n break;\n case 7:\n if (field === \"Referer\" || field === \"referer\")\n return \"referer\";\n if (field === \"Expires\" || field === \"expires\")\n return \"expires\";\n if (field === \"Upgrade\" || field === \"upgrade\")\n return \"\\u0000upgrade\";\n break;\n case 8:\n if (field === \"Location\" || field === \"location\")\n return \"location\";\n if (field === \"If-Match\" || field === \"if-match\")\n return \"\\u0000if-match\";\n break;\n case 10:\n if (field === \"User-Agent\" || field === \"user-agent\")\n return \"user-agent\";\n if (field === \"Set-Cookie\" || field === \"set-cookie\")\n return \"\\u0001\";\n if (field === \"Connection\" || field === \"connection\")\n return \"\\u0000connection\";\n break;\n case 11:\n if (field === \"Retry-After\" || field === \"retry-after\")\n return \"retry-after\";\n break;\n case 12:\n if (field === \"Content-Type\" || field === \"content-type\")\n return \"content-type\";\n if (field === \"Max-Forwards\" || field === \"max-forwards\")\n return \"max-forwards\";\n break;\n case 13:\n if (field === \"Authorization\" || field === \"authorization\")\n return \"authorization\";\n if (field === \"Last-Modified\" || field === \"last-modified\")\n return \"last-modified\";\n if (field === \"Cache-Control\" || field === \"cache-control\")\n return \"\\u0000cache-control\";\n if (field === \"If-None-Match\" || field === \"if-none-match\")\n return \"\\u0000if-none-match\";\n break;\n case 14:\n if (field === \"Content-Length\" || field === \"content-length\")\n return \"content-length\";\n break;\n case 15:\n if (field === \"Accept-Encoding\" || field === \"accept-encoding\")\n return \"\\u0000accept-encoding\";\n if (field === \"Accept-Language\" || field === \"accept-language\")\n return \"\\u0000accept-language\";\n if (field === \"X-Forwarded-For\" || field === \"x-forwarded-for\")\n return \"\\u0000x-forwarded-for\";\n break;\n case 16:\n if (field === \"Content-Encoding\" || field === \"content-encoding\")\n return \"\\u0000content-encoding\";\n if (field === \"X-Forwarded-Host\" || field === \"x-forwarded-host\")\n return \"\\u0000x-forwarded-host\";\n break;\n case 17:\n if (field === \"If-Modified-Since\" || field === \"if-modified-since\")\n return \"if-modified-since\";\n if (field === \"Transfer-Encoding\" || field === \"transfer-encoding\")\n return \"\\u0000transfer-encoding\";\n if (field === \"X-Forwarded-Proto\" || field === \"x-forwarded-proto\")\n return \"\\u0000x-forwarded-proto\";\n break;\n case 19:\n if (field === \"Proxy-Authorization\" || field === \"proxy-authorization\")\n return \"proxy-authorization\";\n if (field === \"If-Unmodified-Since\" || field === \"if-unmodified-since\")\n return \"if-unmodified-since\";\n break;\n }\n if (lowercased) {\n return \"\\u0000\" + field;\n }\n return matchKnownFields(field.toLowerCase(), true);\n}\nfunction onError(self, error, cb) {\n // This is to keep backward compatible behavior.\n // An error is emitted only if there are listeners attached to the event.\n if (self.listenerCount(\"error\") === 0) {\n cb();\n }\n else {\n cb(error);\n }\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\nimport { ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE } from \"./errors.js\";\n/* These items copied from Node.js: node/lib/internal/validators.js */\nexport function validateString(value, name) {\n if (typeof value !== \"string\")\n throw new ERR_INVALID_ARG_TYPE(name, \"string\", value);\n}\nconst linkValueRegExp = /^(?:<[^>]*>)(?:\\s*;\\s*[^;\"\\s]+(?:=(\")?[^;\"\\s]*\\1)?)*$/;\nexport function validateLinkHeaderFormat(value, name) {\n if (typeof value === \"undefined\" || !linkValueRegExp.exec(value)) {\n throw new ERR_INVALID_ARG_VALUE(name, value, 'must be an array or string of format \"</styles.css>; rel=preload; as=style\"');\n }\n}\nexport function validateLinkHeaderValue(hints) {\n if (typeof hints === \"string\") {\n validateLinkHeaderFormat(hints, \"hints\");\n return hints;\n }\n else if (Array.isArray(hints)) {\n const hintsLength = hints.length;\n let result = \"\";\n if (hintsLength === 0) {\n return result;\n }\n for (let i = 0; i < hintsLength; i++) {\n const link = hints[i];\n validateLinkHeaderFormat(link, \"hints\");\n result += link;\n if (i !== hintsLength - 1) {\n result += \", \";\n }\n }\n return result;\n }\n throw new ERR_INVALID_ARG_VALUE(\"hints\", hints, 'must be an array or string of format \"</styles.css>; rel=preload; as=style\"');\n}\n/* These items copied from Node.js: node/lib/internal/util/types.js */\nexport function isUint8Array(value) {\n return value != null && value[Symbol.toStringTag] === \"Uint8Array\";\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n/* These items copied from Node.js: node/lib/internal/http.js. */\nexport const kNeedDrain = Symbol(\"kNeedDrain\");\nexport const kOutHeaders = Symbol(\"kOutHeaders\");\n// In Node.js this utcDate is cached for 1 second, for use across\n// all http connections. However, in C@E we just create a new one\n// since we're not able to share this data across separate invocations.\nexport function utcDate() {\n return new Date().toUTCString();\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n/* These items copied from Node.js: node/lib/internal/streams/state.js. */\nexport function getDefaultHighWaterMark(objectMode) {\n return objectMode ? 16 : 64 * 1024;\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n/* These items copied from Node.js: node/lib/_http_common.js. */\nconst tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/;\n/**\n * Verifies that the given val is a valid HTTP token\n * per the rules defined in RFC 7230\n * See https://tools.ietf.org/html/rfc7230#section-3.2.6\n */\nexport function checkIsHttpToken(val) {\n return tokenRegExp.test(val);\n}\nconst headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n/**\n * True if val contains an invalid field-vchar\n * field-value = *( field-content / obs-fold )\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n */\nexport function checkInvalidHeaderChar(val) {\n return headerCharRegex.test(val);\n}\nexport const chunkExpression = /(?:^|\\W)chunked(?:$|\\W)/i;\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n// This file modeled after Node.js - node/lib/_http_outgoing.js\nimport { Buffer } from \"node:buffer\";\nimport { Writable } from \"node:stream\";\nimport { ERR_HTTP_BODY_NOT_ALLOWED, ERR_HTTP_CONTENT_LENGTH_MISMATCH, ERR_HTTP_HEADERS_SENT, ERR_HTTP_INVALID_HEADER_VALUE, ERR_HTTP_TRAILER_INVALID, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_INVALID_CHAR, ERR_INVALID_HTTP_TOKEN, ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_ALREADY_FINISHED, ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END, } from \"../utils/errors.js\";\nimport { isUint8Array, validateString } from \"../utils/types.js\";\nimport { kNeedDrain, kOutHeaders, utcDate } from \"./internal-http.js\";\nimport { getDefaultHighWaterMark } from \"./internal-streams-state.js\";\nimport { checkInvalidHeaderChar, checkIsHttpToken, chunkExpression as RE_TE_CHUNKED, } from \"./http-common.js\";\n/* These items copied from Node.js: node/lib/_http_outgoing.js. */\nfunction debug(format) {\n // console.log(\"http \" + format);\n}\nconst kCorked = Symbol(\"corked\");\nconst kChunkedBuffer = Symbol(\"kChunkedBuffer\");\nconst kChunkedLength = Symbol(\"kChunkedLength\");\nconst kUniqueHeaders = Symbol(\"kUniqueHeaders\");\nconst kBytesWritten = Symbol(\"kBytesWritten\");\nconst kErrored = Symbol(\"errored\");\nconst kHighWaterMark = Symbol(\"kHighWaterMark\");\nconst kRejectNonStandardBodyWrites = Symbol(\"kRejectNonStandardBodyWrites\");\nconst nop = () => { };\nconst RE_CONN_CLOSE = /(?:^|\\W)close(?:$|\\W)/i;\n// isCookieField performs a case-insensitive comparison of a provided string\n// against the word \"cookie.\" As of V8 6.6 this is faster than handrolling or\n// using a case-insensitive RegExp.\nfunction isCookieField(s) {\n return s.length === 6 && s.toLowerCase() === \"cookie\";\n}\nfunction isContentDispositionField(s) {\n return s.length === 19 && s.toLowerCase() === \"content-disposition\";\n}\n/**\n * An in-memory buffer that stores the chunks that have been streamed to an\n * OutgoingMessage instance.\n */\nexport class WrittenDataBuffer {\n [kCorked] = 0;\n [kHighWaterMark] = getDefaultHighWaterMark();\n entries = [];\n onWrite;\n constructor(params = {}) {\n this.onWrite = params.onWrite;\n }\n write(data, encoding, callback) {\n this.entries.push({\n data,\n length: data.length,\n encoding,\n callback,\n written: false,\n });\n this._flush();\n return true;\n }\n cork() {\n this[kCorked]++;\n }\n uncork() {\n this[kCorked]--;\n this._flush();\n }\n _flush() {\n if (this[kCorked] <= 0) {\n for (const [index, entry] of this.entries.entries()) {\n if (!entry.written) {\n entry.written = true;\n if (this.onWrite != null) {\n this.onWrite(index, entry);\n }\n if (entry.callback != null) {\n entry.callback.call(undefined);\n }\n }\n }\n }\n }\n get writableLength() {\n return this.entries.reduce((acc, entry) => {\n return acc + (entry.written && entry.length ? entry.length : 0);\n }, 0);\n }\n get writableHighWaterMark() {\n return this[kHighWaterMark];\n }\n get writableCorked() {\n return this[kCorked];\n }\n}\n/**\n * This is an implementation of OutgoingMessage from Node.js intended to run in\n * a WinterTC runtime. The 'Writable' interface of this class is wired to an in-memory\n * buffer.\n *\n * This instance can be used in normal ways, but it does not give access to the\n * underlying socket (because there isn't one. req.socket will always return null).\n *\n * Some code in this class is transplanted/adapted from node/lib/_http_outgoing.js\n */\nexport class FetchOutgoingMessage extends Writable {\n req;\n outputData;\n outputSize;\n // Difference from Node.js -\n // `writtenHeaderBytes` is the number of bytes the header has taken.\n // Since Node.js writes both the headers and body into the same outgoing\n // stream, it helps to keep track of this so that we can skip that many bytes\n // from the beginning of the stream when providing the outgoing stream.\n writtenHeaderBytes = 0;\n _last;\n chunkedEncoding;\n shouldKeepAlive;\n maxRequestsOnConnectionReached;\n _defaultKeepAlive;\n useChunkedEncodingByDefault;\n sendDate;\n _removedConnection;\n _removedContLen;\n _removedTE;\n strictContentLength;\n [kBytesWritten];\n _contentLength;\n _hasBody;\n _trailer;\n [kNeedDrain];\n finished;\n _headerSent;\n [kCorked];\n [kChunkedBuffer];\n [kChunkedLength];\n _closed;\n // Difference from Node.js -\n // In Node.js, this is a socket object.\n // [kSocket]: null;\n _header;\n [kOutHeaders];\n _keepAliveTimeout;\n _maxRequestsPerSocket;\n _onPendingData;\n [kUniqueHeaders];\n [kErrored];\n [kHighWaterMark];\n [kRejectNonStandardBodyWrites];\n _writtenDataBuffer = new WrittenDataBuffer({\n onWrite: this._onDataWritten.bind(this),\n });\n constructor(req, options) {\n super();\n this.req = req;\n // Queue that holds all currently pending data, until the response will be\n // assigned to the socket (until it will its turn in the HTTP pipeline).\n this.outputData = [];\n // `outputSize` is an approximate measure of how much data is queued on this\n // response. `_onPendingData` will be invoked to update similar global\n // per-connection counter. That counter will be used to pause/unpause the\n // TCP socket and HTTP Parser and thus handle the backpressure.\n this.outputSize = 0;\n // Cannot assign to this.writable because it is a readonly property\n // this.writable = true;\n this.destroyed = false;\n this._last = false;\n this.chunkedEncoding = false;\n this.shouldKeepAlive = true;\n this.maxRequestsOnConnectionReached = false;\n this._defaultKeepAlive = true;\n this.useChunkedEncodingByDefault = true;\n this.sendDate = false;\n this._removedConnection = false;\n this._removedContLen = false;\n this._removedTE = false;\n this.strictContentLength = false;\n this[kBytesWritten] = 0;\n this._contentLength = null;\n this._hasBody = true;\n this._trailer = \"\";\n this[kNeedDrain] = false;\n this.finished = false;\n this._headerSent = false;\n this[kCorked] = 0;\n this[kChunkedBuffer] = [];\n this[kChunkedLength] = 0;\n this._closed = false;\n this._header = null;\n this[kOutHeaders] = null;\n this._keepAliveTimeout = 0;\n this._onPendingData = nop;\n this[kErrored] = null;\n this[kHighWaterMark] = options?.highWaterMark ?? getDefaultHighWaterMark();\n this[kRejectNonStandardBodyWrites] =\n options?.rejectNonStandardBodyWrites ?? false;\n this[kUniqueHeaders] = null;\n }\n _renderHeaders() {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"render\");\n }\n const headersMap = this[kOutHeaders];\n const headers = {};\n if (headersMap !== null) {\n const keys = Object.keys(headersMap);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0, l = keys.length; i < l; i++) {\n const key = keys[i];\n headers[headersMap[key][0]] = headersMap[key][1];\n }\n }\n return headers;\n }\n cork() {\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would call cork() on the socket instead\n // In our implementation, we do the same to the \"written data buffer\" instead.\n this[kCorked]++;\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.cork();\n }\n }\n uncork() {\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would call uncork() on the socket instead\n // In our implementation, we do the same to the \"written data buffer\" instead.\n this[kCorked]--;\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.uncork();\n }\n if (this[kCorked] || this[kChunkedBuffer].length === 0) {\n return;\n }\n // Difference from Node.js -\n // Chunked transfer encoding doesn't need to use the low-level protocol\n // (with each chunk preceded by its length)\n // All commented out code below is from Node.js used for this purpose.\n // const len = this[kChunkedLength];\n const buf = this[kChunkedBuffer];\n // assert(this.chunkedEncoding);\n // let callbacks: (WriteCallback | undefined)[] | undefined;\n // this._send(len.toString(16), \"latin1\", null);\n // this._send(crlf_buf, null, null);\n for (const { data, encoding, callback } of buf) {\n // this._send(data ?? \"\", encoding, null);\n // if (callback) {\n // callbacks ??= [];\n // callbacks.push(callback);\n // }\n this._send(data ?? \"\", encoding, callback);\n }\n // this._send(\n // crlf_buf,\n // null,\n // callbacks?.length\n // ? (err) => {\n // for (const callback of callbacks) {\n // callback?.(err);\n // }\n // }\n // : null\n // );\n this[kChunkedBuffer].length = 0;\n this[kChunkedLength] = 0;\n }\n setTimeout(msecs, callback) {\n // Difference from Node.js -\n // In Node.js, this is supposed to set the underlying socket to time out\n // after some time and then run a callback.\n // We do nothing here since we don't really have a way to support direct\n // access to the socket.\n return this;\n }\n destroy(error) {\n if (this.destroyed) {\n return this;\n }\n this.destroyed = true;\n this[kErrored] = error;\n // Difference from Node.js -\n // In Node.js, we would also attempt to destroy the underlying socket.\n return this;\n }\n _send(data, encoding, callback, byteLength) {\n // This is a shameful hack to get the headers and first body chunk onto\n // the same packet. Future versions of Node are going to take care of\n // this at a lower level and in a more general way.\n if (!this._headerSent) {\n const header = this._header;\n if (typeof data === \"string\" &&\n (encoding === \"utf8\" || encoding === \"latin1\" || !encoding)) {\n data = header + data;\n }\n else {\n this.outputData.unshift({\n data: header,\n encoding: \"latin1\",\n callback: undefined,\n });\n this.outputSize += header.length;\n this._onPendingData(header.length);\n }\n this._headerSent = true;\n // Difference from Node.js -\n // Parse headers here and trigger _headersSent\n this.writtenHeaderBytes = header.length;\n // Save written headers as object\n const [statusLine, ...headerLines] = this._header.split(\"\\r\\n\");\n const STATUS_LINE_REGEXP = /^HTTP\\/1\\.1 (?<statusCode>\\d+) (?<statusMessage>.*)$/;\n const statusLineResult = STATUS_LINE_REGEXP.exec(statusLine);\n if (statusLineResult == null) {\n throw new Error(\"Unexpected! Status line was \" + statusLine);\n }\n const { statusCode: statusCodeText, statusMessage } = statusLineResult.groups ?? {};\n const statusCode = parseInt(statusCodeText, 10);\n const headers = [];\n for (const headerLine of headerLines) {\n if (headerLine !== \"\") {\n const pos = headerLine.indexOf(\": \");\n const k = headerLine.slice(0, pos);\n const v = headerLine.slice(pos + 2); // Skip the colon and the space\n headers.push([k, v]);\n }\n }\n const event = {\n statusCode,\n statusMessage,\n headers,\n };\n this.emit(\"_headersSent\", event);\n }\n return this._writeRaw(data, encoding, callback, byteLength);\n }\n _writeRaw(data, encoding, callback, size) {\n // Difference from Node.js -\n // In Node.js, we would check for an underlying socket, and if that socket\n // exists and is already destroyed, simply return false.\n if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n // Difference from Node.js -\n // In Node.js, we would check for an underlying socket, and if that socket\n // exists and is currently writable, it would flush any pending data to the socket and then\n // write the current chunk's data directly into the socket. Afterwards, it would return with the\n // value returned from socket.write().\n // In our implementation, instead we do the same for the \"written data buffer\".\n if (this._writtenDataBuffer != null) {\n // There might be pending data in the this.output buffer.\n if (this.outputData.length) {\n this._flushOutput(this._writtenDataBuffer);\n }\n // Directly write to the buffer.\n return this._writtenDataBuffer.write(data, encoding, callback);\n }\n // Buffer, as long as we're not destroyed.\n this.outputData.push({ data, encoding, callback });\n this.outputSize += data.length;\n this._onPendingData(data.length);\n return this.outputSize < this[kHighWaterMark];\n }\n _onDataWritten(index, entry) {\n const event = { index, entry };\n this.emit(\"_dataWritten\", event);\n }\n _storeHeader(firstLine, headers) {\n // firstLine in the case of request is: 'GET /index.html HTTP/1.1\\r\\n'\n // in the case of response it is: 'HTTP/1.1 200 OK\\r\\n'\n const state = {\n connection: false,\n contLen: false,\n te: false,\n date: false,\n expect: false,\n trailer: false,\n header: firstLine,\n };\n if (headers) {\n if (headers === this[kOutHeaders]) {\n for (const key in headers) {\n const entry = headers[key];\n processHeader(this, state, entry[0], entry[1], false);\n }\n }\n else if (Array.isArray(headers)) {\n if (headers.length && Array.isArray(headers[0])) {\n for (let i = 0; i < headers.length; i++) {\n const entry = headers[i];\n processHeader(this, state, entry[0], entry[1], true);\n }\n }\n else {\n if (headers.length % 2 !== 0) {\n throw new ERR_INVALID_ARG_VALUE(\"headers\", headers);\n }\n for (let n = 0; n < headers.length; n += 2) {\n processHeader(this, state, headers[n], headers[n + 1], true);\n }\n }\n }\n else {\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n const _headers = headers;\n processHeader(this, state, key, _headers[key], true);\n }\n }\n }\n }\n let { header } = state;\n // Date header\n if (this.sendDate && !state.date) {\n header += \"Date: \" + utcDate() + \"\\r\\n\";\n }\n // Force the connection to close when the response is a 204 No Content or\n // a 304 Not Modified and the user has set a \"Transfer-Encoding: chunked\"\n // header.\n //\n // RFC 2616 mandates that 204 and 304 responses MUST NOT have a body but\n // node.js used to send out a zero chunk anyway to accommodate clients\n // that don't have special handling for those responses.\n //\n // It was pointed out that this might confuse reverse proxies to the point\n // of creating security liabilities, so suppress the zero chunk and force\n // the connection to close.\n // NOTE: the \"as any\" here is needed because 'statusCode' is only\n // defined on the subclass but is used here.\n if (this.chunkedEncoding &&\n (this.statusCode === 204 || this.statusCode === 304)) {\n debug(this.statusCode +\n \" response should not use chunked encoding,\" +\n \" closing connection.\");\n this.chunkedEncoding = false;\n this.shouldKeepAlive = false;\n }\n // keep-alive logic\n if (this._removedConnection) {\n // shouldKeepAlive is generally true for HTTP/1.1. In that common case,\n // even if the connection header isn't sent, we still persist by default.\n this._last = !this.shouldKeepAlive;\n }\n else if (!state.connection) {\n // this.agent would only exist on class ClientRequest\n const shouldSendKeepAlive = this.shouldKeepAlive &&\n (state.contLen || this.useChunkedEncodingByDefault); /* || this.agent */\n if (shouldSendKeepAlive && this.maxRequestsOnConnectionReached) {\n header += \"Connection: close\\r\\n\";\n }\n else if (shouldSendKeepAlive) {\n header += \"Connection: keep-alive\\r\\n\";\n if (this._keepAliveTimeout && this._defaultKeepAlive) {\n const timeoutSeconds = Math.floor(this._keepAliveTimeout / 1000);\n let max = \"\";\n if (this._maxRequestsPerSocket && ~~this._maxRequestsPerSocket > 0) {\n max = `, max=${this._maxRequestsPerSocket}`;\n }\n header += `Keep-Alive: timeout=${timeoutSeconds}${max}\\r\\n`;\n }\n }\n else {\n this._last = true;\n header += \"Connection: close\\r\\n\";\n }\n }\n if (!state.contLen && !state.te) {\n if (!this._hasBody) {\n // Make sure we don't end the 0\\r\\n\\r\\n at the end of the message.\n this.chunkedEncoding = false;\n }\n else if (!this.useChunkedEncodingByDefault) {\n this._last = true;\n }\n else if (!state.trailer &&\n !this._removedContLen &&\n typeof this._contentLength === \"number\") {\n header += \"Content-Length: \" + this._contentLength + \"\\r\\n\";\n }\n else if (!this._removedTE) {\n header += \"Transfer-Encoding: chunked\\r\\n\";\n this.chunkedEncoding = true;\n }\n else {\n // We should only be able to get here if both Content-Length and\n // Transfer-Encoding are removed by the user.\n // See: test/parallel/test-http-remove-header-stays-removed.js\n debug(\"Both Content-Length and Transfer-Encoding are removed\");\n // We can't keep alive in this case, because with no header info the body\n // is defined as all data until the connection is closed.\n this._last = true;\n }\n }\n // Test non-chunked message does not have trailer header set,\n // message will be terminated by the first empty line after the\n // header fields, regardless of the header fields present in the\n // message, and thus cannot contain a message body or 'trailers'.\n if (this.chunkedEncoding !== true && state.trailer) {\n throw new ERR_HTTP_TRAILER_INVALID();\n }\n this._header = header + \"\\r\\n\";\n this._headerSent = false;\n // Wait until the first body chunk, or close(), is sent to flush,\n // UNLESS we're sending Expect: 100-continue.\n if (state.expect) {\n this._send(\"\");\n }\n }\n get _headers() {\n console.warn(\"DEP0066: OutgoingMessage.prototype._headers is deprecated\");\n return this.getHeaders();\n }\n set _headers(val) {\n console.warn(\"DEP0066: OutgoingMessage.prototype._headers is deprecated\");\n if (val == null) {\n this[kOutHeaders] = null;\n }\n else if (typeof val === \"object\") {\n const headers = (this[kOutHeaders] = Object.create(null));\n const keys = Object.keys(val);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; ++i) {\n const name = keys[i];\n headers[name.toLowerCase()] = [name, val[name]];\n }\n }\n }\n get connection() {\n // Difference from Node.js -\n // Connection is not supported\n return null;\n }\n set connection(_socket) {\n // Difference from Node.js -\n // Connection is not supported\n console.error(\"No support for OutgoingMessage.connection\");\n }\n get socket() {\n // Difference from Node.js -\n // socket is not supported\n return null;\n }\n set socket(_socket) {\n // Difference from Node.js -\n // socket is not supported\n console.error(\"No support for OutgoingMessage.socket\");\n }\n get _headerNames() {\n console.warn(\"DEP0066: OutgoingMessage.prototype._headerNames is deprecated\");\n const headers = this[kOutHeaders];\n if (headers !== null) {\n const out = Object.create(null);\n const keys = Object.keys(headers);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n const val = headers[key][0];\n out[key] = val;\n }\n return out;\n }\n return null;\n }\n set _headerNames(val) {\n console.warn(\"DEP0066: OutgoingMessage.prototype._headerNames is deprecated\");\n if (typeof val === \"object\" && val !== null) {\n const headers = this[kOutHeaders];\n if (!headers)\n return;\n const keys = Object.keys(val);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; ++i) {\n const header = headers[keys[i]];\n if (header)\n header[0] = val[keys[i]];\n }\n }\n }\n setHeader(name, value) {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"set\");\n }\n validateHeaderName(name);\n validateHeaderValue(name, value);\n let headers = this[kOutHeaders];\n if (headers === null) {\n this[kOutHeaders] = headers = { __proto__: null };\n }\n headers[name.toLowerCase()] = [name, value];\n return this;\n }\n setHeaders(headers) {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"set\");\n }\n if (!headers ||\n Array.isArray(headers) ||\n typeof headers.keys !== \"function\" ||\n typeof headers.get !== \"function\") {\n throw new ERR_INVALID_ARG_TYPE(\"headers\", [\"Headers\", \"Map\"], headers);\n }\n // Headers object joins multiple cookies with a comma when using\n // the getter to retrieve the value,\n // unless iterating over the headers directly.\n // We also cannot safely split by comma.\n // To avoid setHeader overwriting the previous value we push\n // set-cookie values in array and set them all at once.\n const cookies = [];\n for (const { 0: key, 1: value } of headers) {\n if (key === \"set-cookie\") {\n if (Array.isArray(value)) {\n cookies.push(...value);\n }\n else {\n cookies.push(value);\n }\n continue;\n }\n this.setHeader(key, value);\n }\n if (cookies.length) {\n this.setHeader(\"set-cookie\", cookies);\n }\n return this;\n }\n appendHeader(name, value) {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"append\");\n }\n validateHeaderName(name);\n validateHeaderValue(name, value);\n const field = name.toLowerCase();\n const headers = this[kOutHeaders];\n if (headers === null || !headers[field]) {\n return this.setHeader(name, value);\n }\n // Prepare the field for appending, if required\n if (!Array.isArray(headers[field][1])) {\n headers[field][1] = [headers[field][1]];\n }\n const existingValues = headers[field][1];\n if (Array.isArray(value)) {\n for (let i = 0, length = value.length; i < length; i++) {\n existingValues.push(value[i]);\n }\n }\n else {\n existingValues.push(value);\n }\n return this;\n }\n getHeader(name) {\n validateString(name, \"name\");\n const headers = this[kOutHeaders];\n if (headers === null) {\n return;\n }\n const entry = headers[name.toLowerCase()];\n return entry?.[1];\n }\n getHeaderNames() {\n return this[kOutHeaders] !== null ? Object.keys(this[kOutHeaders]) : [];\n }\n getRawHeaderNames() {\n const headersMap = this[kOutHeaders];\n if (headersMap === null)\n return [];\n const values = Object.values(headersMap);\n const headers = Array(values.length);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0, l = values.length; i < l; i++) {\n headers[i] = values[i][0];\n }\n return headers;\n }\n getHeaders() {\n const headers = this[kOutHeaders];\n const ret = { __proto__: null };\n if (headers) {\n const keys = Object.keys(headers);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n const val = headers[key][1];\n ret[key] = val;\n }\n }\n return ret;\n }\n hasHeader(name) {\n validateString(name, \"name\");\n return (this[kOutHeaders] !== null && !!this[kOutHeaders][name.toLowerCase()]);\n }\n removeHeader(name) {\n validateString(name, \"name\");\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"remove\");\n }\n const key = name.toLowerCase();\n switch (key) {\n case \"connection\":\n this._removedConnection = true;\n break;\n case \"content-length\":\n this._removedContLen = true;\n break;\n case \"transfer-encoding\":\n this._removedTE = true;\n break;\n case \"date\":\n this.sendDate = false;\n break;\n }\n if (this[kOutHeaders] !== null) {\n delete this[kOutHeaders][key];\n }\n }\n _implicitHeader() {\n throw new ERR_METHOD_NOT_IMPLEMENTED(\"_implicitHeader()\");\n }\n get headersSent() {\n return !!this._header;\n }\n write(chunk, encoding, callback) {\n if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n const ret = write_(this, chunk, encoding, callback, false);\n if (!ret) {\n this[kNeedDrain] = true;\n }\n return ret;\n }\n addTrailers(headers) {\n this._trailer = \"\";\n const isArray = Array.isArray(headers);\n const keys = isArray ? [...headers.keys()] : Object.keys(headers);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0, l = keys.length; i < l; i++) {\n let field, value;\n if (isArray) {\n const _headers = headers;\n const key = keys[i];\n field = _headers[key][0];\n value = _headers[key][1];\n }\n else {\n const _headers = headers;\n const key = keys[i];\n field = key;\n value = _headers[key];\n }\n validateHeaderName(field, \"Trailer name\");\n // Check if the field must be sent several times\n if (Array.isArray(value) &&\n value.length > 1 &&\n (!this[kUniqueHeaders] ||\n !this[kUniqueHeaders].has(field.toLowerCase()))) {\n for (let j = 0, l = value.length; j < l; j++) {\n if (checkInvalidHeaderChar(value[j])) {\n debug(`Trailer \"${field}\"[${j}] contains invalid characters`);\n throw new ERR_INVALID_CHAR(\"trailer content\", field);\n }\n this._trailer += field + \": \" + value[j] + \"\\r\\n\";\n }\n }\n else {\n if (Array.isArray(value)) {\n value = value.join(\"; \");\n }\n if (checkInvalidHeaderChar(String(value))) {\n debug(`Trailer \"${field}\" contains invalid characters`);\n throw new ERR_INVALID_CHAR(\"trailer content\", field);\n }\n this._trailer += field + \": \" + value + \"\\r\\n\";\n }\n }\n }\n end(chunk, encoding, callback) {\n if (typeof chunk === \"function\") {\n callback = chunk;\n chunk = null;\n encoding = null;\n }\n else if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n if (chunk) {\n if (this.finished) {\n onError(this, new ERR_STREAM_WRITE_AFTER_END(), typeof callback !== \"function\" ? nop : callback);\n return this;\n }\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would also call socket.cork() at this point.\n // For our implementation we do the same for the \"written data buffer\"\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.cork();\n }\n write_(this, chunk, encoding, null, true);\n }\n else if (this.finished) {\n if (typeof callback === \"function\") {\n if (!this.writableFinished) {\n this.on(\"finish\", callback);\n }\n else {\n callback(new ERR_STREAM_ALREADY_FINISHED(\"end\"));\n }\n }\n return this;\n }\n else if (!this._header) {\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would also call socket.cork() at this point.\n // For our implementation we do the same for the \"written data buffer\"\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.cork();\n }\n this._contentLength = 0;\n this._implicitHeader();\n }\n if (typeof callback === \"function\")\n this.once(\"finish\", callback);\n if (strictContentLength(this) &&\n this[kBytesWritten] !== this._contentLength) {\n throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten], this._contentLength);\n }\n const finish = onFinish.bind(undefined, this);\n if (this._hasBody && this.chunkedEncoding) {\n // Difference from Node.js -\n // Chunked transfer encoding doesn't need to use the low-level protocol\n // (with each chunk preceded by its length)\n // So here we just send an empty chunk. Trailers are not supported\n // this._send(\"0\\r\\n\" + this._trailer + \"\\r\\n\", \"latin1\", finish);\n this._send(\"\", \"latin1\", finish);\n }\n else if (!this._headerSent || this.writableLength || chunk) {\n this._send(\"\", \"latin1\", finish);\n }\n else {\n setTimeout(finish, 0);\n }\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would also call socket.uncork() at this point.\n // For our implementation we do the same for the \"written data buffer\"\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.uncork();\n }\n this[kCorked] = 1;\n this.uncork();\n this.finished = true;\n // There is the first message on the outgoing queue, and we've sent\n // everything to the socket.\n debug(\"outgoing message end.\");\n // Difference from Node.js -\n // In Node.js, if a socket exists, and there is no pending output data,\n // we would also call this._finish() at this point.\n // For our implementation we do the same for the \"written data buffer\"\n if (this.outputData.length === 0 && this._writtenDataBuffer != null) {\n this._finish();\n }\n return this;\n }\n _finish() {\n // Difference from Node.js -\n // In Node.js, this function is only called if a socket exists.\n // This function would assert() for a socket and then emit 'prefinish'.\n // For our implementation we do the same for the \"written data buffer\"\n this.emit(\"prefinish\");\n }\n // No _flush() implementation?\n _flush() {\n // Difference from Node.js -\n // In Node.js, this function is only called if a socket exists.\n // For our implementation we do the same for the \"written data buffer\"\n if (this._writtenDataBuffer != null) {\n // There might be remaining data in this.output; write it out\n const ret = this._flushOutput(this._writtenDataBuffer);\n if (this.finished) {\n // This is a queue to the server or client to bring in the next this.\n this._finish();\n }\n else if (ret && this[kNeedDrain]) {\n this[kNeedDrain] = false;\n this.emit(\"drain\");\n }\n }\n }\n _flushOutput(dataBuffer) {\n while (this[kCorked]) {\n this[kCorked]--;\n dataBuffer.cork();\n }\n const outputLength = this.outputData.length;\n if (outputLength <= 0) {\n return undefined;\n }\n const outputData = this.outputData;\n dataBuffer.cork();\n let ret;\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < outputLength; i++) {\n const { data, encoding, callback } = outputData[i]; // Avoid any potential ref to Buffer in new generation from old generation\n outputData[i].data = null;\n ret = dataBuffer.write(data ?? \"\", encoding, callback);\n }\n dataBuffer.uncork();\n this.outputData = [];\n this._onPendingData(-this.outputSize);\n this.outputSize = 0;\n return ret;\n }\n flushHeaders() {\n if (!this._header) {\n this._implicitHeader();\n }\n // Force-flush the headers.\n this._send(\"\");\n }\n pipe(destination) {\n // OutgoingMessage should be write-only. Piping from it is disabled.\n this.emit(\"error\", new ERR_STREAM_CANNOT_PIPE());\n return destination;\n }\n}\nfunction processHeader(self, state, key, value, validate) {\n if (validate) {\n validateHeaderName(key);\n }\n // If key is content-disposition and there is content-length\n // encode the value in latin1\n // https://www.rfc-editor.org/rfc/rfc6266#section-4.3\n // Refs: https://github.com/nodejs/node/pull/46528\n if (isContentDispositionField(key) && self._contentLength) {\n // The value could be an array here\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n value[i] = String(Buffer.from(String(value[i]), \"latin1\"));\n }\n }\n else {\n value = String(Buffer.from(String(value), \"latin1\"));\n }\n }\n if (Array.isArray(value)) {\n if ((value.length < 2 || !isCookieField(key)) &&\n (!self[kUniqueHeaders] || !self[kUniqueHeaders].has(key.toLowerCase()))) {\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < value.length; i++) {\n storeHeader(self, state, key, value[i], validate);\n }\n return;\n }\n value = value.join(\"; \");\n }\n storeHeader(self, state, key, String(value), validate);\n}\nfunction storeHeader(self, state, key, value, validate) {\n if (validate) {\n validateHeaderValue(key, value);\n }\n state.header += key + \": \" + value + \"\\r\\n\";\n matchHeader(self, state, key, value);\n}\nfunction validateHeaderName(name, label) {\n if (typeof name !== \"string\" || !name || !checkIsHttpToken(name)) {\n throw new ERR_INVALID_HTTP_TOKEN(label || \"Header name\", name);\n }\n}\nfunction validateHeaderValue(name, value) {\n if (value === undefined) {\n throw new ERR_HTTP_INVALID_HEADER_VALUE(String(value), name);\n }\n if (checkInvalidHeaderChar(String(value))) {\n debug(`Header \"${name}\" contains invalid characters`);\n throw new ERR_INVALID_CHAR(\"header content\", name);\n }\n}\nfunction matchHeader(self, state, field, value) {\n if (field.length < 4 || field.length > 17)\n return;\n field = field.toLowerCase();\n switch (field) {\n case \"connection\":\n state.connection = true;\n self._removedConnection = false;\n if (RE_CONN_CLOSE.exec(value) !== null)\n self._last = true;\n else\n self.shouldKeepAlive = true;\n break;\n case \"transfer-encoding\":\n state.te = true;\n self._removedTE = false;\n if (RE_TE_CHUNKED.exec(value) !== null)\n self.chunkedEncoding = true;\n break;\n case \"content-length\":\n state.contLen = true;\n self._contentLength = +value;\n self._removedContLen = false;\n break;\n case \"date\":\n case \"expect\":\n case \"trailer\":\n state[field] = true;\n break;\n case \"keep-alive\":\n self._defaultKeepAlive = false;\n break;\n }\n}\n// const crlf_buf = Buffer.from(\"\\r\\n\");\nfunction onError(msg, err, callback) {\n if (msg.destroyed) {\n return;\n }\n // Difference from Node.js -\n // In Node.js, we would check for the existence of a socket. If one exists, we would\n // use that async ID to scope the error.\n // Instead, we do this.\n setTimeout(emitErrorNt, 0, msg, err, callback);\n}\nfunction emitErrorNt(msg, err, callback) {\n callback(err);\n if (typeof msg.emit === \"function\" && !msg.destroyed) {\n msg.emit(\"error\", err);\n }\n}\nfunction strictContentLength(msg) {\n return (msg.strictContentLength &&\n msg._contentLength != null &&\n msg._hasBody &&\n !msg._removedContLen &&\n !msg.chunkedEncoding &&\n !msg.hasHeader(\"transfer-encoding\"));\n}\nfunction write_(msg, chunk, encoding, callback, fromEnd) {\n if (typeof callback !== \"function\") {\n callback = nop;\n }\n if (chunk === null) {\n throw new ERR_STREAM_NULL_VALUES();\n }\n else if (typeof chunk !== \"string\" && !isUint8Array(chunk)) {\n throw new ERR_INVALID_ARG_TYPE(\"chunk\", [\"string\", \"Buffer\", \"Uint8Array\"], chunk);\n }\n let err = undefined;\n if (msg.finished) {\n err = new ERR_STREAM_WRITE_AFTER_END();\n }\n else if (msg.destroyed) {\n err = new ERR_STREAM_DESTROYED(\"write\");\n }\n if (err) {\n if (!msg.destroyed) {\n onError(msg, err, callback);\n }\n else {\n setTimeout(callback, 0, err);\n }\n return false;\n }\n let len = undefined;\n if (msg.strictContentLength) {\n len ??=\n typeof chunk === \"string\"\n ? Buffer.byteLength(chunk, encoding ?? undefined)\n : chunk.byteLength;\n if (strictContentLength(msg) &&\n (fromEnd\n ? msg[kBytesWritten] + len !== msg._contentLength\n : msg[kBytesWritten] + len > (msg._contentLength ?? 0))) {\n throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(len + msg[kBytesWritten], msg._contentLength);\n }\n msg[kBytesWritten] += len;\n }\n if (!msg._header) {\n if (fromEnd) {\n len ??=\n typeof chunk === \"string\"\n ? Buffer.byteLength(chunk, encoding ?? undefined)\n : chunk.byteLength;\n msg._contentLength = len;\n }\n msg._implicitHeader();\n }\n if (!msg._hasBody) {\n if (msg[kRejectNonStandardBodyWrites]) {\n throw new ERR_HTTP_BODY_NOT_ALLOWED();\n }\n else {\n debug(\"This type of response MUST NOT have a body. \" +\n \"Ignoring write() calls.\");\n setTimeout(callback, 0);\n return true;\n }\n }\n // Difference from Node.js -\n // In Node.js, we would also check at this point if a socket exists and is not corked.\n // If so, we'd cork the socket and then queue up an 'uncork' for the next tick.\n // In our implementation we do the same for \"written data buffer\"\n if (!fromEnd &&\n msg._writtenDataBuffer != null &&\n !msg._writtenDataBuffer.writableCorked) {\n msg._writtenDataBuffer.cork();\n setTimeout(connectionCorkNT, 0, msg._writtenDataBuffer);\n }\n let ret;\n if (msg.chunkedEncoding && chunk.length !== 0) {\n len ??=\n typeof chunk === \"string\"\n ? Buffer.byteLength(chunk, encoding ?? undefined)\n : chunk.byteLength;\n if (msg[kCorked] && msg._headerSent) {\n msg[kChunkedBuffer].push({ data: chunk, encoding, callback });\n msg[kChunkedLength] += len;\n ret = msg[kChunkedLength] < msg[kHighWaterMark];\n }\n else {\n // Difference from Node.js -\n // Chunked transfer encoding doesn't need to use the low-level protocol\n // (with each chunk preceded by its length)\n // msg._send(len.toString(16), \"latin1\", null);\n // msg._send(crlf_buf, null, null);\n // msg._send(chunk, encoding, null, len);\n // ret = msg._send(crlf_buf, null, callback);\n ret = msg._send(chunk, encoding, callback, len);\n }\n }\n else {\n ret = msg._send(chunk, encoding, callback, len);\n }\n debug(\"write ret = \" + ret);\n return ret;\n}\nfunction connectionCorkNT(dataBuffer) {\n dataBuffer.uncork();\n}\nfunction onFinish(outmsg) {\n // Difference from Node.js -\n // In Node.js, if a socket exists and already had an error, we would simply return.\n outmsg.emit(\"finish\");\n}\n// Override some properties this way, because TypeScript won't let us override\n// properties with accessors.\nObject.defineProperties(FetchOutgoingMessage.prototype, {\n errored: {\n get() {\n return this[kErrored];\n },\n },\n closed: {\n get() {\n return this._closed;\n },\n },\n writableFinished: {\n get() {\n // Difference from Node.js -\n // In Node.js, there is one additional requirement --\n // there must be no underlying socket (or its writableLength must be 0).\n // In this implementation we will do the same against \"written data buffer\".\n return (this.finished &&\n this.outputSize === 0 &&\n (this._writtenDataBuffer == null ||\n this._writtenDataBuffer.writableLength === 0));\n },\n },\n writableObjectMode: {\n get() {\n return false;\n },\n },\n writableLength: {\n get() {\n // Difference from Node.js -\n // In Node.js, if a socket exists then that socket's writableLength is added to\n // this value.\n // In this implementation we will do the same against \"written data buffer\".\n return (this.outputSize +\n this[kChunkedLength] +\n (this._writtenDataBuffer != null\n ? this._writtenDataBuffer.writableLength\n : 0));\n },\n },\n writableHighWaterMark: {\n get() {\n // Difference from Node.js -\n // In Node.js, if a socket exists then use that socket's writableHighWaterMark\n // In this implementation we will do the same against \"written data buffer\".\n return this._writtenDataBuffer != null\n ? this._writtenDataBuffer.writableHighWaterMark\n : this[kHighWaterMark];\n },\n },\n writableCorked: {\n get() {\n return this[kCorked];\n },\n },\n writableEnded: {\n get() {\n return this.finished;\n },\n },\n writableNeedDrain: {\n get() {\n return !this.destroyed && !this.finished && this[kNeedDrain];\n },\n },\n});\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\nimport { Buffer } from \"node:buffer\";\nimport { ERR_HTTP_HEADERS_SENT, ERR_HTTP_INVALID_STATUS_CODE, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_INVALID_CHAR, ERR_METHOD_NOT_IMPLEMENTED, } from \"../utils/errors.js\";\nimport { FetchOutgoingMessage, } from \"./http-outgoing.js\";\nimport { chunkExpression } from \"./http-common.js\";\nimport { FetchIncomingMessage } from \"./http-incoming.js\";\nimport { kOutHeaders } from \"./internal-http.js\";\nimport { validateLinkHeaderValue } from \"../utils/types.js\";\n/* These items copied from Node.js: node/lib/_http_common.js. */\nconst headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n/**\n * True if val contains an invalid field-vchar\n * field-value = *( field-content / obs-fold )\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n */\nfunction checkInvalidHeaderChar(val) {\n return headerCharRegex.test(val);\n}\n// This file modeled after Node.js - node/lib/_http_server.js\nexport const STATUS_CODES = {\n 100: \"Continue\", // RFC 7231 6.2.1\n 101: \"Switching Protocols\", // RFC 7231 6.2.2\n 102: \"Processing\", // RFC 2518 10.1 (obsoleted by RFC 4918)\n 103: \"Early Hints\", // RFC 8297 2\n 200: \"OK\", // RFC 7231 6.3.1\n 201: \"Created\", // RFC 7231 6.3.2\n 202: \"Accepted\", // RFC 7231 6.3.3\n 203: \"Non-Authoritative Information\", // RFC 7231 6.3.4\n 204: \"No Content\", // RFC 7231 6.3.5\n 205: \"Reset Content\", // RFC 7231 6.3.6\n 206: \"Partial Content\", // RFC 7233 4.1\n 207: \"Multi-Status\", // RFC 4918 11.1\n 208: \"Already Reported\", // RFC 5842 7.1\n 226: \"IM Used\", // RFC 3229 10.4.1\n 300: \"Multiple Choices\", // RFC 7231 6.4.1\n 301: \"Moved Permanently\", // RFC 7231 6.4.2\n 302: \"Found\", // RFC 7231 6.4.3\n 303: \"See Other\", // RFC 7231 6.4.4\n 304: \"Not Modified\", // RFC 7232 4.1\n 305: \"Use Proxy\", // RFC 7231 6.4.5\n 307: \"Temporary Redirect\", // RFC 7231 6.4.7\n 308: \"Permanent Redirect\", // RFC 7238 3\n 400: \"Bad Request\", // RFC 7231 6.5.1\n 401: \"Unauthorized\", // RFC 7235 3.1\n 402: \"Payment Required\", // RFC 7231 6.5.2\n 403: \"Forbidden\", // RFC 7231 6.5.3\n 404: \"Not Found\", // RFC 7231 6.5.4\n 405: \"Method Not Allowed\", // RFC 7231 6.5.5\n 406: \"Not Acceptable\", // RFC 7231 6.5.6\n 407: \"Proxy Authentication Required\", // RFC 7235 3.2\n 408: \"Request Timeout\", // RFC 7231 6.5.7\n 409: \"Conflict\", // RFC 7231 6.5.8\n 410: \"Gone\", // RFC 7231 6.5.9\n 411: \"Length Required\", // RFC 7231 6.5.10\n 412: \"Precondition Failed\", // RFC 7232 4.2\n 413: \"Payload Too Large\", // RFC 7231 6.5.11\n 414: \"URI Too Long\", // RFC 7231 6.5.12\n 415: \"Unsupported Media Type\", // RFC 7231 6.5.13\n 416: \"Range Not Satisfiable\", // RFC 7233 4.4\n 417: \"Expectation Failed\", // RFC 7231 6.5.14\n 418: \"I'm a Teapot\", // RFC 7168 2.3.3\n 421: \"Misdirected Request\", // RFC 7540 9.1.2\n 422: \"Unprocessable Entity\", // RFC 4918 11.2\n 423: \"Locked\", // RFC 4918 11.3\n 424: \"Failed Dependency\", // RFC 4918 11.4\n 425: \"Too Early\", // RFC 8470 5.2\n 426: \"Upgrade Required\", // RFC 2817 and RFC 7231 6.5.15\n 428: \"Precondition Required\", // RFC 6585 3\n 429: \"Too Many Requests\", // RFC 6585 4\n 431: \"Request Header Fields Too Large\", // RFC 6585 5\n 451: \"Unavailable For Legal Reasons\", // RFC 7725 3\n 500: \"Internal Server Error\", // RFC 7231 6.6.1\n 501: \"Not Implemented\", // RFC 7231 6.6.2\n 502: \"Bad Gateway\", // RFC 7231 6.6.3\n 503: \"Service Unavailable\", // RFC 7231 6.6.4\n 504: \"Gateway Timeout\", // RFC 7231 6.6.5\n 505: \"HTTP Version Not Supported\", // RFC 7231 6.6.6\n 506: \"Variant Also Negotiates\", // RFC 2295 8.1\n 507: \"Insufficient Storage\", // RFC 4918 11.5\n 508: \"Loop Detected\", // RFC 5842 7.2\n 509: \"Bandwidth Limit Exceeded\",\n 510: \"Not Extended\", // RFC 2774 7\n 511: \"Network Authentication Required\", // RFC 6585 6\n};\n/**\n * This is an implementation of ServerResponse from Node.js intended to run in\n * a WinterTC runtime. The 'Writable' interface of this class is wired to an in-memory\n * buffer. This class also provides a method that creates a Response object that\n * can be handled by the runtime.\n *\n * This instance can be used in normal ways, but it does not give access to the\n * underlying socket (because there isn't one. req.socket will always return null).\n *\n * Some code in this class is transplanted/adapted from node/lib/_httpserver.js\n *\n * NOTE: Node.js doesn't really separate the body from headers, the entire \"stream\"\n * contains the headers and the body. So we provide functions that lets us pull\n * the headers and body out individually at a later time.\n */\nexport class FetchServerResponse extends FetchOutgoingMessage {\n static encoder = new TextEncoder();\n statusCode = 200;\n statusMessage;\n _sent100;\n _expect_continue;\n [kOutHeaders] = null;\n constructor(req, options) {\n super(req, options);\n if (req.method === \"HEAD\") {\n this._hasBody = false;\n }\n // this.req = req; // super() actually does this\n this.sendDate = true;\n this._sent100 = false;\n this._expect_continue = false;\n if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) {\n this.useChunkedEncodingByDefault =\n chunkExpression.exec(String(req.headers.te)) !== null;\n this.shouldKeepAlive = false;\n }\n // Difference from Node.js -\n // In Node.js, in addition to the above, we would check if an observer is enabled for\n // http, and if it is, we would start performance measurement of server response statistics.\n this.fetchResponse = new Promise((resolve) => {\n let finished = false;\n this.on(\"finish\", () => {\n finished = true;\n });\n const initialDataChunks = [];\n const initialDataWrittenHandler = (e) => {\n if (finished) {\n return;\n }\n initialDataChunks[e.index] = this.dataFromDataWrittenEvent(e);\n };\n this.on(\"_dataWritten\", initialDataWrittenHandler);\n this.on(\"_headersSent\", (e) => {\n this.off(\"_dataWritten\", initialDataWrittenHandler);\n // Convert the response object to a Response object and return it\n const { statusCode, statusMessage, headers } = e;\n resolve(this._toFetchResponse(statusCode, statusMessage, headers, initialDataChunks, finished));\n });\n });\n }\n dataFromDataWrittenEvent(e) {\n const { index, entry } = e;\n let { data, encoding } = entry;\n if (index === 0) {\n if (typeof data !== \"string\") {\n console.error(\"First chunk should be string, not sure what happened.\");\n throw new ERR_INVALID_ARG_TYPE(\"packet.data\", [\"string\", \"Buffer\", \"Uint8Array\"], data);\n }\n // The first X bytes are header material, so we remove it.\n data = data.slice(this.writtenHeaderBytes);\n }\n if (typeof data === \"string\") {\n if (encoding === undefined ||\n encoding === \"utf8\" ||\n encoding === \"utf-8\") {\n data = FetchServerResponse.encoder.encode(data);\n }\n else {\n data = Buffer.from(data, encoding ?? undefined);\n }\n }\n return data ?? Buffer.from([]);\n }\n _finish() {\n // Difference from Node.js -\n // In Node.js, if server response statistics performance is being measured, we would stop it.\n super._finish();\n }\n assignSocket(socket) {\n // Difference from Node.js -\n // Socket is not supported\n throw new ERR_METHOD_NOT_IMPLEMENTED(\"assignSocket\");\n }\n detachSocket(socket) {\n // Difference from Node.js -\n // Socket is not supported\n throw new ERR_METHOD_NOT_IMPLEMENTED(\"detachSocket\");\n }\n writeContinue(callback) {\n this._writeRaw(\"HTTP/1.1 100 Continue\\r\\n\\r\\n\", \"ascii\", callback);\n this._sent100 = true;\n }\n writeProcessing(callback) {\n this._writeRaw(\"HTTP/1.1 102 Processing\\r\\n\\r\\n\", \"ascii\", callback);\n }\n writeEarlyHints(hints, callback) {\n let head = \"HTTP/1.1 103 Early Hints\\r\\n\";\n // Difference from Node.js -\n // In Node.js, we would validate the hints object here.\n // validateObject(hints, 'hints');\n if (hints.link === null || hints.link === undefined) {\n return;\n }\n const link = validateLinkHeaderValue(hints.link);\n if (link.length === 0) {\n return;\n }\n head += \"Link: \" + link + \"\\r\\n\";\n for (const key of Object.keys(hints)) {\n if (key !== \"link\") {\n head += key + \": \" + hints[key] + \"\\r\\n\";\n }\n }\n head += \"\\r\\n\";\n this._writeRaw(head, \"ascii\", callback);\n }\n _implicitHeader() {\n this.writeHead(this.statusCode);\n }\n writeHead(statusCode, reason, obj) {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"write\");\n }\n const originalStatusCode = statusCode;\n statusCode |= 0;\n if (statusCode < 100 || statusCode > 999) {\n throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);\n }\n if (typeof reason === \"string\") {\n // writeHead(statusCode, reasonPhrase[, headers])\n this.statusMessage = reason;\n }\n else {\n // writeHead(statusCode[, headers])\n this.statusMessage ||= STATUS_CODES[statusCode] || \"unknown\";\n obj ??= reason;\n }\n this.statusCode = statusCode;\n let headers;\n if (this[kOutHeaders]) {\n // Slow-case: when progressive API and header fields are passed.\n let k;\n if (Array.isArray(obj)) {\n if (obj.length % 2 !== 0) {\n throw new ERR_INVALID_ARG_VALUE(\"headers\", obj);\n }\n // Headers in obj should override previous headers but still\n // allow explicit duplicates. To do so, we first remove any\n // existing conflicts, then use appendHeader.\n for (let n = 0; n < obj.length; n += 2) {\n k = obj[n + 0];\n this.removeHeader(String(k));\n }\n for (let n = 0; n < obj.length; n += 2) {\n k = obj[n];\n if (k) {\n this.appendHeader(String(k), obj[n + 1]);\n }\n }\n }\n else if (obj) {\n const keys = Object.keys(obj);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; i++) {\n k = keys[i];\n if (k) {\n this.setHeader(k, obj[k]);\n }\n }\n }\n // Only progressive api is used\n headers = this[kOutHeaders];\n }\n else {\n // Only writeHead() called\n headers = obj;\n }\n if (checkInvalidHeaderChar(this.statusMessage)) {\n throw new ERR_INVALID_CHAR(\"statusMessage\");\n }\n const statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}\\r\\n`;\n if (statusCode === 204 ||\n statusCode === 304 ||\n (statusCode >= 100 && statusCode <= 199)) {\n // RFC 2616, 10.2.5:\n // The 204 response MUST NOT include a message-body, and thus is always\n // terminated by the first empty line after the header fields.\n // RFC 2616, 10.3.5:\n // The 304 response MUST NOT contain a message-body, and thus is always\n // terminated by the first empty line after the header fields.\n // RFC 2616, 10.1 Informational 1xx:\n // This class of status code indicates a provisional response,\n // consisting only of the Status-Line and optional headers, and is\n // terminated by an empty line.\n this._hasBody = false;\n }\n // Don't keep alive connections where the client expects 100 Continue\n // but we sent a final status; they may put extra bytes on the wire.\n if (this._expect_continue && !this._sent100) {\n this.shouldKeepAlive = false;\n }\n // Convert headers to a compatible type for _storeHeader\n const convertedHeaders = headers && !Array.isArray(headers)\n ? headers\n : headers;\n this._storeHeader(statusLine, convertedHeaders ?? null);\n return this;\n }\n // Docs-only deprecated: DEP0063\n writeHeader = this.writeHead;\n fetchResponse;\n _toFetchResponse(status, statusText, sentHeaders, initialDataChunks, finished) {\n const headers = new Headers();\n for (const [header, value] of sentHeaders) {\n headers.append(header, value);\n }\n const _this = this;\n let body = this._hasBody\n ? new ReadableStream({\n start(controller) {\n for (const dataChunk of initialDataChunks) {\n controller.enqueue(dataChunk);\n }\n if (finished) {\n controller.close();\n }\n else {\n _this.on(\"finish\", () => {\n finished = true;\n controller.close();\n });\n _this.on(\"_dataWritten\", (e) => {\n if (finished) {\n return;\n }\n const data = _this.dataFromDataWrittenEvent(e);\n controller.enqueue(data);\n });\n }\n },\n })\n : null;\n // @ts-expect-error this is (currently) a cloudflare-specific class\n if (body != null && typeof FixedLengthStream !== \"undefined\") {\n const contentLength = parseInt(headers.get(\"content-length\") ?? \"\", 10); // will be NaN if not set\n if (contentLength >= 0) {\n // @ts-expect-error this is (currently) a cloudflare-specific class\n body = body.pipeThrough(new FixedLengthStream(contentLength));\n }\n }\n return new Response(body, {\n status,\n statusText,\n headers,\n });\n }\n}\nexport function toReqRes(req, options) {\n const { createIncomingMessage = () => new FetchIncomingMessage(), createServerResponse = (incoming) => new FetchServerResponse(incoming), ctx, } = options ?? {};\n const incoming = createIncomingMessage(ctx);\n const serverResponse = createServerResponse(incoming, ctx);\n const reqUrl = new URL(req.url);\n const versionMajor = 1;\n const versionMinor = 1;\n incoming.httpVersionMajor = versionMajor;\n incoming.httpVersionMinor = versionMinor;\n incoming.httpVersion = `${versionMajor}.${versionMinor}`;\n incoming.url = reqUrl.pathname + reqUrl.search;\n incoming.upgrade = false;\n const headers = [];\n for (const [headerName, headerValue] of req.headers) {\n headers.push(headerName);\n headers.push(headerValue);\n }\n incoming._addHeaderLines(headers, headers.length);\n incoming.method = req.method;\n incoming._stream = req.body;\n return {\n req: incoming,\n res: serverResponse,\n };\n}\nexport function toFetchResponse(res) {\n if (!(res instanceof FetchServerResponse)) {\n throw new Error(\"toFetchResponse must be called on a ServerResponse generated by toReqRes\");\n }\n return res.fetchResponse;\n}\n","import { MASTRA_FRAMEWORK_PUBLIC_KEY, MASTRA_FRAMEWORK_PUBLIC_KEY as MASTRA_FRAMEWORK_PUBLIC_KEY$1, MastraServer as MastraServer$1, checkRouteFGA, isZodError, normalizeQueryParams, redactStreamChunk, serializeStreamChunk } from \"@mastra/server/server-adapter\";\nimport { toFetchResponse, toReqRes } from \"fetch-to-node\";\nimport { bodyLimit } from \"hono/body-limit\";\nimport { stream } from \"hono/streaming\";\nimport { RequestContext } from \"@mastra/core/request-context\";\nimport { coreAuthMiddleware } from \"@mastra/server/auth\";\nimport { ViewerRegistry, handleInputMessage } from \"@mastra/server/browser-stream\";\n//#region src/auth-middleware.ts\nfunction createAuthMiddleware({ mastra, requiresAuth = true }) {\n\treturn async (c, next) => {\n\t\tif (!requiresAuth) return next();\n\t\tconst authConfig = mastra.getServer()?.auth;\n\t\tif (!authConfig) return next();\n\t\tconst requestContext = c.get(\"requestContext\") ?? new RequestContext();\n\t\tc.set(\"requestContext\", requestContext);\n\t\tc.set(\"mastra\", c.get(\"mastra\") ?? mastra);\n\t\tconst path = c.req.path;\n\t\tconst method = c.req.method;\n\t\tconst customRouteAuthConfig = new Map(c.get(\"customRouteAuthConfig\") ?? []);\n\t\tcustomRouteAuthConfig.set(`${method}:${path}`, true);\n\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\tlet token = authHeader ? authHeader.replace(\"Bearer \", \"\") : null;\n\t\tif (!token) token = c.req.query(\"apiKey\") || null;\n\t\tconst result = await coreAuthMiddleware({\n\t\t\tpath,\n\t\t\tmethod,\n\t\t\tgetHeader: (name) => c.req.header(name),\n\t\t\tmastra,\n\t\t\tauthConfig,\n\t\t\tcustomRouteAuthConfig,\n\t\t\trequestContext,\n\t\t\trawRequest: c.req.raw,\n\t\t\ttoken,\n\t\t\tbuildAuthorizeContext: () => c\n\t\t});\n\t\tif (result.action === \"next\") return next();\n\t\treturn c.json(result.body, result.status);\n\t};\n}\n//#endregion\n//#region src/browser-stream/index.ts\n/**\n* Set up WebSocket-based browser stream endpoint for real-time screencast viewing.\n*\n* Creates a WebSocket route at `/browser/:agentId/stream` that:\n* - Accepts viewer connections\n* - Starts screencast when first viewer connects\n* - Broadcasts frames to all connected viewers\n* - Stops screencast when last viewer disconnects\n*\n* **Note**: Requires `ws` package to be installed. If not available, returns null\n* and logs a warning. Browser streaming will be disabled but everything else works.\n*\n* @param app - The Hono application instance\n* @param config - Configuration for browser stream\n* @returns Object containing injectWebSocket function and registry instance, or null if ws is not available\n*\n* @example\n* ```typescript\n* import { Hono } from 'hono';\n* import { serve } from '@hono/node-server';\n* import { setupBrowserStream } from '@mastra/hono';\n*\n* const app = new Hono();\n* const browserStream = await setupBrowserStream(app, {\n* getToolset: (agentId) => browserToolsets.get(agentId),\n* });\n*\n* const server = serve({ fetch: app.fetch, port: 4111 });\n* browserStream?.injectWebSocket(server);\n* ```\n*/\nasync function setupBrowserStream(app, config) {\n\tlet createNodeWebSocket;\n\ttry {\n\t\tcreateNodeWebSocket = (await import(\n\t\t\t/* @vite-ignore */\n\t\t\t/* webpackIgnore: true */\n\t\t\t\"@hono/node-ws\"\n)).createNodeWebSocket;\n\t} catch {\n\t\treturn null;\n\t}\n\tconst { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });\n\tconst registry = new ViewerRegistry();\n\tconst rawPrefix = config.apiPrefix ?? \"/api\";\n\tconst apiPrefix = (rawPrefix.endsWith(\"/\") ? rawPrefix.slice(0, -1) : rawPrefix) || \"/api\";\n\tapp.get(\"/browser/:agentId/stream\", upgradeWebSocket((c) => {\n\t\tconst agentId = c.req.param(\"agentId\");\n\t\tconst threadId = c.req.query(\"threadId\");\n\t\tconst viewerKey = threadId ? `${agentId}:${threadId}` : agentId;\n\t\treturn {\n\t\t\tonOpen(_event, ws) {\n\t\t\t\tws.send(JSON.stringify({ status: \"connected\" }));\n\t\t\t\tregistry.addViewer(viewerKey, ws, config.getToolset, agentId, threadId);\n\t\t\t},\n\t\t\tonMessage(event, _ws) {\n\t\t\t\tconst data = typeof event.data === \"string\" ? event.data : null;\n\t\t\t\tif (data) handleInputMessage(data, config.getToolset, agentId, threadId);\n\t\t\t},\n\t\t\tonClose(_event, ws) {\n\t\t\t\tregistry.removeViewer(viewerKey, ws);\n\t\t\t},\n\t\t\tonError(event, ws) {\n\t\t\t\tconsole.error(\"[BrowserStream] WebSocket error:\", event);\n\t\t\t\tregistry.removeViewer(viewerKey, ws);\n\t\t\t}\n\t\t};\n\t}));\n\tapp.get(`${apiPrefix}/agents/:agentId/browser/session`, async (c) => {\n\t\tconst agentId = c.req.param(\"agentId\");\n\t\tif (!agentId) return c.json({ error: \"Agent ID is required\" }, 400);\n\t\tconst threadId = c.req.query(\"threadId\");\n\t\tconst toolset = await config.getToolset(agentId);\n\t\tif (!toolset) return c.json({\n\t\t\thasSession: false,\n\t\t\tscreencastAvailable: true\n\t\t});\n\t\tconst hasSession = threadId ? toolset.hasThreadSession(threadId) : false;\n\t\treturn c.json({\n\t\t\thasSession,\n\t\t\tscreencastAvailable: true\n\t\t});\n\t});\n\tapp.post(`${apiPrefix}/agents/:agentId/browser/close`, async (c) => {\n\t\tconst agentId = c.req.param(\"agentId\");\n\t\tif (!agentId) return c.json({ error: \"Agent ID is required\" }, 400);\n\t\tconst toolset = await config.getToolset(agentId);\n\t\tif (!toolset) return c.json({ error: \"No browser session for this agent\" }, 404);\n\t\ttry {\n\t\t\tlet threadId;\n\t\t\ttry {\n\t\t\t\tthreadId = (await c.req.json())?.threadId;\n\t\t\t} catch {}\n\t\t\tconst scope = toolset.getScope();\n\t\t\tconst viewerKey = threadId ? `${agentId}:${threadId}` : agentId;\n\t\t\tif (scope === \"thread\" && threadId) {\n\t\t\t\tawait registry.closeBrowserSession(viewerKey);\n\t\t\t\tif (\"closeThreadSession\" in toolset && typeof toolset.closeThreadSession === \"function\") await toolset.closeThreadSession(threadId);\n\t\t\t} else {\n\t\t\t\tawait registry.closeBrowserSession(viewerKey);\n\t\t\t\tawait toolset.close();\n\t\t\t}\n\t\t\treturn c.json({ success: true });\n\t\t} catch (error) {\n\t\t\tconsole.error(`[BrowserStream] Error closing browser for ${agentId}:`, error);\n\t\t\treturn c.json({ error: \"Failed to close browser\" }, 500);\n\t\t}\n\t});\n\treturn {\n\t\tinjectWebSocket,\n\t\tregistry\n\t};\n}\n//#endregion\n//#region src/index.ts\nlet _hasPermissionPromise;\nfunction loadHasPermission() {\n\tif (!_hasPermissionPromise) _hasPermissionPromise = import(\"@mastra/core/auth/ee\").then((m) => m.hasPermission).catch(() => {\n\t\tconsole.error(\"[@mastra/hono] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest\");\n\t});\n\treturn _hasPermissionPromise;\n}\n/**\n* Wrap a Hono middleware handler so it becomes a no-op for framework-public\n* routes (routes registered with `requiresAuth: false`).\n*\n* Adapters that expose user-provided middleware — for example `serverMiddleware`\n* on the Mastra instance or `server.middleware` in Mastra config — MUST wrap\n* those handlers with this before registering them. This is the framework's\n* guarantee that user middleware cannot accidentally (or intentionally) 401\n* routes the framework needs to keep reachable (e.g. Studio sign-in endpoints).\n*\n* The framework-public flag is computed once per request by\n* {@link MastraServer.registerContextMiddleware} and stashed on the Hono\n* context under `MASTRA_FRAMEWORK_PUBLIC_KEY`.\n*/\nconst skipIfFrameworkPublic = (handler) => {\n\treturn async (c, next) => {\n\t\tif (c.get(MASTRA_FRAMEWORK_PUBLIC_KEY$1)) return next();\n\t\treturn handler(c, next);\n\t};\n};\nvar MastraServer = class extends MastraServer$1 {\n\tcreateContextMiddleware() {\n\t\treturn async (c, next) => {\n\t\t\tconst originalJson = c.req.json.bind(c.req);\n\t\t\tlet jsonPromise;\n\t\t\tc.req.json = () => {\n\t\t\t\tif (!jsonPromise) jsonPromise = originalJson().then((body) => {\n\t\t\t\t\tc.set(\"cachedBody\", body);\n\t\t\t\t\treturn body;\n\t\t\t\t});\n\t\t\t\treturn jsonPromise;\n\t\t\t};\n\t\t\tlet bodyRequestContext;\n\t\t\tlet paramsRequestContext;\n\t\t\tif (c.req.method === \"POST\" || c.req.method === \"PUT\") {\n\t\t\t\tconst contentType = c.req.header(\"content-type\");\n\t\t\t\tconst contentLength = c.req.header(\"content-length\");\n\t\t\t\tif (contentType?.includes(\"application/json\") && contentLength !== \"0\") try {\n\t\t\t\t\tconst body = await c.req.raw.clone().json();\n\t\t\t\t\tif (body.requestContext) bodyRequestContext = body.requestContext;\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tif (c.req.method === \"GET\") try {\n\t\t\t\tconst encodedRequestContext = c.req.query(\"requestContext\");\n\t\t\t\tif (encodedRequestContext) try {\n\t\t\t\t\tparamsRequestContext = JSON.parse(encodedRequestContext);\n\t\t\t\t} catch {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst json = Buffer.from(encodedRequestContext, \"base64\").toString(\"utf-8\");\n\t\t\t\t\t\tparamsRequestContext = JSON.parse(json);\n\t\t\t\t\t} catch {}\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t\tconst requestContext = this.mergeRequestContext({\n\t\t\t\tparamsRequestContext,\n\t\t\t\tbodyRequestContext\n\t\t\t});\n\t\t\tthis.applyRequestMetadataToContext({\n\t\t\t\trequestContext,\n\t\t\t\tgetHeader: (name) => c.req.header(name)\n\t\t\t});\n\t\t\tc.set(\"requestContext\", requestContext);\n\t\t\tc.set(\"mastra\", this.mastra);\n\t\t\tc.set(\"registeredTools\", this.tools || {});\n\t\t\tc.set(\"taskStore\", this.taskStore);\n\t\t\tc.set(\"abortSignal\", c.req.raw.signal);\n\t\t\tc.set(\"customRouteAuthConfig\", this.customRouteAuthConfig);\n\t\t\treturn next();\n\t\t};\n\t}\n\tasync stream(route, res, result) {\n\t\tconst streamFormat = route.streamFormat || \"stream\";\n\t\tif (streamFormat === \"sse\") {\n\t\t\tres.header(\"Content-Type\", \"text/event-stream\");\n\t\t\tres.header(\"Cache-Control\", \"no-cache\");\n\t\t\tres.header(\"Connection\", \"keep-alive\");\n\t\t\tres.header(\"X-Accel-Buffering\", \"no\");\n\t\t} else res.header(\"Content-Type\", \"text/plain\");\n\t\tres.header(\"Transfer-Encoding\", \"chunked\");\n\t\treturn stream(res, async (stream) => {\n\t\t\tif (streamFormat === \"sse\" && route.sseFlushOnConnect) await stream.write(\": connected\\n\\n\");\n\t\t\tconst reader = (result instanceof ReadableStream ? result : result.fullStream).getReader();\n\t\t\tstream.onAbort(() => {\n\t\t\t\treader.cancel(\"request aborted\").catch(() => {});\n\t\t\t});\n\t\t\ttry {\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\tif (streamFormat === \"sse\" && typeof value === \"string\" && value.startsWith(\":\")) {\n\t\t\t\t\t\t\tawait stream.write(value);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst outputValue = this.streamOptions?.redact ?? true ? redactStreamChunk(value) : value;\n\t\t\t\t\t\tconst serialized = serializeStreamChunk(outputValue);\n\t\t\t\t\t\tif (!serialized.ok) {\n\t\t\t\t\t\t\tthis.mastra.getLogger()?.error(\"Failed to serialize stream chunk, skipping\", {\n\t\t\t\t\t\t\t\tpath: route.path,\n\t\t\t\t\t\t\t\tchunkType: outputValue?.type,\n\t\t\t\t\t\t\t\terror: serialized.error.message\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (streamFormat === \"sse\") await stream.write(`data: ${serialized.json}\\n\\n`);\n\t\t\t\t\t\telse await stream.write(serialized.json + \"\u001e\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (streamFormat === \"sse\") await stream.write(\"data: [DONE]\\n\\n\");\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Error in stream processing\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t} finally {\n\t\t\t\tawait stream.close();\n\t\t\t}\n\t\t}, async (err) => {\n\t\t\tthis.mastra.getLogger()?.error(\"Stream error callback\", { error: err instanceof Error ? {\n\t\t\t\tmessage: err.message,\n\t\t\t\tstack: err.stack\n\t\t\t} : err });\n\t\t});\n\t}\n\tasync getParams(route, request) {\n\t\tconst urlParams = request.param();\n\t\tconst queryParams = normalizeQueryParams(request.queries());\n\t\tlet body;\n\t\tlet bodyParseError;\n\t\tif (route.method === \"POST\" || route.method === \"PUT\" || route.method === \"PATCH\" || route.method === \"DELETE\") {\n\t\t\tconst contentType = request.header(\"content-type\") || \"\";\n\t\t\tif (contentType.includes(\"multipart/form-data\")) try {\n\t\t\t\tconst formData = await request.formData();\n\t\t\t\tbody = await this.parseFormData(formData);\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Failed to parse multipart form data\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t\tif (error instanceof Error && error.message.toLowerCase().includes(\"size\")) throw error;\n\t\t\t\tbodyParseError = { message: error instanceof Error ? error.message : \"Failed to parse multipart form data\" };\n\t\t\t}\n\t\t\telse if (contentType.includes(\"application/json\")) {\n\t\t\t\tconst bodyText = await request.raw.clone().text();\n\t\t\t\tif (bodyText && bodyText.trim().length > 0) try {\n\t\t\t\t\tbody = JSON.parse(bodyText);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.mastra.getLogger()?.error(\"Failed to parse JSON body\", { error: error instanceof Error ? {\n\t\t\t\t\t\tmessage: error.message,\n\t\t\t\t\t\tstack: error.stack\n\t\t\t\t\t} : error });\n\t\t\t\t\tbodyParseError = { message: error instanceof Error ? error.message : \"Invalid JSON in request body\" };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\turlParams,\n\t\t\tqueryParams,\n\t\t\tbody,\n\t\t\tbodyParseError\n\t\t};\n\t}\n\t/**\n\t* Parse FormData into a plain object, converting File objects to Buffers.\n\t*/\n\tasync parseFormData(formData) {\n\t\tconst result = {};\n\t\tfor (const [key, value] of formData.entries()) if (value instanceof File) {\n\t\t\tconst arrayBuffer = await value.arrayBuffer();\n\t\t\tresult[key] = Buffer.from(arrayBuffer);\n\t\t} else if (typeof value === \"string\") try {\n\t\t\tresult[key] = JSON.parse(value);\n\t\t} catch {\n\t\t\tresult[key] = value;\n\t\t}\n\t\telse result[key] = value;\n\t\treturn result;\n\t}\n\tasync sendResponse(route, response, result, prefix) {\n\t\tconst resolvedPrefix = prefix ?? this.prefix ?? \"\";\n\t\tif (result && typeof result === \"object\" && \"__refreshHeaders\" in result) {\n\t\t\tconst refreshHeaders = result.__refreshHeaders;\n\t\t\tfor (const [key, value] of Object.entries(refreshHeaders)) response.header(key, value);\n\t\t\tdelete result.__refreshHeaders;\n\t\t}\n\t\tif (route.responseType === \"json\") return response.json(result, 200);\n\t\telse if (route.responseType === \"stream\") return this.stream(route, response, result);\n\t\telse if (route.responseType === \"datastream-response\") return result;\n\t\telse if (route.responseType === \"mcp-http\") {\n\t\t\tconst { server, httpPath, mcpOptions: routeMcpOptions } = result;\n\t\t\tconst { req, res } = toReqRes(response.req.raw);\n\t\t\tconst options = {\n\t\t\t\t...this.mcpOptions,\n\t\t\t\t...routeMcpOptions\n\t\t\t};\n\t\t\tserver.startHTTP({\n\t\t\t\turl: new URL(response.req.url),\n\t\t\t\thttpPath: `${resolvedPrefix}${httpPath}`,\n\t\t\t\treq,\n\t\t\t\tres,\n\t\t\t\toptions: Object.keys(options).length > 0 ? options : void 0\n\t\t\t}).catch((e) => {\n\t\t\t\tthis.mastra.getLogger()?.error(\"[MCP HTTP] Error in background startHTTP:\", { error: e instanceof Error ? {\n\t\t\t\t\tmessage: e.message,\n\t\t\t\t\tstack: e.stack\n\t\t\t\t} : e });\n\t\t\t\ttry {\n\t\t\t\t\tif (!res.headersSent) {\n\t\t\t\t\t\tres.writeHead(500, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\tres.end(JSON.stringify({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: -32603,\n\t\t\t\t\t\t\t\tmessage: \"Internal server error\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tid: null\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\t\t\t\t} catch {}\n\t\t\t});\n\t\t\treturn await toFetchResponse(res);\n\t\t} else if (route.responseType === \"mcp-sse\") {\n\t\t\tconst { server, ssePath, messagePath } = result;\n\t\t\ttry {\n\t\t\t\treturn await server.startHonoSSE({\n\t\t\t\t\turl: new URL(response.req.url),\n\t\t\t\t\tssePath: `${resolvedPrefix}${ssePath}`,\n\t\t\t\t\tmessagePath: `${resolvedPrefix}${messagePath}`,\n\t\t\t\t\tcontext: response\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\treturn response.json({ error: \"Error handling MCP SSE request\" }, 500);\n\t\t\t}\n\t\t} else return response.status(500);\n\t}\n\tasync registerRoute(app, route, { prefix: prefixParam } = {}) {\n\t\tconst prefix = prefixParam ?? this.prefix ?? \"\";\n\t\tconst shouldApplyBodyLimit = this.bodyLimitOptions && [\n\t\t\t\"POST\",\n\t\t\t\"PUT\",\n\t\t\t\"PATCH\",\n\t\t\t\"DELETE\"\n\t\t].includes(route.method.toUpperCase());\n\t\tconst maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n\t\tconst middlewares = [];\n\t\tif (shouldApplyBodyLimit && maxSize && this.bodyLimitOptions) {\n\t\t\tconst { onError } = this.bodyLimitOptions;\n\t\t\tmiddlewares.push(bodyLimit({\n\t\t\t\tmaxSize,\n\t\t\t\tonError: (c) => c.json(onError({ error: \"Request body too large\" }), 413)\n\t\t\t}));\n\t\t}\n\t\tapp[route.method.toLowerCase()](`${prefix}${route.path}`, ...middlewares, async (c) => {\n\t\t\tconst authResult = await this.checkRouteAuth(route, {\n\t\t\t\tpath: c.req.path,\n\t\t\t\tmethod: c.req.method,\n\t\t\t\tgetHeader: (name) => c.req.header(name),\n\t\t\t\tgetQuery: (name) => c.req.query(name),\n\t\t\t\trequestContext: c.get(\"requestContext\"),\n\t\t\t\trequest: c.req.raw,\n\t\t\t\tbuildAuthorizeContext: () => c\n\t\t\t});\n\t\t\tif (authResult) {\n\t\t\t\tif (authResult.headers) for (const [key, value] of Object.entries(authResult.headers)) c.header(key, value);\n\t\t\t\tif (authResult.error) return c.json({ error: authResult.error }, authResult.status);\n\t\t\t}\n\t\t\tconst params = await this.getParams(route, c.req);\n\t\t\tif (params.bodyParseError) return c.json({\n\t\t\t\terror: \"Invalid request body\",\n\t\t\t\tissues: [{\n\t\t\t\t\tfield: \"body\",\n\t\t\t\t\tmessage: params.bodyParseError.message\n\t\t\t\t}]\n\t\t\t}, 400);\n\t\t\tif (params.queryParams) try {\n\t\t\t\tparams.queryParams = await this.parseQueryParams(route, params.queryParams);\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Error parsing query params\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t\tif (isZodError(error)) {\n\t\t\t\t\tconst { status, body } = this.resolveValidationError(route, error, \"query\");\n\t\t\t\t\treturn c.json(body, status);\n\t\t\t\t}\n\t\t\t\treturn c.json({\n\t\t\t\t\terror: \"Invalid query parameters\",\n\t\t\t\t\tissues: [{\n\t\t\t\t\t\tfield: \"unknown\",\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t\t}]\n\t\t\t\t}, 400);\n\t\t\t}\n\t\t\tif (params.body) try {\n\t\t\t\tparams.body = await this.parseBody(route, params.body);\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Error parsing body\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t\tif (isZodError(error)) {\n\t\t\t\t\tconst { status, body } = this.resolveValidationError(route, error, \"body\");\n\t\t\t\t\treturn c.json(body, status);\n\t\t\t\t}\n\t\t\t\treturn c.json({\n\t\t\t\t\terror: \"Invalid request body\",\n\t\t\t\t\tissues: [{\n\t\t\t\t\t\tfield: \"unknown\",\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t\t}]\n\t\t\t\t}, 400);\n\t\t\t}\n\t\t\tif (params.urlParams) try {\n\t\t\t\tparams.urlParams = await this.parsePathParams(route, params.urlParams);\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Error parsing path params\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t\tif (isZodError(error)) {\n\t\t\t\t\tconst { status, body } = this.resolveValidationError(route, error, \"path\");\n\t\t\t\t\treturn c.json(body, status);\n\t\t\t\t}\n\t\t\t\treturn c.json({\n\t\t\t\t\terror: \"Invalid path parameters\",\n\t\t\t\t\tissues: [{\n\t\t\t\t\t\tfield: \"unknown\",\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t\t}]\n\t\t\t\t}, 400);\n\t\t\t}\n\t\t\tconst handlerParams = {\n\t\t\t\t...params.urlParams,\n\t\t\t\t...params.queryParams,\n\t\t\t\t...typeof params.body === \"object\" ? params.body : {},\n\t\t\t\trequestContext: c.get(\"requestContext\"),\n\t\t\t\tmastra: this.mastra,\n\t\t\t\tregisteredTools: c.get(\"registeredTools\"),\n\t\t\t\ttaskStore: c.get(\"taskStore\"),\n\t\t\t\tabortSignal: c.get(\"abortSignal\"),\n\t\t\t\troutePrefix: prefix,\n\t\t\t\trequest: c.req.raw\n\t\t\t};\n\t\t\tconst requestContext = c.get(\"requestContext\");\n\t\t\tif (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {\n\t\t\t\tconst hasPermission = await loadHasPermission();\n\t\t\t\tif (hasPermission) {\n\t\t\t\t\tconst userPermissions = requestContext.get(\"mastra__userPermissions\");\n\t\t\t\t\tconst permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, requestContext);\n\t\t\t\t\tif (permissionError) return c.json({\n\t\t\t\t\t\terror: permissionError.error,\n\t\t\t\t\t\tmessage: permissionError.message\n\t\t\t\t\t}, permissionError.status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst fgaError = await checkRouteFGA(this.mastra, route, c.get(\"requestContext\"), {\n\t\t\t\t...params.urlParams,\n\t\t\t\t...params.queryParams,\n\t\t\t\t...typeof params.body === \"object\" ? params.body : {}\n\t\t\t});\n\t\t\tif (fgaError) return c.json({\n\t\t\t\terror: fgaError.error,\n\t\t\t\tmessage: fgaError.message\n\t\t\t}, fgaError.status);\n\t\t\ttry {\n\t\t\t\tconst result = await route.handler(handlerParams);\n\t\t\t\treturn this.sendResponse(route, c, result, prefix);\n\t\t\t} catch (error) {\n\t\t\t\tconst httpStatus = error && typeof error === \"object\" && \"status\" in error ? error.status : void 0;\n\t\t\t\tif (!(typeof httpStatus === \"number\" && httpStatus >= 400 && httpStatus < 500)) this.mastra.getLogger()?.error(\"Error calling handler\", {\n\t\t\t\t\terror: error instanceof Error ? {\n\t\t\t\t\t\tmessage: error.message,\n\t\t\t\t\t\tstack: error.stack\n\t\t\t\t\t} : error,\n\t\t\t\t\tpath: route.path,\n\t\t\t\t\tmethod: route.method\n\t\t\t\t});\n\t\t\t\tif (error && typeof error === \"object\") {\n\t\t\t\t\tif (\"status\" in error) {\n\t\t\t\t\t\tconst status = error.status;\n\t\t\t\t\t\tlet safeCause;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst raw = error instanceof Error ? error.cause : void 0;\n\t\t\t\t\t\t\tif (raw && typeof raw === \"object\" && !Array.isArray(raw) && \"failingItems\" in raw && Array.isArray(raw.failingItems)) safeCause = { failingItems: raw.failingItems };\n\t\t\t\t\t\t} catch {}\n\t\t\t\t\t\treturn c.json({\n\t\t\t\t\t\t\terror: error instanceof Error ? error.message : \"Unknown error\",\n\t\t\t\t\t\t\t...safeCause ? { cause: safeCause } : {}\n\t\t\t\t\t\t}, status);\n\t\t\t\t\t}\n\t\t\t\t\tif (\"details\" in error && error.details && typeof error.details === \"object\" && \"status\" in error.details) {\n\t\t\t\t\t\tconst status = error.details.status;\n\t\t\t\t\t\treturn c.json({ error: error instanceof Error ? error.message : \"Unknown error\" }, status);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: error instanceof Error ? error.message : \"Unknown error\" }, 500);\n\t\t\t}\n\t\t});\n\t}\n\tasync registerCustomApiRoutes() {\n\t\tif (!await this.buildCustomRouteHandler()) return;\n\t\tconst routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [];\n\t\tfor (const route of routes) {\n\t\t\tconst serverRoute = {\n\t\t\t\tmethod: route.method,\n\t\t\t\tpath: route.path,\n\t\t\t\tresponseType: \"json\",\n\t\t\t\thandler: async () => {},\n\t\t\t\trequiresAuth: route.requiresAuth,\n\t\t\t\trequiresPermission: route.requiresPermission,\n\t\t\t\tfga: route.fga\n\t\t\t};\n\t\t\tconst routeHandler = async (c) => {\n\t\t\t\tconst authError = await this.checkRouteAuth(serverRoute, {\n\t\t\t\t\tpath: c.req.path,\n\t\t\t\t\tmethod: c.req.method,\n\t\t\t\t\tgetHeader: (name) => c.req.header(name),\n\t\t\t\t\tgetQuery: (name) => c.req.query(name),\n\t\t\t\t\trequestContext: c.get(\"requestContext\"),\n\t\t\t\t\trequest: c.req.raw,\n\t\t\t\t\tbuildAuthorizeContext: () => c\n\t\t\t\t});\n\t\t\t\tif (authError) {\n\t\t\t\t\tif (authError.headers) for (const [key, value] of Object.entries(authError.headers)) c.header(key, value);\n\t\t\t\t\tif (authError.error) return c.json({ error: authError.error }, authError.status);\n\t\t\t\t}\n\t\t\t\tconst requestContext = c.get(\"requestContext\");\n\t\t\t\tif (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {\n\t\t\t\t\tconst hasPermission = await loadHasPermission();\n\t\t\t\t\tif (hasPermission) {\n\t\t\t\t\t\tconst userPermissions = requestContext.get(\"mastra__userPermissions\");\n\t\t\t\t\t\tconst permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission, requestContext);\n\t\t\t\t\t\tif (permissionError) return c.json({\n\t\t\t\t\t\t\terror: permissionError.error,\n\t\t\t\t\t\t\tmessage: permissionError.message\n\t\t\t\t\t\t}, permissionError.status);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlet bodyParams = {};\n\t\t\t\tconst contentType = c.req.header(\"content-type\");\n\t\t\t\tif (contentType?.includes(\"application/json\")) try {\n\t\t\t\t\tconst body = await c.req.raw.clone().json();\n\t\t\t\t\tif (body && typeof body === \"object\" && !Array.isArray(body)) bodyParams = body;\n\t\t\t\t} catch {\n\t\t\t\t\tbodyParams = {};\n\t\t\t\t}\n\t\t\t\telse if (contentType?.includes(\"application/x-www-form-urlencoded\") || contentType?.includes(\"multipart/form-data\")) try {\n\t\t\t\t\tbodyParams = Object.fromEntries(await c.req.raw.clone().formData());\n\t\t\t\t} catch {\n\t\t\t\t\tbodyParams = {};\n\t\t\t\t}\n\t\t\t\tconst fgaError = await checkRouteFGA(this.mastra, serverRoute, c.get(\"requestContext\"), {\n\t\t\t\t\t...c.req.param(),\n\t\t\t\t\t...Object.fromEntries(new URL(c.req.url).searchParams.entries()),\n\t\t\t\t\t...bodyParams\n\t\t\t\t});\n\t\t\t\tif (fgaError) return c.json({\n\t\t\t\t\terror: fgaError.error,\n\t\t\t\t\tmessage: fgaError.message\n\t\t\t\t}, fgaError.status);\n\t\t\t\tconst reqHeaders = {};\n\t\t\t\tc.req.raw.headers.forEach((v, k) => {\n\t\t\t\t\treqHeaders[k] = v;\n\t\t\t\t});\n\t\t\t\tlet executionCtx;\n\t\t\t\ttry {\n\t\t\t\t\texecutionCtx = c.executionCtx;\n\t\t\t\t} catch {\n\t\t\t\t\texecutionCtx = void 0;\n\t\t\t\t}\n\t\t\t\tconst response = await this.handleCustomRouteRequest(c.req.url, c.req.method, reqHeaders, c.req.raw.body, c.get(\"requestContext\"), c.req.raw.signal, executionCtx);\n\t\t\t\tif (!response) return c.json({ error: \"Not Found\" }, 404);\n\t\t\t\treturn response;\n\t\t\t};\n\t\t\tconst method = route.method.toLowerCase();\n\t\t\tthis.app[method](route.path, routeHandler);\n\t\t}\n\t}\n\tregisterContextMiddleware() {\n\t\tconst isFrameworkPublic = this.getFrameworkPublicMatcher();\n\t\tthis.app.use(\"*\", this.createContextMiddleware());\n\t\tthis.app.use(\"*\", async (c, next) => {\n\t\t\tc.set(MASTRA_FRAMEWORK_PUBLIC_KEY$1, isFrameworkPublic(c.req.path, c.req.method));\n\t\t\treturn next();\n\t\t});\n\t\tthis.app.use(\"*\", async (c, next) => {\n\t\t\tawait next();\n\t\t\tthis.warnIfUnregisteredChannelWebhook(c.req.path, c.req.method, c.res.status);\n\t\t});\n\t}\n\tregisterAuthMiddleware() {}\n\tregisterHttpLoggingMiddleware() {\n\t\tif (!this.httpLoggingConfig?.enabled) return;\n\t\tthis.app.use(\"*\", async (c, next) => {\n\t\t\tif (!this.shouldLogRequest(c.req.path)) return next();\n\t\t\tconst start = Date.now();\n\t\t\tconst method = c.req.method;\n\t\t\tconst path = c.req.path;\n\t\t\tawait next();\n\t\t\tconst duration = Date.now() - start;\n\t\t\tconst status = c.res.status;\n\t\t\tconst level = this.httpLoggingConfig?.level || \"info\";\n\t\t\tconst logData = {\n\t\t\t\tmethod,\n\t\t\t\tpath,\n\t\t\t\tstatus,\n\t\t\t\tduration: `${duration}ms`\n\t\t\t};\n\t\t\tif (this.httpLoggingConfig?.includeQueryParams) logData.query = c.req.query();\n\t\t\tif (this.httpLoggingConfig?.includeHeaders) {\n\t\t\t\tconst headers = Object.fromEntries(c.req.raw.headers.entries());\n\t\t\t\t(this.httpLoggingConfig.redactHeaders || []).forEach((h) => {\n\t\t\t\t\tconst key = h.toLowerCase();\n\t\t\t\t\tif (headers[key] !== void 0) headers[key] = \"[REDACTED]\";\n\t\t\t\t});\n\t\t\t\tlogData.headers = headers;\n\t\t\t}\n\t\t\tthis.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n\t\t});\n\t}\n};\n//#endregion\nexport { MASTRA_FRAMEWORK_PUBLIC_KEY, MastraServer, createAuthMiddleware, setupBrowserStream, skipIfFrameworkPublic };\n\n//# sourceMappingURL=index.js.map","import { findTargetHandler } from 'hono/utils/handler';\nimport { sValidator } from '@hono/standard-validator';\nimport { loadVendor as loadVendor$1, toJsonSchema } from '@standard-community/standard-json';\nimport { loadVendor as loadVendor$2, toOpenAPISchema } from '@standard-community/standard-openapi';\n\nconst uniqueSymbol = Symbol(\"openapi\");\nconst ALLOWED_METHODS = [\n \"GET\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"OPTIONS\",\n \"HEAD\",\n \"PATCH\",\n \"TRACE\"\n];\nconst toOpenAPIPathSegment = (segment) => {\n let tmp = segment;\n if (tmp.startsWith(\":\")) {\n const match = tmp.match(/^:([^{?]+)(?:{(.+)})?(\\?)?$/);\n if (match) {\n const paramName = match[1];\n tmp = `{${paramName}}`;\n } else {\n tmp = tmp.slice(1, tmp.length);\n if (tmp.endsWith(\"?\")) tmp = tmp.slice(0, -1);\n tmp = `{${tmp}}`;\n }\n }\n return tmp;\n};\nconst toOpenAPIPath = (path) => path.split(\"/\").map(toOpenAPIPathSegment).join(\"/\");\nconst toPascalCase = (text) => text.split(/[\\W_]+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(\"\");\nconst generateOperationId = (route) => {\n let operationId = route.method.toLowerCase();\n if (route.path === \"/\") return `${operationId}Index`;\n for (const segment of route.path.split(\"/\")) {\n const openApiPathSegment = toOpenAPIPathSegment(segment);\n if (openApiPathSegment.charCodeAt(0) === 123) {\n operationId += `By${toPascalCase(openApiPathSegment.slice(1, -1))}`;\n } else {\n operationId += toPascalCase(openApiPathSegment);\n }\n }\n return operationId;\n};\nconst paramKey = (param) => \"$ref\" in param ? param.$ref : `${param.in} ${param.name}`;\nfunction mergeParameters(...params) {\n const merged = params.flatMap((x) => x ?? []).reduce((acc, param) => {\n acc.set(paramKey(param), param);\n return acc;\n }, /* @__PURE__ */ new Map());\n return Array.from(merged.values());\n}\nconst specsByPathContext = /* @__PURE__ */ new Map();\nfunction getPathContext(path) {\n const context = [];\n for (const [key, data] of specsByPathContext) {\n if (data && path.match(key)) {\n context.push(data);\n }\n }\n return context;\n}\nfunction clearSpecsContext() {\n specsByPathContext.clear();\n}\nfunction mergeSpecs(route, ...specs) {\n return specs.reduce(\n (prev, spec) => {\n if (!spec || !prev) return prev;\n for (const [key, value] of Object.entries(spec)) {\n if (value == null) continue;\n if (key in prev && (typeof value === \"object\" || typeof value === \"function\" && key === \"operationId\")) {\n if (Array.isArray(value)) {\n const values = [...prev[key] ?? [], ...value];\n if (key === \"tags\") {\n prev[key] = Array.from(new Set(values));\n } else if (key === \"parameters\") {\n prev[key] = mergeParameters(values);\n } else {\n prev[key] = values;\n }\n } else if (typeof value === \"function\") {\n prev[key] = value(route);\n } else {\n if (key === \"parameters\") {\n prev[key] = mergeParameters(prev[key], value);\n } else {\n prev[key] = {\n ...prev[key],\n ...value\n };\n }\n }\n } else {\n prev[key] = value;\n }\n }\n return prev;\n },\n {\n operationId: generateOperationId(route)\n }\n );\n}\nfunction registerSchemaPath({\n route,\n specs,\n paths\n}) {\n const path = toOpenAPIPath(route.path);\n const method = route.method.toLowerCase();\n if (method === \"all\") {\n if (!specs) return;\n if (specsByPathContext.has(path)) {\n const prev = specsByPathContext.get(path) ?? {};\n specsByPathContext.set(path, mergeSpecs(route, prev, specs));\n } else {\n specsByPathContext.set(path, specs);\n }\n } else {\n const pathContext = getPathContext(path);\n if (!(path in paths)) {\n paths[path] = {};\n }\n if (paths[path]) {\n paths[path][method] = mergeSpecs(\n route,\n ...pathContext,\n paths[path]?.[method],\n specs\n );\n }\n }\n}\nfunction removeExcludedPaths(paths, ctx) {\n const { exclude, excludeStaticFile } = ctx.options;\n const newPaths = {};\n const _exclude = Array.isArray(exclude) ? exclude : [exclude];\n for (const [key, value] of Object.entries(paths)) {\n if (value == null) continue;\n const isExplicitlyExcluded = _exclude.some((x) => {\n if (typeof x === \"string\") return key === x;\n return x.test(key);\n });\n if (isExplicitlyExcluded) continue;\n const isWildcardWithoutParameters = key.includes(\"*\") && !key.includes(\"{\");\n if (isWildcardWithoutParameters) continue;\n if (excludeStaticFile) {\n const hasPathParameters = key.includes(\"{\");\n const lastSegment = key.split(\"/\").pop() || \"\";\n const looksLikeStaticFile = lastSegment.includes(\".\");\n const shouldExcludeAsStaticFile = !hasPathParameters && looksLikeStaticFile;\n if (shouldExcludeAsStaticFile) continue;\n }\n for (const method of Object.keys(value)) {\n const schema = value[method];\n if (schema == null) continue;\n if (key.includes(\"{\")) {\n schema.parameters = schema.parameters ? [...schema.parameters] : [];\n const pathParameters = key.split(\"/\").filter(\n (x) => x.startsWith(\"{\") && !schema.parameters.find(\n (params) => params.in === \"path\" && params.name === x.slice(1, x.length - 1)\n )\n );\n for (const param of pathParameters) {\n const paramName = param.slice(1, param.length - 1);\n const index = schema.parameters.findIndex(\n (x) => {\n if (\"$ref\" in x) {\n const pos = x.$ref.split(\"/\").pop();\n if (pos) {\n const param2 = ctx.components.parameters?.[pos];\n if (param2 && !(\"$ref\" in param2)) {\n return param2.in === \"path\" && param2.name === paramName;\n }\n }\n return false;\n }\n return x.in === \"path\" && x.name === paramName;\n }\n );\n if (index === -1) {\n schema.parameters.push({\n schema: { type: \"string\" },\n in: \"path\",\n name: paramName,\n required: true\n });\n }\n }\n }\n if (!schema.responses) {\n schema.responses = {\n 200: {}\n };\n }\n }\n const filteredValue = {};\n for (const method of Object.keys(value)) {\n if (value[method] != null) {\n filteredValue[method] = value[method];\n }\n }\n if (Object.keys(filteredValue).length > 0) {\n newPaths[key] = filteredValue;\n }\n }\n return newPaths;\n}\n\nconst DEFAULT_OPTIONS = {\n documentation: {},\n excludeStaticFile: true,\n exclude: [],\n excludeMethods: [\"OPTIONS\"],\n excludeTags: []\n};\nfunction openAPIRouteHandler(hono, options) {\n let specs;\n return async (c) => {\n if (specs) return c.json(specs);\n specs = await generateSpecs(hono, options, c);\n return c.json(specs);\n };\n}\nasync function generateSpecs(hono, options = DEFAULT_OPTIONS, c) {\n const ctx = {\n components: {},\n // @ts-expect-error\n options: {\n ...DEFAULT_OPTIONS,\n ...options\n }\n };\n const _documentation = ctx.options.documentation ?? {};\n clearSpecsContext();\n const paths = await generatePaths(hono, ctx);\n for (const path in paths) {\n for (const method in paths[path]) {\n const isHidden = getHiddenValue({\n valueOrFunc: paths[path][method]?.hide,\n method,\n path,\n c\n });\n if (isHidden) {\n paths[path][method] = void 0;\n }\n }\n }\n const { components: resolvedDocComponents } = _documentation.components?.responses ? await resolveResponseSchemas(_documentation.components.responses) : { components: {} };\n const components = mergeComponentsObjects(\n _documentation.components,\n resolvedDocComponents,\n ctx.components\n );\n return {\n openapi: \"3.1.0\",\n ..._documentation,\n tags: _documentation.tags?.filter(\n (tag) => !ctx.options.excludeTags?.includes(tag?.name)\n ),\n info: {\n title: \"Hono Documentation\",\n description: \"Development documentation\",\n version: \"0.0.0\",\n ..._documentation.info\n },\n paths: {\n ...removeExcludedPaths(paths, ctx),\n ..._documentation.paths\n },\n components\n };\n}\nasync function generatePaths(hono, ctx) {\n const paths = {};\n for (const route of hono.routes) {\n const middlewareHandler = findTargetHandler(route.handler)[uniqueSymbol];\n if (!middlewareHandler) {\n if (ctx.options.includeEmptyPaths) {\n registerSchemaPath({\n route,\n paths\n });\n }\n continue;\n }\n const routeMethod = route.method;\n if (routeMethod !== \"ALL\") {\n if (ctx.options.excludeMethods?.includes(routeMethod)) {\n continue;\n }\n if (!ALLOWED_METHODS.includes(routeMethod)) {\n continue;\n }\n }\n const defaultOptionsForThisMethod = ctx.options.defaultOptions?.[routeMethod] && { ...ctx.options.defaultOptions[routeMethod] };\n const { schema: routeSpecs, components = {} } = await getSpec(\n middlewareHandler,\n defaultOptionsForThisMethod\n );\n ctx.components = mergeComponentsObjects(ctx.components, components);\n registerSchemaPath({\n route,\n specs: routeSpecs,\n paths\n });\n }\n return paths;\n}\nfunction getHiddenValue(options) {\n const { valueOrFunc, c, method, path } = options;\n if (valueOrFunc != null) {\n if (typeof valueOrFunc === \"boolean\") {\n return valueOrFunc;\n }\n if (typeof valueOrFunc === \"function\") {\n return valueOrFunc({ c, method, path });\n }\n }\n return false;\n}\nasync function getSpec(middlewareHandler, defaultOptions) {\n if (\"spec\" in middlewareHandler) {\n const tmp = {\n ...defaultOptions,\n ...middlewareHandler.spec,\n responses: {\n ...defaultOptions?.responses,\n ...middlewareHandler.spec.responses\n }\n };\n let components = {};\n if (tmp.responses) {\n const resolved = await resolveResponseSchemas(tmp.responses);\n components = resolved.components;\n }\n return { schema: tmp, components };\n }\n const result = await middlewareHandler.toOpenAPISchema();\n const docs = { ...defaultOptions };\n if (middlewareHandler.target === \"form\" || middlewareHandler.target === \"json\") {\n const media = middlewareHandler.options?.media ?? middlewareHandler.target === \"json\" ? \"application/json\" : \"multipart/form-data\";\n if (!docs.requestBody || !(\"content\" in docs.requestBody) || !docs.requestBody.content) {\n docs.requestBody = {\n required: true,\n content: {\n [media]: {\n schema: result.schema\n }\n }\n };\n } else {\n docs.requestBody.content[media] = {\n schema: result.schema\n };\n }\n } else {\n let parameters = [];\n if (\"$ref\" in result.schema) {\n const ref = result.schema.$ref;\n const pos = ref.split(\"/\").pop();\n if (pos && result.components?.schemas?.[pos]) {\n const schema = result.components.schemas[pos];\n const newParameters = generateParameters(\n middlewareHandler.target,\n schema\n )[0];\n if (!result.components.parameters) {\n result.components.parameters = {};\n }\n result.components.parameters[pos] = newParameters;\n delete result.components.schemas[pos];\n parameters.push({\n $ref: `#/components/parameters/${pos}`\n });\n }\n } else {\n parameters = generateParameters(middlewareHandler.target, result.schema);\n }\n docs.parameters = parameters;\n }\n return { schema: docs, components: result.components };\n}\nfunction generateParameters(target, schema) {\n const parameters = [];\n for (const [key, value] of Object.entries(schema.properties ?? {})) {\n const def = {\n in: target === \"param\" ? \"path\" : target,\n name: key,\n // @ts-expect-error\n schema: value\n };\n const isRequired = schema.required?.includes(key);\n if (isRequired) {\n def.required = true;\n }\n if (def.schema && \"description\" in def.schema && def.schema.description) {\n def.description = def.schema.description;\n def.schema.description = void 0;\n }\n parameters.push(def);\n }\n return parameters;\n}\nasync function resolveResponseSchemas(responses) {\n let components = {};\n for (const key of Object.keys(responses)) {\n const response = responses[key];\n if (!response || !(\"content\" in response)) continue;\n for (const contentKey of Object.keys(response.content ?? {})) {\n const raw = response.content?.[contentKey];\n if (!raw) continue;\n if (raw.schema && \"toOpenAPISchema\" in raw.schema) {\n const result = await raw.schema.toOpenAPISchema();\n raw.schema = result.schema;\n if (result.components) {\n components = mergeComponentsObjects(components, result.components);\n }\n }\n }\n }\n return { responses, components };\n}\nfunction mergeComponentsObjects(...components) {\n return components.reduce(\n (prev, component, index) => {\n if (component == null || index === 0) return prev;\n if (prev.schemas && Object.keys(prev.schemas).length > 0 || component.schemas && Object.keys(component.schemas).length > 0) {\n prev.schemas = {\n ...prev.schemas,\n ...component.schemas\n };\n }\n if (prev.parameters && Object.keys(prev.parameters).length > 0 || component.parameters && Object.keys(component.parameters).length > 0) {\n prev.parameters = {\n ...prev.parameters,\n ...component.parameters\n };\n }\n return prev;\n },\n components[0] ?? {}\n );\n}\n\nfunction loadVendor(vendor, fn) {\n if (fn.toJSONSchema) {\n loadVendor$1(vendor, fn.toJSONSchema);\n }\n if (fn.toOpenAPISchema) {\n loadVendor$2(vendor, fn.toOpenAPISchema);\n }\n}\nconst arktypeMorphFallback = (ctx) => ctx.base;\nconst zodV4DateOverride = (ctx) => {\n if (ctx.zodSchema._zod.def.type === \"date\") {\n ctx.jsonSchema.type = \"string\";\n ctx.jsonSchema.format = \"date-time\";\n }\n};\nfunction resolver(schema, userDefinedOptions) {\n const vendor = schema[\"~standard\"].vendor;\n return {\n vendor,\n validate: schema[\"~standard\"].validate,\n toJSONSchema: (customOptions) => toJsonSchema(schema, { ...userDefinedOptions, ...customOptions }),\n toOpenAPISchema: (customOptions) => toOpenAPISchema(schema, {\n ...userDefinedOptions,\n ...customOptions,\n ...vendor === \"arktype\" ? injectArktypeFallback(userDefinedOptions, customOptions) : void 0,\n ...vendor === \"zod\" ? injectZodV4DateOverride(schema, userDefinedOptions, customOptions) : void 0\n })\n };\n}\nfunction injectArktypeFallback(userDefined, custom) {\n const userNested = userDefined?.options;\n const customNested = custom?.options;\n if (userDefined?.fallback || userNested?.fallback || custom?.fallback || customNested?.fallback) {\n return void 0;\n }\n return {\n options: {\n fallback: arktypeMorphFallback,\n ...userNested,\n ...customNested\n }\n };\n}\nfunction injectZodV4DateOverride(schema, userDefined, custom) {\n if (!(\"_zod\" in schema)) return void 0;\n const userNested = userDefined?.options;\n const customNested = custom?.options;\n if (userDefined?.override || userNested?.override || custom?.override || customNested?.override) {\n return void 0;\n }\n return {\n options: {\n unrepresentable: \"any\",\n override: zodV4DateOverride,\n ...userNested,\n ...customNested\n }\n };\n}\nfunction validator(target, schema, hook, options) {\n const middleware = sValidator(target, schema, hook);\n Object.defineProperty(middleware, \"name\", {\n value: \"validator\",\n configurable: true\n });\n return Object.assign(middleware, {\n [uniqueSymbol]: {\n target,\n ...resolver(schema, options),\n options\n }\n });\n}\nfunction describeRoute(spec) {\n const middleware = async (_c, next) => {\n await next();\n };\n Object.defineProperty(middleware, \"name\", {\n value: \"describeRoute\",\n configurable: true\n });\n return Object.assign(middleware, {\n [uniqueSymbol]: {\n spec\n }\n });\n}\nfunction describeResponse(handler, responses, options) {\n const _responses = Object.entries(responses).reduce(\n (acc, [statusCode, response]) => {\n if (response.content) {\n const content = Object.entries(response.content).reduce(\n (contentAcc, [mediaType, media]) => {\n if (media.vSchema) {\n const { vSchema, ...rest } = media;\n contentAcc[mediaType] = {\n ...rest,\n schema: resolver(vSchema, options)\n };\n } else {\n contentAcc[mediaType] = media;\n }\n return contentAcc;\n },\n {}\n );\n acc[statusCode] = { ...response, content };\n } else {\n acc[statusCode] = response;\n }\n return acc;\n },\n {}\n );\n return Object.assign(handler, {\n [uniqueSymbol]: {\n spec: { responses: _responses }\n }\n });\n}\n\nexport { ALLOWED_METHODS, clearSpecsContext, describeResponse, describeRoute, generateSpecs, loadVendor, openAPIRouteHandler, registerSchemaPath, removeExcludedPaths, resolver, uniqueSymbol, validator };\n","import process from 'node:process';\nimport type { Context } from 'hono';\n\nconst DEFAULT_AGENT_LEARNING_ENDPOINT = 'https://output.signals.mastra.ai';\nconst AGENT_LEARNING_TIMEOUT_MS = 8_000;\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport async function agentLearningProxyHandler(c: Context): Promise<Response> {\n const requestUrl = new URL(c.req.url);\n if (!LOOPBACK_HOSTS.has(requestUrl.hostname)) {\n return c.json({ error: 'Agent Learning development proxy is only available on loopback hosts' }, 403);\n }\n\n const origin = c.req.header('Origin');\n if (origin && origin !== requestUrl.origin) {\n return c.json({ error: 'Cross-origin Agent Learning requests are not allowed' }, 403);\n }\n\n const accessToken = process.env.MASTRA_PLATFORM_ACCESS_TOKEN;\n const projectId = process.env.MASTRA_PROJECT_ID;\n if (!accessToken || !projectId) {\n return c.json(\n {\n error: 'MASTRA_PLATFORM_ACCESS_TOKEN and MASTRA_PROJECT_ID are required for Agent Learning',\n },\n 503,\n );\n }\n\n const endpoint = process.env.MASTRA_PLATFORM_AGENT_LEARNING_ENDPOINT || DEFAULT_AGENT_LEARNING_ENDPOINT;\n let upstreamUrl: URL;\n try {\n upstreamUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, `${endpoint.replace(/\\/+$/, '')}/`);\n } catch {\n return c.json({ error: 'MASTRA_PLATFORM_AGENT_LEARNING_ENDPOINT must be a valid URL' }, 503);\n }\n\n try {\n const upstream = await fetch(upstreamUrl, {\n method: 'GET',\n headers: {\n Accept: c.req.header('Accept') || 'application/json',\n Authorization: `Bearer ${accessToken}`,\n 'X-Mastra-Project-Id': projectId,\n },\n signal: AbortSignal.timeout(AGENT_LEARNING_TIMEOUT_MS),\n });\n\n const headers = new Headers();\n const contentType = upstream.headers.get('content-type');\n const cacheControl = upstream.headers.get('cache-control');\n if (contentType) headers.set('content-type', contentType);\n if (cacheControl) headers.set('cache-control', cacheControl);\n\n return new Response(upstream.body, {\n status: upstream.status,\n statusText: upstream.statusText,\n headers,\n });\n } catch {\n return c.json({ error: 'Agent Learning upstream unavailable' }, 502);\n }\n}\n","import type { Context } from 'hono';\n\nconst clients = new Set<ReadableStreamDefaultController>();\nlet hotReloadDisabled = false;\n\nexport function handleClientsRefresh(c: Context): Response {\n const stream = new ReadableStream({\n start(controller) {\n clients.add(controller);\n controller.enqueue('data: connected\\n\\n');\n\n c.req.raw.signal.addEventListener('abort', () => {\n clients.delete(controller);\n });\n },\n });\n\n return new Response(stream, {\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'Access-Control-Allow-Origin': '*',\n },\n });\n}\n\nexport function handleTriggerClientsRefresh(c: Context) {\n clients.forEach(controller => {\n try {\n controller.enqueue('data: refresh\\n\\n');\n } catch {\n clients.delete(controller);\n }\n });\n return c.json({ success: true, clients: clients.size });\n}\n\n// Functions to control hot reload during template installation\nexport function disableHotReload() {\n hotReloadDisabled = true;\n console.info('🔒 Hot reload disabled for template installation');\n}\n\nexport function enableHotReload() {\n hotReloadDisabled = false;\n console.info('🔓 Hot reload re-enabled after template installation');\n}\n\nexport function isHotReloadDisabled(): boolean {\n return hotReloadDisabled;\n}\n","import type { Context } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport type { ContentfulStatusCode } from 'hono/utils/http-status';\n\nimport type { ApiError } from '../types';\n\n// Helper to handle errors consistently\nexport function handleError(error: unknown, defaultMessage: string): Promise<Response> {\n const apiError = error as ApiError;\n throw new HTTPException((apiError.status || 500) as ContentfulStatusCode, {\n message: apiError.message || defaultMessage,\n cause: apiError.cause,\n });\n}\nexport function errorHandler(err: Error, c: Context, isDev?: boolean): Response {\n if (err instanceof HTTPException) {\n if (isDev) {\n return c.json({ error: err.message, cause: err.cause, stack: err.stack }, err.status);\n }\n return c.json({ error: err.message }, err.status);\n }\n\n c.get('mastra').getLogger().error(err);\n return c.json({ error: 'Internal Server Error' }, 500);\n}\n","import type { Context } from 'hono';\n\n// Health check handler\nexport async function healthHandler(c: Context) {\n return c.json({ success: true }, 200);\n}\n","import type { Mastra } from '@mastra/core/mastra';\nimport type { Context } from 'hono';\n\nimport { handleError } from './error';\n\nexport async function restartAllActiveWorkflowRunsHandler(c: Context) {\n try {\n const mastra: Mastra = c.get('mastra');\n void mastra.restartAllActiveWorkflowRuns().catch(error => {\n mastra.getLogger().error('Failed to restart active workflow runs during server startup', { error });\n });\n\n // Opt-in boot-time recovery for orphaned RUNNING durable-agent runs.\n // Gated by `recovery.durableAgents === 'auto'` so we don't silently\n // re-issue LLM calls / re-execute tools on restart.\n if (mastra.recoveryConfig?.durableAgents === 'auto') {\n void mastra.recoverAllDurableAgents().catch(error => {\n mastra.getLogger().error('Failed to recover durable agent runs during server startup', { error });\n });\n }\n\n return c.json({ message: 'Restarting all active workflow runs...' });\n } catch (error) {\n return handleError(error, 'Error restarting active workflow runs');\n }\n}\n","import type { Context } from 'hono';\n\n// Root handler\nexport async function rootHandler(c: Context) {\n const baseUrl = new URL(c.req.url).origin;\n\n return c.html(\n /* html */\n `\n <!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Mastra API</title>\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/inter-ui/3.19.3/inter.min.css\" />\n <style>\n body {\n margin: 0;\n padding: 0;\n background-color: #0d0d0d;\n color: #ffffff;\n font-family:\n 'Inter',\n -apple-system,\n BlinkMacSystemFont,\n system-ui,\n sans-serif;\n min-height: 100vh;\n display: flex;\n flex-direction: column;\n }\n\n main {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 2rem;\n text-align: center;\n }\n\n h1 {\n font-size: 4rem;\n font-weight: 600;\n margin: 0 0 1rem 0;\n background: linear-gradient(to right, #fff, #ccc);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n line-height: 1.2;\n }\n\n .subtitle {\n color: #9ca3af;\n font-size: 1.25rem;\n max-width: 600px;\n margin: 0 auto 3rem auto;\n line-height: 1.6;\n }\n\n .link {\n color: #ffffff;\n }\n\n .link:hover {\n text-decoration: none;\n }\n\n .docs-link {\n background-color: #1a1a1a;\n padding: 1rem 2rem;\n border-radius: 0.5rem;\n display: flex;\n align-items: center;\n gap: 1rem;\n font-family: monospace;\n font-size: 1rem;\n color: #ffffff;\n text-decoration: none;\n transition: background-color 0.2s;\n }\n\n .docs-link:hover {\n background-color: #252525;\n }\n\n .arrow-icon {\n transition: transform 0.2s;\n }\n\n .docs-link:hover .arrow-icon {\n transform: translateX(4px);\n }\n </style>\n </head>\n <body>\n <main>\n <h1>Welcome to the Mastra API</h1>\n <p class=\"subtitle\">\n Discover all available endpoints through Swagger UI. You can also define your own <a href=\"https://mastra.ai/docs/server-db/custom-api-routes\" target=\"_blank\" class=\"link\">API routes</a>.\n </p>\n <a href=\"${baseUrl}/swagger-ui\" target=\"_blank\" class=\"docs-link\">\n Browse Swagger UI\n <svg\n class=\"arrow-icon\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <path d=\"M5 12h14M12 5l7 7-7 7\" />\n </svg>\n </a>\n </main>\n </body>\n </html>\n `,\n );\n}\n","/**\n * Trim leading and trailing slashes. Index scan instead of regex to avoid\n * backtracking (CodeQL js/polynomial-redos).\n */\nfunction trimSlashes(value: string): string {\n let start = 0;\n let end = value.length;\n while (start < end && value[start] === '/') start++;\n while (end > start && value[end - 1] === '/') end--;\n return value.slice(start, end);\n}\n\nexport function welcomeHtml(apiPrefix: string = '/api') {\n // Normalize: ensure single leading slash, no trailing slash.\n const prefix = '/' + trimSlashes(apiPrefix);\n const prefixNoSlash = prefix.slice(1);\n return `\n<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Mastra Server</title>\n <style>\n * { box-sizing: border-box; }\n\n body {\n margin: 0;\n padding: 0;\n background-color: #0a0a0a;\n color: #e4e4e7;\n font-family: -apple-system, BlinkMacSystemFont, system-ui, sans-serif;\n min-height: 100vh;\n line-height: 1.6;\n }\n\n .page {\n max-width: 720px;\n margin: 0 auto;\n padding: 3rem 1.5rem 4rem;\n }\n\n header {\n margin-bottom: 2.5rem;\n }\n\n header h1 {\n font-size: 1.75rem;\n font-weight: 600;\n margin: 0 0 0.25rem;\n color: #fff;\n }\n\n header p {\n color: #71717a;\n font-size: 0.9rem;\n margin: 0;\n }\n\n .status-bar {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n margin-top: 1rem;\n font-size: 0.8rem;\n color: #a1a1aa;\n }\n\n .status-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: #22c55e;\n flex-shrink: 0;\n }\n\n section {\n margin-bottom: 2rem;\n }\n\n section h2 {\n font-size: 0.75rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: #71717a;\n margin: 0 0 0.75rem;\n }\n\n .card {\n background: #18181b;\n border: 1px solid #27272a;\n border-radius: 8px;\n overflow: hidden;\n }\n\n .card + .card {\n margin-top: 0.75rem;\n }\n\n .card-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0.75rem 1rem;\n gap: 0.75rem;\n }\n\n .card-row + .card-row {\n border-top: 1px solid #27272a;\n }\n\n .card-row-left {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n min-width: 0;\n }\n\n .method {\n font-family: 'SF Mono', SFMono-Regular, ui-monospace, Menlo, monospace;\n font-size: 0.7rem;\n font-weight: 600;\n padding: 2px 6px;\n border-radius: 4px;\n flex-shrink: 0;\n }\n\n .method-get { background: #052e16; color: #4ade80; }\n .method-post { background: #172554; color: #60a5fa; }\n\n .endpoint-path {\n font-family: 'SF Mono', SFMono-Regular, ui-monospace, Menlo, monospace;\n font-size: 0.8rem;\n color: #d4d4d8;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .endpoint-desc {\n font-size: 0.75rem;\n color: #71717a;\n flex-shrink: 0;\n }\n\n .curl-block {\n position: relative;\n background: #111113;\n border: 1px solid #27272a;\n border-radius: 8px;\n overflow: hidden;\n }\n\n .curl-block + .curl-block {\n margin-top: 0.75rem;\n }\n\n .curl-label {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0.5rem 1rem;\n border-bottom: 1px solid #27272a;\n font-size: 0.75rem;\n color: #a1a1aa;\n }\n\n .copy-btn {\n background: none;\n border: 1px solid #3f3f46;\n border-radius: 4px;\n color: #a1a1aa;\n font-size: 0.7rem;\n padding: 2px 8px;\n cursor: pointer;\n font-family: inherit;\n transition: all 0.15s;\n }\n\n .copy-btn:hover {\n background: #27272a;\n color: #e4e4e7;\n }\n\n .curl-code {\n padding: 0.75rem 1rem;\n font-family: 'SF Mono', SFMono-Regular, ui-monospace, Menlo, monospace;\n font-size: 0.8rem;\n line-height: 1.5;\n color: #d4d4d8;\n overflow-x: auto;\n white-space: pre;\n margin: 0;\n }\n\n .curl-code .c-cmd { color: #a78bfa; }\n .curl-code .c-flag { color: #60a5fa; }\n .curl-code .c-url { color: #fbbf24; }\n .curl-code .c-str { color: #4ade80; }\n\n .links-grid {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 0.75rem;\n }\n\n .link-card {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n padding: 0.875rem 1rem;\n background: #18181b;\n border: 1px solid #27272a;\n border-radius: 8px;\n color: #d4d4d8;\n text-decoration: none;\n font-size: 0.85rem;\n transition: all 0.15s;\n }\n\n .link-card:hover {\n background: #1f1f23;\n border-color: #3f3f46;\n color: #fff;\n }\n\n .link-icon {\n flex-shrink: 0;\n width: 18px;\n height: 18px;\n color: #71717a;\n }\n\n .link-card:hover .link-icon { color: #a1a1aa; }\n\n footer {\n margin-top: 3rem;\n padding-top: 1.5rem;\n border-top: 1px solid #1c1c1f;\n font-size: 0.75rem;\n color: #52525b;\n }\n\n @media (max-width: 480px) {\n .page { padding: 2rem 1rem 3rem; }\n header h1 { font-size: 1.5rem; }\n .links-grid { grid-template-columns: 1fr; }\n .endpoint-desc { display: none; }\n }\n </style>\n </head>\n <body>\n <div class=\"page\">\n <header>\n <h1>Mastra Server</h1>\n <p>Your server is running. Use the endpoints below to get started.</p>\n <div class=\"status-bar\">\n <span class=\"status-dot\"></span>\n <span id=\"base-url\"></span>\n </div>\n </header>\n\n <section>\n <h2>Quick Start</h2>\n\n <div class=\"curl-block\">\n <div class=\"curl-label\">\n <span>Check server health</span>\n <button class=\"copy-btn\" onclick=\"copyCode(this)\">Copy</button>\n </div>\n <pre class=\"curl-code\" data-tpl=\"curl <base>/health\"><span class=\"c-cmd\">curl</span> <span class=\"c-url\" data-url=\"health\"></span></pre>\n </div>\n\n <div class=\"curl-block\">\n <div class=\"curl-label\">\n <span>List your agents</span>\n <button class=\"copy-btn\" onclick=\"copyCode(this)\">Copy</button>\n </div>\n <pre class=\"curl-code\" data-tpl=\"curl <base>${prefix}/agents\"><span class=\"c-cmd\">curl</span> <span class=\"c-url\" data-url=\"${prefixNoSlash}/agents\"></span></pre>\n </div>\n\n <div class=\"curl-block\">\n <div class=\"curl-label\">\n <span>Chat with an agent</span>\n <button class=\"copy-btn\" onclick=\"copyCode(this)\">Copy</button>\n </div>\n <pre class=\"curl-code\" data-tpl=\"curl -X POST <base>${prefix}/agents/:agent-id/generate -H 'Content-Type: application/json' -d '{&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Hello&quot;}]}'\"><span class=\"c-cmd\">curl</span> <span class=\"c-flag\">-X POST</span> <span class=\"c-url\" data-url=\"${prefixNoSlash}/agents/:agent-id/generate\"></span> \\\\\n <span class=\"c-flag\">-H</span> <span class=\"c-str\">'Content-Type: application/json'</span> \\\\\n <span class=\"c-flag\">-d</span> <span class=\"c-str\">'{\"messages\":[{\"role\":\"user\",\"content\":\"Hello\"}]}'</span></pre>\n </div>\n\n <div class=\"curl-block\">\n <div class=\"curl-label\">\n <span>Stream an agent response</span>\n <button class=\"copy-btn\" onclick=\"copyCode(this)\">Copy</button>\n </div>\n <pre class=\"curl-code\" data-tpl=\"curl -N -X POST <base>${prefix}/agents/:agent-id/stream -H 'Content-Type: application/json' -d '{&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Hello&quot;}]}'\"><span class=\"c-cmd\">curl</span> <span class=\"c-flag\">-N -X POST</span> <span class=\"c-url\" data-url=\"${prefixNoSlash}/agents/:agent-id/stream\"></span> \\\\\n <span class=\"c-flag\">-H</span> <span class=\"c-str\">'Content-Type: application/json'</span> \\\\\n <span class=\"c-flag\">-d</span> <span class=\"c-str\">'{\"messages\":[{\"role\":\"user\",\"content\":\"Hello\"}]}'</span></pre>\n </div>\n </section>\n\n <section>\n <h2>API Endpoints</h2>\n <div class=\"card\">\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-get\">GET</span>\n <span class=\"endpoint-path\">${prefix}/agents</span>\n </div>\n <span class=\"endpoint-desc\">List all agents</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-post\">POST</span>\n <span class=\"endpoint-path\">${prefix}/agents/:id/generate</span>\n </div>\n <span class=\"endpoint-desc\">Generate a response</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-post\">POST</span>\n <span class=\"endpoint-path\">${prefix}/agents/:id/stream</span>\n </div>\n <span class=\"endpoint-desc\">Stream a response</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-get\">GET</span>\n <span class=\"endpoint-path\">${prefix}/workflows</span>\n </div>\n <span class=\"endpoint-desc\">List all workflows</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-post\">POST</span>\n <span class=\"endpoint-path\">${prefix}/workflows/:id/start</span>\n </div>\n <span class=\"endpoint-desc\">Run a workflow</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-get\">GET</span>\n <span class=\"endpoint-path\">${prefix}/tools</span>\n </div>\n <span class=\"endpoint-desc\">List all tools</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-post\">POST</span>\n <span class=\"endpoint-path\">${prefix}/tools/:id/execute</span>\n </div>\n <span class=\"endpoint-desc\">Execute a tool</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-get\">GET</span>\n <span class=\"endpoint-path\">${prefix}/memory/threads</span>\n </div>\n <span class=\"endpoint-desc\">List memory threads</span>\n </div>\n </div>\n </section>\n\n <section>\n <h2>Resources</h2>\n <div class=\"links-grid\">\n <a href=\"https://mastra.ai/docs\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"link-card\">\n <svg class=\"link-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 19.5A2.5 2.5 0 0 1 6.5 17H20\"/><path d=\"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z\"/></svg>\n Documentation\n </a>\n <a href=\"https://mastra.ai/docs/server-db/custom-api-routes\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"link-card\">\n <svg class=\"link-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M16 18l6-6-6-6\"/><path d=\"M8 6l-6 6 6 6\"/></svg>\n Custom API Routes\n </a>\n <a href=\"https://mastra.ai/docs/agents/overview\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"link-card\">\n <svg class=\"link-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"3\"/><path d=\"M12 1v4m0 14v4m-7.8-15.4 2.8 2.8m9.6 9.6 2.8 2.8M1 12h4m14 0h4M4.2 19.8l2.8-2.8m9.6-9.6 2.8-2.8\"/></svg>\n Agents Guide\n </a>\n <a href=\"https://mastra.ai/docs/workflows/overview\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"link-card\">\n <svg class=\"link-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"16 3 21 3 21 8\"/><line x1=\"4\" y1=\"20\" x2=\"21\" y2=\"3\"/><polyline points=\"21 16 21 21 16 21\"/><line x1=\"15\" y1=\"15\" x2=\"21\" y2=\"21\"/><line x1=\"4\" y1=\"4\" x2=\"9\" y2=\"9\"/></svg>\n Workflows Guide\n </a>\n </div>\n </section>\n\n <footer>\n Powered by <a href=\"https://mastra.ai\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"color:#71717a;\">Mastra</a>\n </footer>\n </div>\n\n <script>\n (function() {\n var base = location.origin;\n document.getElementById('base-url').textContent = base;\n\n var els = document.querySelectorAll('[data-url]');\n for (var i = 0; i < els.length; i++) {\n els[i].textContent = base + '/' + els[i].getAttribute('data-url');\n }\n\n var tpls = document.querySelectorAll('[data-tpl]');\n for (var i = 0; i < tpls.length; i++) {\n tpls[i].setAttribute('data-tpl', tpls[i].getAttribute('data-tpl').replace(/<base>/g, base));\n }\n })();\n\n function copyCode(btn) {\n var pre = btn.closest('.curl-block').querySelector('.curl-code');\n var text = pre.getAttribute('data-tpl');\n if (!navigator.clipboard || !navigator.clipboard.writeText) {\n btn.textContent = 'Unavailable';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n return;\n }\n navigator.clipboard.writeText(text).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n }).catch(function() {\n btn.textContent = 'Failed';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n }\n </script>\n </body>\n</html>\n`;\n}\n","import { readFile } from 'node:fs/promises';\nimport * as https from 'node:https';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { serve } from '@hono/node-server';\nimport { serveStatic } from '@hono/node-server/serve-static';\nimport { swaggerUI } from '@hono/swagger-ui';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { ApiRoute, CorsOptions } from '@mastra/core/server';\nimport { Tool } from '@mastra/core/tools';\nimport { MastraServer, setupBrowserStream, skipIfFrameworkPublic } from '@mastra/hono';\nimport type { HonoBindings, HonoVariables } from '@mastra/hono';\nimport { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport { findMatchingCustomRoute } from '@mastra/server/auth';\nimport type { Context, MiddlewareHandler as HonoMiddlewareHandler } from 'hono';\nimport { Hono } from 'hono';\nimport { compress } from 'hono/compress';\nimport { cors } from 'hono/cors';\nimport { logger } from 'hono/logger';\nimport { timeout } from 'hono/timeout';\nimport { describeRoute } from 'hono-openapi';\nimport type { DescribeRouteOptions } from 'hono-openapi';\nimport { escapeStudioHtmlValue, injectStudioHtmlConfig, normalizeStudioBase } from '../build/utils';\nimport { agentLearningProxyHandler } from './handlers/agent-learning';\nimport { handleClientsRefresh, handleTriggerClientsRefresh, isHotReloadDisabled } from './handlers/client';\nimport { errorHandler } from './handlers/error';\nimport { healthHandler } from './handlers/health';\nimport { restartAllActiveWorkflowRunsHandler } from './handlers/restart-active-runs';\nimport { rootHandler } from './handlers/root';\nimport type { ServerBundleOptions } from './types';\nimport { welcomeHtml } from './welcome';\n\n// Get studio path from env or default to ./studio relative to cwd\nconst getStudioPath = () => {\n if (process.env.MASTRA_STUDIO_PATH) {\n return process.env.MASTRA_STUDIO_PATH;\n }\n\n let __dirname: string = '.';\n if (import.meta.url) {\n const __filename = fileURLToPath(import.meta.url);\n __dirname = dirname(__filename);\n }\n\n const studioPath = process.env.MASTRA_STUDIO_PATH || join(__dirname, 'studio');\n return studioPath;\n};\n\n// Use adapter type definitions\ntype Bindings = HonoBindings;\n\ntype Variables = HonoVariables & {\n clients: Set<{ controller: ReadableStreamDefaultController }>;\n};\n\ntype ApiRouteMiddleware = Extract<Exclude<ApiRoute['middleware'], undefined>, Function>;\n\nconst DEFAULT_CORS_ALLOW_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];\nconst DEFAULT_CORS_ALLOW_HEADERS = [\n 'Content-Type',\n 'Authorization',\n 'A2A-Version',\n 'x-mastra-client-type',\n 'x-mastra-dev-playground',\n];\nconst DEFAULT_CORS_EXPOSE_HEADERS = ['Content-Length', 'X-Requested-With'];\n\nfunction getCorsConfig(serverCors: CorsOptions | false | undefined, credentialsDefault: boolean) {\n const userCors = serverCors && typeof serverCors === 'object' ? serverCors : undefined;\n const origin =\n userCors && 'origin' in userCors && userCors.origin\n ? userCors.origin\n : credentialsDefault\n ? (requestOrigin: string) => requestOrigin || undefined\n : '*';\n const credentials = userCors && 'credentials' in userCors ? userCors.credentials : credentialsDefault;\n\n return {\n origin,\n allowMethods: DEFAULT_CORS_ALLOW_METHODS,\n credentials,\n maxAge: 3600,\n ...userCors,\n allowHeaders: [...DEFAULT_CORS_ALLOW_HEADERS, ...(userCors?.allowHeaders ?? [])],\n exposeHeaders: [...DEFAULT_CORS_EXPOSE_HEADERS, ...(userCors?.exposeHeaders ?? [])],\n };\n}\n\nfunction getRouteCorsConfig(apiRoutes: ApiRoute[] | undefined, pathname: string, method: string) {\n const route = findMatchingCustomRoute(pathname, method, apiRoutes)?.route;\n return route?.cors;\n}\n\nexport function getToolExports(tools: Record<string, Function>[]) {\n try {\n return tools.reduce((acc, toolModule) => {\n Object.entries(toolModule).forEach(([key, tool]) => {\n if (tool instanceof Tool) {\n acc[key] = tool;\n }\n });\n return acc;\n }, {});\n } catch (err: any) {\n console.error(\n `Failed to import tools\nreason: ${err.message}\n${err.stack.split('\\n').slice(1).join('\\n')}\n `,\n err,\n );\n }\n}\n\nexport async function createHonoServer(\n mastra: Mastra,\n options: ServerBundleOptions = {\n tools: {},\n },\n) {\n // Register bundled tools with Mastra so they can be used by stored agents\n // This bridges the gap between tools discovered by the CLI bundler and the Mastra instance\n if (options.tools) {\n for (const [key, tool] of Object.entries(options.tools)) {\n try {\n mastra.addTool(tool as any, key);\n } catch {\n // Tool may already be registered (e.g., if defined in Mastra config), ignore\n }\n }\n }\n\n // Create typed Hono app\n const app = new Hono<{ Bindings: Bindings; Variables: Variables }>();\n const server = mastra.getServer();\n const apiPrefix = server?.apiPrefix ?? '/api';\n const a2aTaskStore = new InMemoryTaskStore();\n const routes = server?.apiRoutes;\n\n // Pre-process routes: bake hono-openapi describeRoute into route middleware\n // so the adapter handles it as normal middleware without needing to know about hono-openapi\n const processedRoutes: ApiRoute[] | undefined = routes?.map(route => {\n if ('openapi' in route && route.openapi) {\n const existingMiddleware = route.middleware\n ? Array.isArray(route.middleware)\n ? route.middleware\n : [route.middleware]\n : [];\n return {\n ...route,\n middleware: [\n describeRoute(route.openapi as unknown as DescribeRouteOptions) as unknown as ApiRouteMiddleware,\n ...existingMiddleware,\n ],\n };\n }\n return route;\n });\n\n // Store custom route auth configurations\n const customRouteAuthConfig = new Map<string, boolean>();\n\n if (processedRoutes) {\n for (const route of processedRoutes) {\n // By default, routes require authentication unless explicitly set to false\n const requiresAuth = route.requiresAuth !== false;\n const routeKey = `${route.method}:${route.path}`;\n customRouteAuthConfig.set(routeKey, requiresAuth);\n }\n }\n\n // Set up error handling - use custom onError handler if provided, otherwise use default\n const customOnError = server?.onError;\n app.onError((err, c) => {\n if (customOnError) {\n return customOnError(err, c as unknown as Parameters<typeof customOnError>[1]);\n }\n return errorHandler(err, c, options.isDev);\n });\n\n // Define body limit options\n const bodyLimitOptions = {\n maxSize: server?.bodySizeLimit ?? 4.5 * 1024 * 1024, // 4.5 MB,\n onError: () => ({ error: 'Request body too large' }),\n };\n\n // Create server adapter with all configuration\n const honoServerAdapter = new MastraServer({\n app,\n mastra,\n tools: options.tools,\n taskStore: a2aTaskStore,\n bodyLimitOptions,\n openapiPath: options?.isDev || server?.build?.openAPIDocs ? '/openapi.json' : undefined,\n customRouteAuthConfig,\n customApiRoutes: processedRoutes,\n prefix: apiPrefix,\n mcpOptions: server?.mcpOptions,\n });\n\n // Register context middleware FIRST - this sets mastra, requestContext, tools, taskStore in context\n // Cast needed due to Hono type variance - safe because registerContextMiddleware is generic\n honoServerAdapter.registerContextMiddleware();\n\n // Apply custom server middleware from Mastra instance\n const serverMiddleware = mastra.getServerMiddleware?.();\n\n if (serverMiddleware && serverMiddleware.length > 0) {\n for (const m of serverMiddleware) {\n // Wrap with skipIfFrameworkPublic so user middleware cannot 401 routes\n // the framework declared public via `requiresAuth: false`\n // (e.g. Studio sign-in endpoints like /api/auth/capabilities).\n app.use(m.path, skipIfFrameworkPublic(m.handler));\n }\n }\n\n // Browser stream WebSocket setup - MUST be before CORS middleware\n // to avoid \"can't modify immutable headers\" error on WebSocket upgrade\n // This is async because it dynamically imports @hono/node-ws to avoid\n // bundling ws into user code. Returns null if ws is not available.\n const browserStreamSetup =\n options.browserStream === false\n ? null\n : await setupBrowserStream(app, {\n getToolset: async (agentId: string) => {\n // Look up agent and return its browser if configured.\n // First try the runtime registry (code-defined + previously hydrated agents),\n // then fall back to the editor for stored agents (hydrates on first access).\n try {\n const runtimeAgent = mastra.getAgentById(agentId);\n if (runtimeAgent) {\n return runtimeAgent.browser;\n }\n } catch {\n // Agent not in runtime registry — try stored agents via editor\n }\n\n try {\n const storedAgent = await mastra.getEditor?.()?.agent.getById(agentId);\n return storedAgent?.browser;\n } catch {\n return undefined;\n }\n },\n apiPrefix,\n });\n\n // Fallback session probe when browser streaming isn't available\n // (ws / @hono/node-ws not installed, disabled by deployer, or serverless environment).\n // Lets the client decide not to open a WS instead of failing the upgrade.\n if (!browserStreamSetup) {\n app.get(`${apiPrefix}/agents/:agentId/browser/session`, c =>\n c.json({ hasSession: false, screencastAvailable: false }),\n );\n }\n\n // Global CORS config\n if (server?.cors === false) {\n app.use('*', timeout(server?.timeout ?? 3 * 60 * 1000));\n } else {\n const hasAuth = !!server?.auth;\n app.use('*', timeout(server?.timeout ?? 3 * 60 * 1000), async (c, next) => {\n const pathname = new URL(c.req.url).pathname;\n const method =\n c.req.method === 'OPTIONS' ? (c.req.header('Access-Control-Request-Method') ?? c.req.method) : c.req.method;\n const routeCors = getRouteCorsConfig(processedRoutes, pathname, method);\n\n const corsOptions = routeCors ? getCorsConfig(routeCors, false) : getCorsConfig(server?.cors, hasAuth);\n return cors(corsOptions as unknown as Parameters<typeof cors>[0])(c, next);\n });\n }\n\n // Health check endpoint (before auth middleware so it's publicly accessible)\n app.get(\n '/health',\n describeRoute({\n description: 'Health check endpoint',\n tags: ['system'],\n responses: {\n 200: {\n description: 'Service is healthy',\n },\n },\n }),\n healthHandler,\n );\n\n if (options?.isDev && options.studio) {\n app.get('/api/learning/*', agentLearningProxyHandler);\n }\n\n if (options?.isDev || server?.build?.swaggerUI) {\n app.get(\n apiPrefix,\n describeRoute({\n description: 'API Welcome Page',\n tags: ['system'],\n responses: {\n 200: {\n description: 'Success',\n },\n },\n }),\n rootHandler,\n );\n }\n\n // Validate EE license before starting (checks RBAC config vs license)\n await honoServerAdapter.validateEELicense();\n\n // Register auth middleware (authentication and authorization)\n // This is handled by the server adapter now\n honoServerAdapter.registerAuthMiddleware();\n\n if (server?.middleware) {\n const normalizedMiddlewares = Array.isArray(server.middleware) ? server.middleware : [server.middleware];\n const middlewares = normalizedMiddlewares.map(middleware => {\n if (typeof middleware === 'function') {\n return {\n path: '*',\n handler: middleware,\n };\n }\n\n return middleware;\n });\n\n for (const middleware of middlewares) {\n // Wrap with skipIfFrameworkPublic so user middleware cannot 401 routes\n // the framework declared public via `requiresAuth: false`\n // (e.g. Studio sign-in endpoints like /api/auth/capabilities).\n app.use(middleware.path, skipIfFrameworkPublic(middleware.handler as unknown as HonoMiddlewareHandler));\n }\n }\n\n // Register custom API routes via the adapter (auth + middleware handled uniformly)\n await honoServerAdapter.registerCustomApiRoutes();\n\n if (server?.build?.apiReqLogs) {\n app.use(logger());\n }\n\n // Register adapter routes (adapter was created earlier with configuration)\n // Cast needed due to Hono type variance - safe because registerRoutes is generic\n await honoServerAdapter.registerRoutes();\n\n if (options?.isDev || server?.build?.swaggerUI) {\n // Warn if Swagger UI is enabled but OpenAPI docs are not in production\n if (!options?.isDev && server?.build?.swaggerUI && !server?.build?.openAPIDocs) {\n const logger = mastra.getLogger();\n logger.warn(\n 'Swagger UI is enabled but OpenAPI documentation is disabled. ' +\n 'The Swagger UI will not function properly without the OpenAPI endpoint. ' +\n 'Please enable openAPIDocs in your server.build configuration:\\n' +\n ' server: { build: { swaggerUI: true, openAPIDocs: true } }',\n );\n }\n\n app.get(\n '/swagger-ui',\n describeRoute({\n hide: true,\n }),\n swaggerUI({ url: `${apiPrefix}/openapi.json` }),\n );\n }\n\n if (options?.isDev) {\n app.post(\n '/__restart-active-workflow-runs',\n describeRoute({\n hide: true,\n }),\n restartAllActiveWorkflowRunsHandler,\n );\n }\n\n const serverOptions = mastra.getServer();\n const studioBasePath = normalizeStudioBase(serverOptions?.studioBase ?? '/');\n\n if (options?.studio) {\n // SSE endpoint for refresh notifications\n app.get(\n `${studioBasePath}/refresh-events`,\n describeRoute({\n hide: true,\n }),\n handleClientsRefresh,\n );\n\n // Trigger refresh for all clients\n app.post(\n `${studioBasePath}/__refresh`,\n describeRoute({\n hide: true,\n }),\n handleTriggerClientsRefresh,\n );\n\n // Check hot reload status\n app.get(\n `${studioBasePath}/__hot-reload-status`,\n describeRoute({\n hide: true,\n }),\n (c: Context) => {\n return c.json({\n disabled: isHotReloadDisabled(),\n timestamp: new Date().toISOString(),\n });\n },\n );\n\n // Enable gzip/deflate compression for studio static assets only\n app.use(`${studioBasePath}/assets/*`, compress());\n\n // Studio routes - these should come after API routes\n // Serve static assets from studio directory\n // Note: Vite builds with base: './' so all asset URLs are relative\n // The <base href> tag in index.html handles path resolution for the SPA\n const studioPath = getStudioPath();\n app.use(\n `${studioBasePath}/assets/*`,\n serveStatic({\n root: join(studioPath, 'assets'),\n rewriteRequestPath: path => {\n // Remove the basePath AND /assets prefix to get the actual file path\n // Example: /custom-path/assets/style.css -> /style.css -> ./studio/assets/style.css\n let rewritten = path;\n if (studioBasePath && rewritten.startsWith(studioBasePath)) {\n rewritten = rewritten.slice(studioBasePath.length);\n }\n // Remove the /assets prefix since root is already './studio/assets'\n if (rewritten.startsWith('/assets')) {\n rewritten = rewritten.slice('/assets'.length);\n }\n return rewritten;\n },\n }),\n );\n }\n\n // Dynamic HTML handler - this must come before static file serving\n app.get('*', async (c, next) => {\n const requestPath = c.req.path;\n\n // Skip if it's an API route\n if (\n requestPath === apiPrefix ||\n requestPath.startsWith(`${apiPrefix}/`) ||\n requestPath.startsWith('/swagger-ui') ||\n requestPath.startsWith('/openapi.json')\n ) {\n return await next();\n }\n\n // Skip if it's an asset file (has extension other than .html)\n if (requestPath.includes('.') && !requestPath.endsWith('.html')) {\n return await next();\n }\n\n // Only serve studio for routes matching the configured base path\n const isStudioRoute =\n studioBasePath === '' || requestPath === studioBasePath || requestPath.startsWith(`${studioBasePath}/`);\n if (options?.studio && isStudioRoute) {\n // For HTML routes, serve index.html with dynamic replacements\n const studioPath = getStudioPath();\n let indexHtml = await readFile(join(studioPath, 'index.html'), 'utf-8');\n\n // Inject the server configuration into index.html placeholders\n const port = serverOptions?.port ?? (Number(process.env.PORT) || 4111);\n const hideCloudCta = process.env.MASTRA_HIDE_CLOUD_CTA === 'true';\n const bindHost = serverOptions?.host ?? process.env.MASTRA_HOST;\n const host = bindHost ?? 'localhost';\n const key =\n serverOptions?.https?.key ??\n (process.env.MASTRA_HTTPS_KEY ? Buffer.from(process.env.MASTRA_HTTPS_KEY, 'base64') : undefined);\n const cert =\n serverOptions?.https?.cert ??\n (process.env.MASTRA_HTTPS_CERT ? Buffer.from(process.env.MASTRA_HTTPS_CERT, 'base64') : undefined);\n const protocol = key && cert ? 'https' : 'http';\n // Studio host/protocol/port for Studio URL injection — allows bind address\n // (e.g. 0.0.0.0) to differ from the domain browsers should connect to\n const studioHost = serverOptions?.studioHost ?? host;\n const studioProtocol = serverOptions?.studioProtocol ?? protocol;\n const studioPort = serverOptions?.studioPort ?? port;\n\n const cloudApiEndpoint = process.env.MASTRA_CLOUD_API_ENDPOINT || '';\n const experimentalFeatures = process.env.EXPERIMENTAL_FEATURES === 'true' ? 'true' : 'false';\n const experimentalUI = process.env.MASTRA_EXPERIMENTAL_UI === 'true' ? 'true' : 'false';\n const templatesEnabled = process.env.MASTRA_TEMPLATES === 'true' ? 'true' : 'false';\n const agentSignals = process.env.MASTRA_AGENT_SIGNALS === 'false' ? 'false' : 'true';\n const signalsUI = process.env.MASTRA_SIGNALS_UI === 'true' ? 'true' : 'false';\n const organizationId = process.env.MASTRA_ORGANIZATION_ID || '';\n const platformProjectId = process.env.MASTRA_PLATFORM_PROJECT_ID || '';\n const platformObservabilityEndpoint = process.env.MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT || '';\n const requestContextPresets = process.env.MASTRA_REQUEST_CONTEXT_PRESETS || '';\n\n const autoDetectUrl = process.env.MASTRA_AUTO_DETECT_URL === 'true';\n\n indexHtml = injectStudioHtmlConfig(indexHtml, {\n host: `'${studioHost}'`,\n port: `'${studioPort}'`,\n protocol: `'${studioProtocol}'`,\n apiPrefix: `'${serverOptions?.apiPrefix ?? '/api'}'`,\n basePath: studioBasePath,\n hideCloudCta: `'${hideCloudCta}'`,\n cloudApiEndpoint: `'${escapeStudioHtmlValue(cloudApiEndpoint)}'`,\n experimentalFeatures: `'${experimentalFeatures}'`,\n templates: `'${templatesEnabled}'`,\n telemetryDisabled: `'${escapeStudioHtmlValue(process.env.MASTRA_TELEMETRY_DISABLED ?? '')}'`,\n requestContextPresets: `'${escapeStudioHtmlValue(requestContextPresets)}'`,\n experimentalUI: `'${experimentalUI}'`,\n agentSignals: `'${agentSignals}'`,\n signalsUI: `'${signalsUI}'`,\n organizationId: `'${escapeStudioHtmlValue(organizationId)}'`,\n platformProjectId: `'${escapeStudioHtmlValue(platformProjectId)}'`,\n platformObservabilityEndpoint: `'${escapeStudioHtmlValue(platformObservabilityEndpoint)}'`,\n autoDetectUrl: `'${autoDetectUrl}'`,\n });\n\n return c.newResponse(indexHtml, 200, { 'Content-Type': 'text/html' });\n }\n\n return c.newResponse(welcomeHtml(apiPrefix), 200, { 'Content-Type': 'text/html' });\n });\n\n if (options?.studio) {\n // Serve extra static files from studio directory (this comes after HTML handler)\n const studioRootPath = getStudioPath();\n const studioPath = studioBasePath ? `${studioBasePath}/*` : '*';\n app.use(\n studioPath,\n serveStatic({\n root: studioRootPath,\n rewriteRequestPath: path => {\n // Remove the basePath prefix if present\n if (studioBasePath && path.startsWith(studioBasePath)) {\n return path.slice(studioBasePath.length);\n }\n return path;\n },\n }),\n );\n }\n\n // Attach injectWebSocket to app for backwards compatibility\n // Consumers can use app directly, and optionally call app.injectWebSocket(server) for browser streaming\n (app as any).injectWebSocket = browserStreamSetup?.injectWebSocket;\n\n return app;\n}\n\nexport async function createNodeServer(mastra: Mastra, options: ServerBundleOptions = { tools: {} }) {\n const app = await createHonoServer(mastra, options);\n const injectWebSocket = (app as any).injectWebSocket;\n const serverOptions = mastra.getServer();\n const apiPrefix = serverOptions?.apiPrefix ?? '/api';\n\n const key =\n serverOptions?.https?.key ??\n (process.env.MASTRA_HTTPS_KEY ? Buffer.from(process.env.MASTRA_HTTPS_KEY, 'base64') : undefined);\n const cert =\n serverOptions?.https?.cert ??\n (process.env.MASTRA_HTTPS_CERT ? Buffer.from(process.env.MASTRA_HTTPS_CERT, 'base64') : undefined);\n const isHttpsEnabled = Boolean(key && cert);\n\n const bindHost = serverOptions?.host ?? process.env.MASTRA_HOST;\n const host = bindHost ?? 'localhost';\n const port = serverOptions?.port ?? (Number(process.env.PORT) || 4111);\n const protocol = isHttpsEnabled ? 'https' : 'http';\n const studioHost = serverOptions?.studioHost ?? host;\n const studioProtocol = serverOptions?.studioProtocol ?? protocol;\n const studioPort = serverOptions?.studioPort ?? port;\n\n const server = serve(\n {\n fetch: app.fetch,\n port,\n hostname: bindHost,\n ...(isHttpsEnabled\n ? {\n createServer: https.createServer,\n serverOptions: {\n key,\n cert,\n },\n }\n : {}),\n },\n () => {\n const logger = mastra.getLogger();\n logger.info('Mastra API running', { url: `${protocol}://${host}:${port}${apiPrefix}` });\n if (options?.studio) {\n const studioBasePath = normalizeStudioBase(serverOptions?.studioBase ?? '/');\n const studioUrl = `${studioProtocol}://${studioHost}:${studioPort}${studioBasePath}`;\n logger.info('Studio available', { url: studioUrl });\n }\n\n if (process.send) {\n process.send({\n type: 'server-ready',\n port,\n host,\n });\n }\n },\n );\n\n // Enable WebSocket support for browser streaming (if available)\n // MUST be called after serve() returns per @hono/node-ws requirements\n injectWebSocket?.(server);\n\n // Backwards compatibility for projects running a newer deployer/CLI with an older @mastra/core.\n // TODO(v2): call `mastra.startWorkers()` unconditionally once old core versions are unsupported.\n const workerLifecycle = mastra as unknown as {\n startWorkers?: () => Promise<void>;\n startEventEngine: () => Promise<void>;\n };\n if (typeof workerLifecycle.startWorkers === 'function') {\n await workerLifecycle.startWorkers();\n } else {\n await workerLifecycle.startEventEngine();\n }\n\n // Fire-and-forget anonymous token usage telemetry (respects MASTRA_TELEMETRY_DISABLED).\n // Dynamic import keeps compatibility with older @mastra/core versions without the\n // `@mastra/core/telemetry` entry point.\n void import('@mastra/core/telemetry').then(({ syncUsageTelemetry }) => syncUsageTelemetry(mastra)).catch(() => {});\n void import('@mastra/core/telemetry')\n .then(({ syncFeatureUsageTelemetry }) => syncFeatureUsageTelemetry(mastra))\n .catch(() => {});\n\n // Graceful shutdown so storage backends release resources (e.g. DuckDB's\n // native file lock) before the process exits. On `mastra dev` hot reloads\n // the old process is sent SIGINT; without this the lock can linger and the\n // restarted process fails with \"Conflicting lock is held\".\n const SHUTDOWN_TIMEOUT_MS = 5000;\n let shuttingDown = false;\n const shutdown = async (signal: NodeJS.Signals) => {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n const logger = mastra.getLogger();\n logger.info('Shutting down Mastra server', { signal });\n server.close();\n // Feature-detect for older @mastra/core versions without shutdown().\n const lifecycle = mastra as unknown as { shutdown?: () => Promise<void> };\n if (typeof lifecycle.shutdown === 'function') {\n // Bound the wait so a hanging shutdown can't block process exit.\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timedOut = Symbol('shutdown-timeout');\n const timeoutPromise = new Promise<typeof timedOut>(resolve => {\n timeout = setTimeout(() => resolve(timedOut), SHUTDOWN_TIMEOUT_MS);\n });\n try {\n const result = await Promise.race([lifecycle.shutdown(), timeoutPromise]);\n if (result === timedOut) {\n logger.warn('Mastra shutdown timed out; forcing exit', { timeoutMs: SHUTDOWN_TIMEOUT_MS });\n }\n } catch (error) {\n logger.error('Error during Mastra shutdown', { error });\n } finally {\n clearTimeout(timeout);\n }\n }\n process.exit(0);\n };\n process.once('SIGINT', () => void shutdown('SIGINT'));\n process.once('SIGTERM', () => void shutdown('SIGTERM'));\n\n return server;\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,14],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACOA,IAAI,eAAe,cAAc,MAAM;CACtC,YAAY,SAAS,SAAS;EAC7B,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACb;AACD;AAIA,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,YAAY,QAAQ,MAAM,gBAAgB;CAC/C,MAAM,MAAM,GAAG,OAAO,KAAK,OAAO;CAClC,IAAI,CAAC,YAAY,KAAK,IAAI,GAAG;EAC5B,MAAM,SAAS,IAAI,IAAI,GAAG;EAC1B,IAAI,OAAO,SAAS,WAAW,KAAK,UAAU,OAAO,cAAc,KAAK,SAAS,GAAG,IAAI,KAAK,QAAQ,SAAS,EAAE,IAAI,KAAA,CAAM,YAAY,GAAG,MAAM,IAAI,aAAa,qBAAqB;EACrL,OAAO,OAAO;CACf,OAAO,IAAI,YAAY,WAAW,GAAG,OAAO,MAAM;MAC7C;EACJ,IAAI,YAAY,WAAW,CAAC,MAAM,IAAI,MAAM,IAAI,aAAa,aAAa;EAC1E,IAAI,CAAC,kBAAkB,KAAK,WAAW,KAAK,aAAa,KAAK,WAAW,GA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AAY,yBAAyB,CAAC,MAAM,EAAE,yBAAyB,mBAAmB,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;CACjH,OAAY,yBAAyB,CAClC,MAAM,EAAE,gCAAgC,0BAA0B,MAAM,CAAC,CAAC,CAC1E,YAAY,CAAC,CAAC;CAMjB,MAAM,sBAAsB;CAC5B,IAAI,eAAe;CACnB,MAAM,WAAW,OAAO,WAA2B;EACjD,IAAI,cACF;EAEF,eAAe;EACf,MAAM,SAAS,OAAO,UAAU;EAChC,OAAO,KAAK,+BAA+B,EAAE,OAAO,CAAC;EACrD,OAAO,MAAM;EAEb,MAAM,YAAY;EAClB,IAAI,OAAO,UAAU,aAAa,YAAY;GAE5C,IAAI;GACJ,MAAM,WAAW,OAAO,kBAAkB;GAC1C,MAAM,iBAAiB,IAAI,SAAyB,YAAW;IAC7D,UAAU,iBAAiB,QAAQ,QAAQ,GAAG,mBAAmB;GACnE,CAAC;GACD,IAAI;IAEF,IAAI,MADiB,QAAQ,KAAK,CAAC,UAAU,SAAS,GAAG,cAAc,CAAC,MACzD,UACb,OAAO,KAAK,2CAA2C,EAAE,WAAW,oBAAoB,CAAC;GAE7F,SAAS,OAAO;IACd,OAAO,MAAM,gCAAgC,EAAE,MAAM,CAAC;GACxD,UAAU;IACR,aAAa,OAAO;GACtB;EACF;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,KAAK,gBAAgB,KAAK,SAAS,QAAQ,CAAC;CACpD,QAAQ,KAAK,iBAAiB,KAAK,SAAS,SAAS,CAAC;CAEtD,OAAO;AACT"}
1
+ {"version":3,"file":"index.cjs","names":["Http2ServerRequest","Readable","#body","#init","stream","constants","#eventInitDict","STATUS_CODES","createServer","versions","Readable","stream","path","Readable","onError","headerCharRegex","checkInvalidHeaderChar","Writable","checkInvalidHeaderChar","Buffer","RE_TE_CHUNKED","Buffer","ViewerRegistry","MASTRA_FRAMEWORK_PUBLIC_KEY$1","MastraServer$1","process","HTTPException","Tool","Hono","InMemoryTaskStore","swaggerUI","normalizeStudioBase","path","injectStudioHtmlConfig","escapeStudioHtmlValue"],"sources":["../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/index.mjs","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/utils/stream.mjs","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/serve-static.mjs","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/swagger-ui/0.5.3/e2a67d786252daef9d3d1d955111365f4d3b8b4c3d7bbe3cd9046cc5c088d984/node_modules/@hono/swagger-ui/dist/index.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/utils/errors.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/http-incoming.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/utils/types.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/internal-http.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/internal-streams-state.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/http-common.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/http-outgoing.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fetch-to-node/2.1.0/75a085586b95f3a18a440f8655a7cb5c851846ab2c5e6ad2c4ae036e3bbaa05c/node_modules/fetch-to-node/dist/fetch-to-node/http-server.js","../../../../server-adapters/hono/dist/index.js","../../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/hono-openapi/1.3.1/053f98053f08198fa5b6e0d29547d4cd5182ae4dbab8de92581c6160e3026d7d/node_modules/hono-openapi/dist/index.js","../../src/server/handlers/agent-learning.ts","../../src/server/handlers/client.ts","../../src/server/handlers/error.ts","../../src/server/handlers/health.ts","../../src/server/handlers/restart-active-runs.ts","../../src/server/handlers/root.ts","../../src/server/welcome.ts","../../src/server/index.ts"],"sourcesContent":["//#region src/utils/response/constants.ts\nconst X_ALREADY_SENT = \"x-hono-already-sent\";\n\n//#endregion\nexport { X_ALREADY_SENT as t };","import { t as X_ALREADY_SENT } from \"./constants-BLSFu_RU.mjs\";\nimport { STATUS_CODES, createServer } from \"node:http\";\nimport { Http2ServerRequest, constants } from \"node:http2\";\nimport { Readable } from \"node:stream\";\nimport { defineWebSocketHelper } from \"hono/ws\";\n\n//#region src/error.ts\nvar RequestError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.name = \"RequestError\";\n\t}\n};\n\n//#endregion\n//#region src/url.ts\nconst reValidRequestUrl = /^\\/[!#$&-;=?-\\[\\]_a-z~]*$/;\nconst reDotSegment = /\\/\\.\\.?(?:[/?#]|$)/;\nconst reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\\d{3,4}|[6-9]\\d{3}))?$/;\nconst buildUrl = (scheme, host, incomingUrl) => {\n\tconst url = `${scheme}://${host}${incomingUrl}`;\n\tif (!reValidHost.test(host)) {\n\t\tconst urlObj = new URL(url);\n\t\tif (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(\":\") ? host.replace(/:\\d+$/, \"\") : host).toLowerCase()) throw new RequestError(\"Invalid host header\");\n\t\treturn urlObj.href;\n\t} else if (incomingUrl.length === 0) return url + \"/\";\n\telse {\n\t\tif (incomingUrl.charCodeAt(0) !== 47) throw new RequestError(\"Invalid URL\");\n\t\tif (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;\n\t\treturn url;\n\t}\n};\n\n//#endregion\n//#region src/request.ts\nconst toRequestError = (e) => {\n\tif (e instanceof RequestError) return e;\n\treturn new RequestError(e.message, { cause: e });\n};\nconst GlobalRequest = global.Request;\nvar Request$1 = class extends GlobalRequest {\n\tconstructor(input, options) {\n\t\tif (typeof input === \"object\" && getRequestCache in input) {\n\t\t\tconst hasReplacementBody = options !== void 0 && \"body\" in options && options.body != null;\n\t\t\tif (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError(\"Cannot construct a Request with a Request object that has already been used.\");\n\t\t\tinput = input[getRequestCache]();\n\t\t}\n\t\tif (typeof (options?.body)?.getReader !== \"undefined\") options.duplex ??= \"half\";\n\t\tsuper(input, options);\n\t}\n};\nconst newHeadersFromIncoming = (incoming) => {\n\tconst headerRecord = [];\n\tconst rawHeaders = incoming.rawHeaders;\n\tfor (let i = 0, len = rawHeaders.length; i < len; i += 2) {\n\t\tconst key = rawHeaders[i];\n\t\tif (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);\n\t}\n\treturn new Headers(headerRecord);\n};\nconst wrapBodyStream = Symbol(\"wrapBodyStream\");\nconst byteExactEncodings = new Set([\n\t\"latin1\",\n\t\"binary\",\n\t\"hex\",\n\t\"base64\",\n\t\"base64url\"\n]);\nconst isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);\nconst bodyBufferedBeforeDisconnectKey = Symbol(\"bodyBufferedBeforeDisconnect\");\nconst bodyBufferedLengthBeforeDisconnectKey = Symbol(\"bodyBufferedLengthBeforeDisconnect\");\nconst toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? \"utf8\");\nconst isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === \"function\" && isByteExactEncoding(incoming.readableEncoding);\nconst recordBodyBufferedBeforeDisconnect = (incoming) => {\n\tif (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;\n\tconst incomingWithRecovery = incoming;\n\tincomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;\n};\nconst readBodyBufferedBeforeDisconnect = (incoming, chunks) => {\n\tif (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;\n\tconst incomingWithRecovery = incoming;\n\tif (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];\n\tlet result;\n\tconst errored = incoming.errored;\n\tif (errored && errored.code !== \"ECONNRESET\") result = errored;\n\telse if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();\n\telse {\n\t\tconst bodyChunks = chunks ?? [];\n\t\tconst chunk = incoming.read();\n\t\tif (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));\n\t\tconst buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);\n\t\tresult = buffer;\n\t\tconst contentLength = incoming.headers[\"content-length\"];\n\t\tif (typeof contentLength === \"string\" && /^\\d+$/.test(contentLength)) {\n\t\t\tconst expectedLength = Number(contentLength);\n\t\t\tif (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();\n\t\t}\n\t}\n\tincomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;\n\treturn result;\n};\nconst enqueueBufferedBody = (controller, buffered) => {\n\tif (buffered instanceof Error) {\n\t\tcontroller.error(buffered);\n\t\treturn;\n\t}\n\tif (buffered.length > 0) controller.enqueue(buffered);\n\tcontroller.close();\n};\nconst newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n\tconst init = {\n\t\tmethod,\n\t\theaders,\n\t\tsignal: abortController.signal\n\t};\n\tif (method === \"TRACE\") {\n\t\tinit.method = \"GET\";\n\t\tconst req = new Request$1(url, init);\n\t\tObject.defineProperty(req, \"method\", { get() {\n\t\t\treturn \"TRACE\";\n\t\t} });\n\t\treturn req;\n\t}\n\tif (!(method === \"GET\" || method === \"HEAD\")) if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {\n\t\tcontroller.enqueue(incoming.rawBody);\n\t\tcontroller.close();\n\t} });\n\telse if (incoming[wrapBodyStream]) {\n\t\tlet reader;\n\t\tinit.body = new ReadableStream({ async pull(controller) {\n\t\t\ttry {\n\t\t\t\tif (!reader) {\n\t\t\t\t\tconst buffered = readBodyBufferedBeforeDisconnect(incoming);\n\t\t\t\t\tif (buffered !== void 0) {\n\t\t\t\t\t\tenqueueBufferedBody(controller, buffered);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treader ||= Readable.toWeb(incoming).getReader();\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t}\n\t\t} });\n\t} else {\n\t\tconst buffered = readBodyBufferedBeforeDisconnect(incoming);\n\t\tif (buffered !== void 0) init.body = new ReadableStream({ start(controller) {\n\t\t\tenqueueBufferedBody(controller, buffered);\n\t\t} });\n\t\telse init.body = Readable.toWeb(incoming);\n\t}\n\treturn new Request$1(url, init);\n};\nconst getRequestCache = Symbol(\"getRequestCache\");\nconst requestCache = Symbol(\"requestCache\");\nconst incomingKey = Symbol(\"incomingKey\");\nconst urlKey = Symbol(\"urlKey\");\nconst methodKey = Symbol(\"methodKey\");\nconst headersKey = Symbol(\"headersKey\");\nconst abortControllerKey = Symbol(\"abortControllerKey\");\nconst getAbortController = Symbol(\"getAbortController\");\nconst abortRequest = Symbol(\"abortRequest\");\nconst bodyBufferKey = Symbol(\"bodyBuffer\");\nconst bodyReadPromiseKey = Symbol(\"bodyReadPromise\");\nconst bodyConsumedDirectlyKey = Symbol(\"bodyConsumedDirectly\");\nconst bodyLockReaderKey = Symbol(\"bodyLockReader\");\nconst abortReasonKey = Symbol(\"abortReason\");\nconst newBodyUnusableError = () => {\n\treturn /* @__PURE__ */ new TypeError(\"Body is unusable\");\n};\nconst rejectBodyUnusable = () => {\n\treturn Promise.reject(newBodyUnusableError());\n};\nconst textDecoder = new TextDecoder();\nconst consumeBodyDirectOnce = (request) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\trequest[bodyConsumedDirectlyKey] = true;\n};\nconst toArrayBuffer = (buf) => {\n\treturn buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n};\nconst contentType = (request) => {\n\treturn (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get(\"content-type\") || \"\";\n};\nconst methodTokenRegExp = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst normalizeIncomingMethod = (method) => {\n\tif (typeof method !== \"string\" || method.length === 0) return \"GET\";\n\tswitch (method) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\": return method;\n\t}\n\tconst upper = method.toUpperCase();\n\tswitch (upper) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\": return upper;\n\t\tdefault: return method;\n\t}\n};\nconst validateDirectReadMethod = (method) => {\n\tif (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);\n\tconst normalized = method.toUpperCase();\n\tif (normalized === \"CONNECT\" || normalized === \"TRACK\" || normalized === \"TRACE\" && method !== \"TRACE\") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);\n};\nconst readBodyWithFastPath = (request, method, fromBuffer) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\tconst methodName = request.method;\n\tif (methodName === \"GET\" || methodName === \"HEAD\") return request[getRequestCache]()[method]();\n\tconst methodValidationError = validateDirectReadMethod(methodName);\n\tif (methodValidationError) return Promise.reject(methodValidationError);\n\tif (request[requestCache]) {\n\t\tif (methodName !== \"TRACE\") return request[requestCache][method]();\n\t}\n\tconst alreadyUsedError = consumeBodyDirectOnce(request);\n\tif (alreadyUsedError) return alreadyUsedError;\n\tconst raw = readRawBodyIfAvailable(request);\n\tif (raw) {\n\t\tconst result = Promise.resolve(fromBuffer(raw, request));\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t}\n\treturn readBodyDirect(request).then((buf) => {\n\t\tconst result = fromBuffer(buf, request);\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t});\n};\nconst readRawBodyIfAvailable = (request) => {\n\tconst incoming = request[incomingKey];\n\tif (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;\n};\nconst normalizeAbortError = (request, incoming) => {\n\tif (incoming.errored) return incoming.errored;\n\tconst reason = request[abortReasonKey];\n\tif (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));\n\treturn /* @__PURE__ */ new Error(\"Client connection prematurely closed.\");\n};\nconst readBodyDirect = (request) => {\n\tif (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);\n\tif (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];\n\tconst incoming = request[incomingKey];\n\tif (incoming.readableDidRead) return rejectBodyUnusable();\n\tconst buffered = readBodyBufferedBeforeDisconnect(incoming);\n\tif (buffered !== void 0) {\n\t\tif (buffered instanceof Error) return Promise.reject(buffered);\n\t\trequest[bodyBufferKey] = buffered;\n\t\treturn Promise.resolve(buffered);\n\t}\n\tconst promise = new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\tlet settled = false;\n\t\tconst finish = (callback) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tcallback();\n\t\t};\n\t\tconst recoverCompleteBodyAfterDisconnect = (error) => {\n\t\t\tconst streamError = incoming.errored ?? error;\n\t\t\tif (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== \"ECONNRESET\") return false;\n\t\t\tfinish(() => {\n\t\t\t\tconst recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);\n\t\t\t\tif (recovered instanceof Error) reject(recovered);\n\t\t\t\telse if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));\n\t\t\t\telse {\n\t\t\t\t\trequest[bodyBufferKey] = recovered;\n\t\t\t\t\tresolve(recovered);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn true;\n\t\t};\n\t\tconst onData = (chunk) => {\n\t\t\tchunks.push(toBufferChunk(chunk, incoming.readableEncoding));\n\t\t};\n\t\tconst onEnd = () => {\n\t\t\tfinish(() => {\n\t\t\t\tconst buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);\n\t\t\t\trequest[bodyBufferKey] = buffer;\n\t\t\t\tresolve(buffer);\n\t\t\t});\n\t\t};\n\t\tconst onError = (error) => {\n\t\t\tif (recoverCompleteBodyAfterDisconnect(error)) return;\n\t\t\tfinish(() => {\n\t\t\t\treject(error);\n\t\t\t});\n\t\t};\n\t\tconst onClose = () => {\n\t\t\tif (incoming.readableEnded) {\n\t\t\t\tonEnd();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (recoverCompleteBodyAfterDisconnect()) return;\n\t\t\tfinish(() => {\n\t\t\t\treject(normalizeAbortError(request, incoming));\n\t\t\t});\n\t\t};\n\t\tconst cleanup = () => {\n\t\t\tincoming.off(\"data\", onData);\n\t\t\tincoming.off(\"end\", onEnd);\n\t\t\tincoming.off(\"error\", onError);\n\t\t\tincoming.off(\"close\", onClose);\n\t\t\trequest[bodyReadPromiseKey] = void 0;\n\t\t};\n\t\tincoming.on(\"data\", onData);\n\t\tincoming.on(\"end\", onEnd);\n\t\tincoming.on(\"error\", onError);\n\t\tincoming.on(\"close\", onClose);\n\t\tqueueMicrotask(() => {\n\t\t\tif (settled) return;\n\t\t\tif (incoming.readableEnded) onEnd();\n\t\t\telse if (incoming.errored) onError(incoming.errored);\n\t\t\telse if (incoming.destroyed) onClose();\n\t\t});\n\t});\n\trequest[bodyReadPromiseKey] = promise;\n\treturn promise;\n};\nconst requestPrototype = {\n\tget method() {\n\t\treturn this[methodKey];\n\t},\n\tget url() {\n\t\treturn this[urlKey];\n\t},\n\tget headers() {\n\t\treturn this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n\t},\n\t[abortRequest](reason) {\n\t\tif (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;\n\t\tconst abortController = this[abortControllerKey];\n\t\tif (abortController && !abortController.signal.aborted) abortController.abort(reason);\n\t},\n\t[getAbortController]() {\n\t\tthis[abortControllerKey] ||= new AbortController();\n\t\tif (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);\n\t\treturn this[abortControllerKey];\n\t},\n\t[getRequestCache]() {\n\t\tconst abortController = this[getAbortController]();\n\t\tif (this[requestCache]) return this[requestCache];\n\t\tconst method = this.method;\n\t\tif (this[bodyConsumedDirectlyKey] && !(method === \"GET\" || method === \"HEAD\")) {\n\t\t\tthis[bodyBufferKey] = void 0;\n\t\t\tconst init = {\n\t\t\t\tmethod: method === \"TRACE\" ? \"GET\" : method,\n\t\t\t\theaders: this.headers,\n\t\t\t\tsignal: abortController.signal\n\t\t\t};\n\t\t\tif (method !== \"TRACE\") {\n\t\t\t\tinit.body = new ReadableStream({ start(c) {\n\t\t\t\t\tc.close();\n\t\t\t\t} });\n\t\t\t\tinit.duplex = \"half\";\n\t\t\t}\n\t\t\tconst req = new Request$1(this[urlKey], init);\n\t\t\tif (method === \"TRACE\") Object.defineProperty(req, \"method\", { get() {\n\t\t\t\treturn \"TRACE\";\n\t\t\t} });\n\t\t\treturn this[requestCache] = req;\n\t\t}\n\t\treturn this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);\n\t},\n\tget body() {\n\t\tif (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;\n\t\tconst request = this[getRequestCache]();\n\t\tif (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();\n\t\treturn request.body;\n\t},\n\tget bodyUsed() {\n\t\tif (this[bodyConsumedDirectlyKey]) return true;\n\t\tif (this[requestCache]) return this[requestCache].bodyUsed;\n\t\treturn false;\n\t}\n};\nObject.defineProperty(requestPrototype, \"signal\", { get() {\n\treturn this[getAbortController]().signal;\n} });\n[\n\t\"cache\",\n\t\"credentials\",\n\t\"destination\",\n\t\"integrity\",\n\t\"mode\",\n\t\"redirect\",\n\t\"referrer\",\n\t\"referrerPolicy\",\n\t\"keepalive\"\n].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { get() {\n\t\treturn this[getRequestCache]()[k];\n\t} });\n});\n[\"clone\", \"formData\"].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { value: function() {\n\t\tif (this[bodyConsumedDirectlyKey]) {\n\t\t\tif (k === \"clone\") throw newBodyUnusableError();\n\t\t\treturn rejectBodyUnusable();\n\t\t}\n\t\treturn this[getRequestCache]()[k]();\n\t} });\n});\nObject.defineProperty(requestPrototype, \"text\", { value: function() {\n\treturn readBodyWithFastPath(this, \"text\", (buf) => textDecoder.decode(buf));\n} });\nObject.defineProperty(requestPrototype, \"arrayBuffer\", { value: function() {\n\treturn readBodyWithFastPath(this, \"arrayBuffer\", (buf) => toArrayBuffer(buf));\n} });\nObject.defineProperty(requestPrototype, \"blob\", { value: function() {\n\treturn readBodyWithFastPath(this, \"blob\", (buf, request) => {\n\t\tconst type = contentType(request);\n\t\tconst init = type ? { headers: { \"content-type\": type } } : void 0;\n\t\treturn new Response(buf, init).blob();\n\t});\n} });\nObject.defineProperty(requestPrototype, \"json\", { value: function() {\n\tif (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\treturn this.text().then(JSON.parse);\n} });\nObject.defineProperty(requestPrototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Request (lightweight) ${inspectFn({\n\t\tmethod: this.method,\n\t\turl: this.url,\n\t\theaders: this.headers,\n\t\tnativeRequest: this[requestCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(requestPrototype, Request$1.prototype);\nconst newRequest = (incoming, defaultHostname) => {\n\tconst req = Object.create(requestPrototype);\n\treq[incomingKey] = incoming;\n\treq[methodKey] = normalizeIncomingMethod(incoming.method);\n\tconst incomingUrl = incoming.url || \"\";\n\tif (incomingUrl[0] !== \"/\" && (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n\t\tif (incoming instanceof Http2ServerRequest) throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n\t\ttry {\n\t\t\treq[urlKey] = new URL(incomingUrl).href;\n\t\t} catch (e) {\n\t\t\tthrow new RequestError(\"Invalid absolute URL\", { cause: e });\n\t\t}\n\t\treturn req;\n\t}\n\tconst host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n\tif (!host) throw new RequestError(\"Missing host header\");\n\tlet scheme;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\tscheme = incoming.scheme;\n\t\tif (!(scheme === \"http\" || scheme === \"https\")) throw new RequestError(\"Unsupported scheme\");\n\t} else scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n\ttry {\n\t\treq[urlKey] = buildUrl(scheme, host, incomingUrl);\n\t} catch (e) {\n\t\tif (e instanceof RequestError) throw e;\n\t\telse throw new RequestError(\"Invalid URL\", { cause: e });\n\t}\n\treturn req;\n};\n\n//#endregion\n//#region src/response.ts\nconst defaultContentType = \"text/plain; charset=UTF-8\";\nconst responseCache = Symbol(\"responseCache\");\nconst getResponseCache = Symbol(\"getResponseCache\");\nconst cacheKey = Symbol(\"cache\");\nconst GlobalResponse = global.Response;\nvar Response$1 = class Response$1 {\n\t#body;\n\t#init;\n\t[getResponseCache]() {\n\t\tconst cache = this[cacheKey];\n\t\tconst liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;\n\t\tdelete this[cacheKey];\n\t\treturn this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {\n\t\t\tstatus: this.#init?.status,\n\t\t\tstatusText: this.#init?.statusText,\n\t\t\theaders: liveHeaders\n\t\t} : this.#init);\n\t}\n\tconstructor(body, init) {\n\t\tlet headers;\n\t\tthis.#body = body;\n\t\tif (init instanceof Response$1) {\n\t\t\tconst cachedGlobalResponse = init[responseCache];\n\t\t\tif (cachedGlobalResponse) {\n\t\t\t\tthis.#init = cachedGlobalResponse;\n\t\t\t\tthis[getResponseCache]();\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tthis.#init = init.#init;\n\t\t\t\theaders = new Headers(init.headers);\n\t\t\t}\n\t\t} else this.#init = init;\n\t\tif (body == null || typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [\n\t\t\tinit?.status || 200,\n\t\t\tbody ?? null,\n\t\t\theaders || init?.headers\n\t\t];\n\t}\n\tget headers() {\n\t\tconst cache = this[cacheKey];\n\t\tif (cache) {\n\t\t\tif (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { \"content-type\": defaultContentType }));\n\t\t\treturn cache[2];\n\t\t}\n\t\treturn this[getResponseCache]().headers;\n\t}\n\tget status() {\n\t\treturn this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n\t}\n\tget ok() {\n\t\tconst status = this.status;\n\t\treturn status >= 200 && status < 300;\n\t}\n};\n[\n\t\"body\",\n\t\"bodyUsed\",\n\t\"redirected\",\n\t\"statusText\",\n\t\"trailers\",\n\t\"type\",\n\t\"url\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { get() {\n\t\treturn this[getResponseCache]()[k];\n\t} });\n});\n[\n\t\"arrayBuffer\",\n\t\"blob\",\n\t\"clone\",\n\t\"formData\",\n\t\"json\",\n\t\"text\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { value: function() {\n\t\treturn this[getResponseCache]()[k]();\n\t} });\n});\nObject.defineProperty(Response$1.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Response (lightweight) ${inspectFn({\n\t\tstatus: this.status,\n\t\theaders: this.headers,\n\t\tok: this.ok,\n\t\tnativeResponse: this[responseCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(Response$1, GlobalResponse);\nObject.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);\nconst validRedirectUrl = /^https?:\\/\\/[!#-;=?-[\\]_a-z~A-Z]+$/;\nconst parseRedirectUrl = (url) => {\n\tif (url instanceof URL) return url.href;\n\tif (validRedirectUrl.test(url)) return url;\n\treturn new URL(url).href;\n};\nconst validRedirectStatuses = new Set([\n\t301,\n\t302,\n\t303,\n\t307,\n\t308\n]);\nObject.defineProperty(Response$1, \"redirect\", {\n\tvalue: function redirect(url, status = 302) {\n\t\tif (!validRedirectStatuses.has(status)) throw new RangeError(\"Invalid status code\");\n\t\treturn new Response$1(null, {\n\t\t\tstatus,\n\t\t\theaders: { location: parseRedirectUrl(url) }\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\nObject.defineProperty(Response$1, \"json\", {\n\tvalue: function json(data, init) {\n\t\tconst body = JSON.stringify(data);\n\t\tif (body === void 0) throw new TypeError(\"The data is not JSON serializable\");\n\t\tconst initHeaders = init?.headers;\n\t\tlet headers;\n\t\tif (initHeaders) {\n\t\t\theaders = new Headers(initHeaders);\n\t\t\tif (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n\t\t} else headers = { \"content-type\": \"application/json\" };\n\t\treturn new Response$1(body, {\n\t\t\tstatus: init?.status ?? 200,\n\t\t\tstatusText: init?.statusText,\n\t\t\theaders\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\n\n//#endregion\n//#region src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n\treturn Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n\tconst cancel = (error) => {\n\t\treader.cancel(error).catch(() => {});\n\t};\n\twritable.on(\"close\", cancel);\n\twritable.on(\"error\", cancel);\n\t(currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n\treturn reader.closed.finally(() => {\n\t\twritable.off(\"close\", cancel);\n\t\twritable.off(\"error\", cancel);\n\t});\n\tfunction handleStreamError(error) {\n\t\tif (error) writable.destroy(error);\n\t}\n\tfunction onDrain() {\n\t\treader.read().then(flow, handleStreamError);\n\t}\n\tfunction flow({ done, value }) {\n\t\ttry {\n\t\t\tif (done) writable.end();\n\t\t\telse if (!writable.write(value)) writable.once(\"drain\", onDrain);\n\t\t\telse return reader.read().then(flow, handleStreamError);\n\t\t} catch (e) {\n\t\t\thandleStreamError(e);\n\t\t}\n\t}\n}\nfunction writeFromReadableStream(stream, writable) {\n\tif (stream.locked) throw new TypeError(\"ReadableStream is locked.\");\n\telse if (writable.destroyed) return;\n\treturn writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nconst buildOutgoingHttpHeaders = (headers, defaultContentType) => {\n\tconst res = {};\n\tif (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);\n\tif (headers.has(\"set-cookie\")) {\n\t\tconst cookies = [];\n\t\tfor (const [k, v] of headers) if (k === \"set-cookie\") cookies.push(v);\n\t\telse res[k] = v;\n\t\tif (cookies.length > 0) res[\"set-cookie\"] = cookies;\n\t} else for (const [k, v] of headers) res[k] = v;\n\tif (defaultContentType) res[\"content-type\"] ??= defaultContentType;\n\treturn res;\n};\n\n//#endregion\n//#region src/listener.ts\nconst outgoingEnded = Symbol(\"outgoingEnded\");\nconst incomingDraining = Symbol(\"incomingDraining\");\nconst DRAIN_TIMEOUT_MS = 500;\nconst MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nconst drainIncoming = (incoming) => {\n\tconst incomingWithDrainState = incoming;\n\tif (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;\n\tincomingWithDrainState[incomingDraining] = true;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\ttry {\n\t\t\tincoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);\n\t\t} catch {}\n\t\treturn;\n\t}\n\tlet bytesRead = 0;\n\tconst cleanup = () => {\n\t\tclearTimeout(timer);\n\t\tincoming.off(\"data\", onData);\n\t\tincoming.off(\"end\", cleanup);\n\t\tincoming.off(\"error\", cleanup);\n\t};\n\tconst forceClose = () => {\n\t\tcleanup();\n\t\tconst socket = incoming.socket;\n\t\tif (socket && !socket.destroyed) socket.destroySoon();\n\t};\n\tconst timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n\ttimer.unref?.();\n\tconst onData = (chunk) => {\n\t\tbytesRead += chunk.length;\n\t\tif (bytesRead > MAX_DRAIN_BYTES) forceClose();\n\t};\n\tincoming.on(\"data\", onData);\n\tincoming.on(\"end\", cleanup);\n\tincoming.on(\"error\", cleanup);\n\tincoming.resume();\n};\nconst makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {\n\tif (incoming.errored) {\n\t\trecordBodyBufferedBeforeDisconnect(incoming);\n\t\treq[abortRequest](incoming.errored.toString());\n\t} else if (!outgoing.writableFinished) {\n\t\trecordBodyBufferedBeforeDisconnect(incoming);\n\t\treq[abortRequest](\"Client connection prematurely closed.\");\n\t}\n\tif (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {\n\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\tdrainIncoming(incoming);\n\t\t});\n\t});\n};\nconst isImmediateCacheableResponse = (res) => {\n\tif (!(cacheKey in res)) return false;\n\tconst body = res[cacheKey][1];\n\treturn body === null || typeof body === \"string\" || body instanceof Uint8Array;\n};\nconst handleRequestError = () => new Response(null, { status: 400 });\nconst handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500 });\nconst handleResponseError = (e, outgoing) => {\n\tconst err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n\tif (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") console.info(\"The user aborted a request.\");\n\telse {\n\t\tconsole.error(e);\n\t\tif (!outgoing.headersSent) outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n\t\toutgoing.end(`Error: ${err.message}`);\n\t\toutgoing.destroy(err);\n\t}\n};\nconst flushHeaders = (outgoing) => {\n\tif (\"flushHeaders\" in outgoing && outgoing.writable) outgoing.flushHeaders();\n};\nconst responseViaCache = async (res, outgoing) => {\n\tlet [status, body, header] = res[cacheKey];\n\tif (!header) {\n\t\tif (body === null) {\n\t\t\toutgoing.writeHead(status);\n\t\t\toutgoing.end();\n\t\t} else if (typeof body === \"string\") {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": Buffer.byteLength(body)\n\t\t\t});\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Uint8Array) {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": body.byteLength\n\t\t\t});\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Blob) {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": body.size\n\t\t\t});\n\t\t\toutgoing.end(new Uint8Array(await body.arrayBuffer()));\n\t\t} else {\n\t\t\toutgoing.writeHead(status, { \"Content-Type\": defaultContentType });\n\t\t\tflushHeaders(outgoing);\n\t\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t\t}\n\t\toutgoing[outgoingEnded]?.();\n\t\treturn;\n\t}\n\tlet hasContentLength = false;\n\tif (header instanceof Headers) {\n\t\thasContentLength = header.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);\n\t} else if (Array.isArray(header)) {\n\t\tconst headerObj = new Headers(header);\n\t\thasContentLength = headerObj.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);\n\t} else for (const key in header) if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n\t\thasContentLength = true;\n\t\tbreak;\n\t}\n\tif (!hasContentLength) {\n\t\tif (typeof body === \"string\") header[\"Content-Length\"] = Buffer.byteLength(body);\n\t\telse if (body instanceof Uint8Array) header[\"Content-Length\"] = body.byteLength;\n\t\telse if (body instanceof Blob) header[\"Content-Length\"] = body.size;\n\t}\n\toutgoing.writeHead(status, header);\n\tif (body == null) outgoing.end();\n\telse if (typeof body === \"string\" || body instanceof Uint8Array) outgoing.end(body);\n\telse if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));\n\telse {\n\t\tflushHeaders(outgoing);\n\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst isPromise = (res) => typeof res.then === \"function\";\nconst responseViaResponseObject = async (res, outgoing, options = {}) => {\n\tif (isPromise(res)) if (options.errorHandler) try {\n\t\tres = await res;\n\t} catch (err) {\n\t\tconst errRes = await options.errorHandler(err);\n\t\tif (!errRes) return;\n\t\tres = errRes;\n\t}\n\telse res = await res.catch(handleFetchError);\n\tif (cacheKey in res) return responseViaCache(res, outgoing);\n\tconst resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);\n\tif (res.body) {\n\t\tconst reader = res.body.getReader();\n\t\tconst values = [];\n\t\tlet done = false;\n\t\tlet currentReadPromise = void 0;\n\t\tif (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n\t\t\tlet maxReadCount = 2;\n\t\t\tfor (let i = 0; i < maxReadCount; i++) {\n\t\t\t\tcurrentReadPromise ||= reader.read();\n\t\t\t\tconst chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t\tdone = true;\n\t\t\t\t});\n\t\t\t\tif (!chunk) {\n\t\t\t\t\tif (i === 1) {\n\t\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve));\n\t\t\t\t\t\tmaxReadCount = 3;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcurrentReadPromise = void 0;\n\t\t\t\tif (chunk.value) values.push(chunk.value);\n\t\t\t\tif (chunk.done) {\n\t\t\t\t\tdone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (done && !(\"content-length\" in resHeaderRecord)) resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n\t\t}\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\tvalues.forEach((value) => {\n\t\t\toutgoing.write(value);\n\t\t});\n\t\tif (done) outgoing.end();\n\t\telse {\n\t\t\tif (values.length === 0) flushHeaders(outgoing);\n\t\t\tawait writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n\t\t}\n\t} else if (resHeaderRecord[X_ALREADY_SENT]) {} else {\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\toutgoing.end();\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst getRequestListener = (fetchCallback, options = {}) => {\n\tconst autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n\tif (options.overrideGlobalObjects !== false && global.Request !== Request$1) {\n\t\tObject.defineProperty(global, \"Request\", { value: Request$1 });\n\t\tObject.defineProperty(global, \"Response\", { value: Response$1 });\n\t}\n\treturn async (incoming, outgoing) => {\n\t\tlet res, req;\n\t\tlet needsBodyCleanup = false;\n\t\tlet closeHandlerAttached = false;\n\t\tconst ensureCloseHandler = () => {\n\t\t\tif (!req || closeHandlerAttached) return;\n\t\t\tcloseHandlerAttached = true;\n\t\t\toutgoing.on(\"close\", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));\n\t\t};\n\t\ttry {\n\t\t\treq = newRequest(incoming, options.hostname);\n\t\t\tneedsBodyCleanup = autoCleanupIncoming && !(incoming.method === \"GET\" || incoming.method === \"HEAD\");\n\t\t\tif (needsBodyCleanup) {\n\t\t\t\tincoming[wrapBodyStream] = true;\n\t\t\t\tif (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {\n\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\t\tincoming.destroy();\n\t\t\t\t\t\t\toutgoing.destroy();\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}\n\t\t\tres = fetchCallback(req, {\n\t\t\t\tincoming,\n\t\t\t\toutgoing\n\t\t\t});\n\t\t\tif (!isPromise(res) && isImmediateCacheableResponse(res)) {\n\t\t\t\tif (needsBodyCleanup && !incoming.readableEnded) outgoing.once(\"finish\", () => {\n\t\t\t\t\tif (!incoming.readableEnded) drainIncoming(incoming);\n\t\t\t\t});\n\t\t\t\treturn responseViaCache(res, outgoing);\n\t\t\t}\n\t\t\tensureCloseHandler();\n\t\t} catch (e) {\n\t\t\tif (!res) if (options.errorHandler) {\n\t\t\t\tensureCloseHandler();\n\t\t\t\tres = await options.errorHandler(req ? e : toRequestError(e));\n\t\t\t\tif (!res) return;\n\t\t\t} else if (!req) res = handleRequestError();\n\t\t\telse res = handleFetchError(e);\n\t\t\telse return handleResponseError(e, outgoing);\n\t\t}\n\t\ttry {\n\t\t\treturn await responseViaResponseObject(res, outgoing, options);\n\t\t} catch (e) {\n\t\t\treturn handleResponseError(e, outgoing);\n\t\t}\n\t};\n};\n\n//#endregion\n//#region src/websocket.ts\n/**\n* @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent\n*/\nconst CloseEvent = globalThis.CloseEvent ?? class extends Event {\n\t#eventInitDict;\n\tconstructor(type, eventInitDict = {}) {\n\t\tsuper(type, eventInitDict);\n\t\tthis.#eventInitDict = eventInitDict;\n\t}\n\tget wasClean() {\n\t\treturn this.#eventInitDict.wasClean ?? false;\n\t}\n\tget code() {\n\t\treturn this.#eventInitDict.code ?? 0;\n\t}\n\tget reason() {\n\t\treturn this.#eventInitDict.reason ?? \"\";\n\t}\n};\n/**\n* Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.\n* @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent\n*/\nconst ErrorEvent = globalThis.ErrorEvent ?? class extends Event {\n\t#eventInitDict;\n\tconstructor(type, eventInitDict = {}) {\n\t\tsuper(type, eventInitDict);\n\t\tthis.#eventInitDict = eventInitDict;\n\t}\n\tget message() {\n\t\treturn this.#eventInitDict.message ?? \"\";\n\t}\n\tget filename() {\n\t\treturn this.#eventInitDict.filename ?? \"\";\n\t}\n\tget lineno() {\n\t\treturn this.#eventInitDict.lineno ?? 0;\n\t}\n\tget colno() {\n\t\treturn this.#eventInitDict.colno ?? 0;\n\t}\n\tget error() {\n\t\treturn this.#eventInitDict.error ?? null;\n\t}\n};\nconst generateConnectionSymbol = () => Symbol(\"connection\");\nconst CONNECTION_SYMBOL_KEY = Symbol(\"CONNECTION_SYMBOL_KEY\");\nconst WAIT_FOR_WEBSOCKET_SYMBOL = Symbol(\"WAIT_FOR_WEBSOCKET_SYMBOL\");\nconst responseHeadersToSkip = new Set([\n\t\"connection\",\n\t\"content-length\",\n\t\"keep-alive\",\n\t\"proxy-authenticate\",\n\t\"proxy-authorization\",\n\t\"te\",\n\t\"trailer\",\n\t\"transfer-encoding\",\n\t\"upgrade\",\n\t\"sec-websocket-accept\",\n\t\"sec-websocket-extensions\",\n\t\"sec-websocket-protocol\"\n]);\nconst appendResponseHeaders = (headers, responseHeaders) => {\n\tif (!responseHeaders) return;\n\tresponseHeaders.forEach((value, key) => {\n\t\tif (responseHeadersToSkip.has(key.toLowerCase())) return;\n\t\theaders.push(`${key}: ${value}`);\n\t});\n};\nconst rejectUpgradeRequest = (socket, status, responseHeaders) => {\n\tconst responseLines = [\"Connection: close\", \"Content-Length: 0\"];\n\tappendResponseHeaders(responseLines, responseHeaders);\n\tsocket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? \"\"}\\r\\n${responseLines.join(\"\\r\\n\")}\\r\\n\\r\n`);\n};\nconst createUpgradeRequest = (request) => {\n\tconst protocol = request.socket.encrypted ? \"https\" : \"http\";\n\tconst url = new URL(request.url ?? \"/\", `${protocol}://${request.headers.host ?? \"localhost\"}`);\n\tconst headers = new Headers();\n\tfor (const key in request.headers) {\n\t\tconst value = request.headers[key];\n\t\tif (!value) continue;\n\t\theaders.append(key, Array.isArray(value) ? value[0] : value);\n\t}\n\treturn new Request(url, { headers });\n};\nconst setupWebSocket = (options) => {\n\tconst { server, fetchCallback, wss } = options;\n\tconst waiterMap = /* @__PURE__ */ new Map();\n\twss.on(\"connection\", (ws, request) => {\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (waiter) {\n\t\t\twaiter.resolve(ws);\n\t\t\twaiterMap.delete(request);\n\t\t}\n\t});\n\tconst rejectWaiter = (request) => {\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (waiter) {\n\t\t\twaiterMap.delete(request);\n\t\t\twaiter.reject(/* @__PURE__ */ new Error(\"WebSocket handshake aborted\"));\n\t\t}\n\t};\n\tconst waitForWebSocket = (request, connectionSymbol) => {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\twaiterMap.set(request, {\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t\tconnectionSymbol\n\t\t\t});\n\t\t});\n\t};\n\tserver.on(\"upgrade\", async (request, socket, head) => {\n\t\tif (request.headers.upgrade?.toLowerCase() !== \"websocket\") return;\n\t\tconst env = {\n\t\t\tincoming: request,\n\t\t\toutgoing: void 0,\n\t\t\twss,\n\t\t\t[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket\n\t\t};\n\t\tlet status = 400;\n\t\tlet responseHeaders;\n\t\ttry {\n\t\t\tconst response = await fetchCallback(createUpgradeRequest(request), env);\n\t\t\tif (response instanceof Response) {\n\t\t\t\tstatus = response.status;\n\t\t\t\tresponseHeaders = response.headers;\n\t\t\t}\n\t\t} catch {\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, 500);\n\t\t\treturn;\n\t\t}\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {\n\t\t\trejectWaiter(request);\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, status, responseHeaders);\n\t\t\treturn;\n\t\t}\n\t\tconst addResponseHeaders = (headers) => {\n\t\t\tappendResponseHeaders(headers, responseHeaders);\n\t\t};\n\t\tconst reclaimWaiterOnClose = () => rejectWaiter(request);\n\t\tsocket.once(\"close\", reclaimWaiterOnClose);\n\t\twss.on(\"headers\", addResponseHeaders);\n\t\ttry {\n\t\t\twss.handleUpgrade(request, socket, head, (ws) => {\n\t\t\t\tsocket.off(\"close\", reclaimWaiterOnClose);\n\t\t\t\twss.emit(\"connection\", ws, request);\n\t\t\t});\n\t\t} finally {\n\t\t\twss.off(\"headers\", addResponseHeaders);\n\t\t}\n\t});\n\tserver.on(\"close\", () => {\n\t\twss.close();\n\t});\n};\nconst upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {\n\tif (c.req.header(\"upgrade\")?.toLowerCase() !== \"websocket\") return;\n\tconst env = c.env;\n\tconst waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];\n\tif (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });\n\tconst connectionSymbol = generateConnectionSymbol();\n\tenv[CONNECTION_SYMBOL_KEY] = connectionSymbol;\n\t(async () => {\n\t\tlet ws;\n\t\ttry {\n\t\t\tws = await waitForWebSocket(env.incoming, connectionSymbol);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tconst messagesReceivedInStarting = [];\n\t\tconst bufferMessage = (data, isBinary) => {\n\t\t\tmessagesReceivedInStarting.push([data, isBinary]);\n\t\t};\n\t\tws.on(\"message\", bufferMessage);\n\t\tconst ctx = {\n\t\t\tbinaryType: \"arraybuffer\",\n\t\t\tclose(code, reason) {\n\t\t\t\tws.close(code, reason);\n\t\t\t},\n\t\t\tprotocol: ws.protocol,\n\t\t\traw: ws,\n\t\t\tget readyState() {\n\t\t\t\treturn ws.readyState;\n\t\t\t},\n\t\t\tsend(source, opts) {\n\t\t\t\tws.send(source, { compress: opts?.compress });\n\t\t\t},\n\t\t\turl: new URL(c.req.url)\n\t\t};\n\t\ttry {\n\t\t\tevents?.onOpen?.(new Event(\"open\"), ctx);\n\t\t} catch (e) {\n\t\t\t(options?.onError ?? console.error)(e);\n\t\t}\n\t\tconst handleMessage = (data, isBinary) => {\n\t\t\tconst datas = Array.isArray(data) ? data : [data];\n\t\t\tfor (const data of datas) try {\n\t\t\t\tevents?.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);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t};\n\t\tws.off(\"message\", bufferMessage);\n\t\tfor (const message of messagesReceivedInStarting) handleMessage(...message);\n\t\tws.on(\"message\", (data, isBinary) => {\n\t\t\thandleMessage(data, isBinary);\n\t\t});\n\t\tws.on(\"close\", (code, reason) => {\n\t\t\ttry {\n\t\t\t\tevents?.onClose?.(new CloseEvent(\"close\", {\n\t\t\t\t\tcode,\n\t\t\t\t\treason: reason.toString()\n\t\t\t\t}), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t\tws.on(\"error\", (error) => {\n\t\t\ttry {\n\t\t\t\tevents?.onError?.(new ErrorEvent(\"error\", { error }), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t})();\n\treturn new Response();\n});\n\n//#endregion\n//#region src/server.ts\nconst createAdaptorServer = (options) => {\n\tconst fetchCallback = options.fetch;\n\tconst requestListener = getRequestListener(fetchCallback, {\n\t\thostname: options.hostname,\n\t\toverrideGlobalObjects: options.overrideGlobalObjects,\n\t\tautoCleanupIncoming: options.autoCleanupIncoming\n\t});\n\tconst server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);\n\tif (options.websocket && options.websocket.server) {\n\t\tif (options.websocket.server.options.noServer !== true) throw new Error(\"WebSocket server must be created with { noServer: true } option\");\n\t\tsetupWebSocket({\n\t\t\tserver,\n\t\t\tfetchCallback,\n\t\t\twss: options.websocket.server\n\t\t});\n\t}\n\treturn server;\n};\nconst serve = (options, listeningListener) => {\n\tconst server = createAdaptorServer(options);\n\tserver.listen(options?.port ?? 3e3, options.hostname, () => {\n\t\tconst serverInfo = server.address();\n\t\tlisteningListener && listeningListener(serverInfo);\n\t});\n\treturn server;\n};\n\n//#endregion\nexport { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };","import { Readable } from \"node:stream\";\nimport { versions } from \"node:process\";\n\n//#region src/utils/stream.ts\nconst pr54206Applied = () => {\n\tconst [major, minor] = versions.node.split(\".\").map((component) => parseInt(component));\n\treturn major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;\n};\nconst useReadableToWeb = pr54206Applied();\nconst createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => {\n\tif (useNativeReadableToWeb) return Readable.toWeb(stream);\n\tlet controller;\n\tlet settled = false;\n\tconst cleanup = () => {\n\t\tstream.off(\"data\", onData);\n\t\tstream.off(\"error\", onError);\n\t\tstream.off(\"end\", onTerminate);\n\t\tstream.off(\"close\", onTerminate);\n\t};\n\tconst settle = (callback) => {\n\t\tif (settled) return;\n\t\tsettled = true;\n\t\tcleanup();\n\t\tcallback?.();\n\t};\n\tconst onData = (chunk) => {\n\t\tif (settled || !controller) return;\n\t\tcontroller.enqueue(chunk);\n\t\tif ((controller.desiredSize ?? 0) <= 0) stream.pause();\n\t};\n\tconst onError = (error) => {\n\t\tsettle(() => {\n\t\t\tcontroller?.error(error);\n\t\t});\n\t};\n\tconst onTerminate = () => {\n\t\tsettle(() => {\n\t\t\tcontroller?.close();\n\t\t});\n\t};\n\treturn new ReadableStream({\n\t\tstart(streamController) {\n\t\t\tcontroller = streamController;\n\t\t\tstream.on(\"data\", onData);\n\t\t\tstream.on(\"error\", onError);\n\t\t\tstream.on(\"end\", onTerminate);\n\t\t\tstream.on(\"close\", onTerminate);\n\t\t\tstream.pause();\n\t\t},\n\t\tpull() {\n\t\t\tif (!settled) stream.resume();\n\t\t},\n\t\tcancel() {\n\t\t\tsettle();\n\t\t\tconst ignoreError = () => {};\n\t\t\tstream.on(\"error\", ignoreError);\n\t\t\tstream.once(\"close\", () => stream.off(\"error\", ignoreError));\n\t\t\tstream.destroy();\n\t\t}\n\t});\n};\n\n//#endregion\nexport { createStreamBody };","import { createStreamBody } from \"./utils/stream.mjs\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport { createReadStream, existsSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n//#region src/serve-static.ts\nconst 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;\nconst ENCODINGS = {\n\tbr: \".br\",\n\tzstd: \".zst\",\n\tgzip: \".gz\"\n};\nconst ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);\nconst getStats = (path) => {\n\tlet stats;\n\ttry {\n\t\tstats = statSync(path);\n\t} catch {}\n\treturn stats;\n};\nconst BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\\d*)-(\\d*)$/;\nconst parseByteRange = (range) => {\n\tconst match = range.match(BYTE_RANGE_PATTERN);\n\tif (!match) return;\n\tconst [, start, end] = match;\n\tif (start === \"\") return {\n\t\ttype: \"suffix\",\n\t\tlength: Number(end)\n\t};\n\tif (end === \"\") return {\n\t\ttype: \"open-ended\",\n\t\tstart: Number(start)\n\t};\n\treturn {\n\t\ttype: \"bounded\",\n\t\tstart: Number(start),\n\t\tend: Number(end)\n\t};\n};\nconst resolveByteRange = (spec, size) => {\n\tif (size === 0) return;\n\tif (spec.type === \"suffix\") {\n\t\tif (spec.length === 0) return;\n\t\treturn {\n\t\t\tstart: Math.max(size - spec.length, 0),\n\t\t\tend: size - 1\n\t\t};\n\t}\n\tconst end = spec.type === \"bounded\" ? Math.min(spec.end, size - 1) : size - 1;\n\tif (spec.start >= size || spec.start > end) return;\n\treturn {\n\t\tstart: spec.start,\n\t\tend\n\t};\n};\nconst tryDecode = (str, decoder) => {\n\ttry {\n\t\treturn decoder(str);\n\t} catch {\n\t\treturn str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n\t\t\ttry {\n\t\t\t\treturn decoder(match);\n\t\t\t} catch {\n\t\t\t\treturn match;\n\t\t\t}\n\t\t});\n\t}\n};\nconst tryDecodeURI = (str) => tryDecode(str, decodeURI);\nconst serveStatic = (options = { root: \"\" }) => {\n\tconst root = options.root || \"\";\n\tconst optionPath = options.path;\n\tif (root !== \"\" && !existsSync(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);\n\treturn async (c, next) => {\n\t\tif (c.finalized) return next();\n\t\tlet filename;\n\t\tif (optionPath) filename = optionPath;\n\t\telse try {\n\t\t\tfilename = tryDecodeURI(c.req.path);\n\t\t\tif (/(?:^|[\\/\\\\])\\.{1,2}(?:$|[\\/\\\\])|[\\/\\\\]{2,}|\\\\/.test(filename)) throw new Error();\n\t\t} catch {\n\t\t\tawait options.onNotFound?.(c.req.path, c);\n\t\t\treturn next();\n\t\t}\n\t\tlet path = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename);\n\t\tlet stats = getStats(path);\n\t\tif (stats && stats.isDirectory()) {\n\t\t\tconst indexFile = options.index ?? \"index.html\";\n\t\t\tpath = join(path, indexFile);\n\t\t\tstats = getStats(path);\n\t\t}\n\t\tif (!stats) {\n\t\t\tawait options.onNotFound?.(path, c);\n\t\t\treturn next();\n\t\t}\n\t\tconst mimeType = getMimeType(path);\n\t\tc.header(\"Content-Type\", mimeType || \"application/octet-stream\");\n\t\tif (options.precompressed && (!mimeType || mimeType === \"application/octet-stream\" || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {\n\t\t\tconst acceptEncodingSet = new Set(c.req.header(\"Accept-Encoding\")?.split(\",\").map((encoding) => encoding.trim()));\n\t\t\tfor (const encoding of ENCODINGS_ORDERED_KEYS) {\n\t\t\t\tif (!acceptEncodingSet.has(encoding)) continue;\n\t\t\t\tconst precompressedStats = getStats(path + ENCODINGS[encoding]);\n\t\t\t\tif (precompressedStats) {\n\t\t\t\t\tc.header(\"Content-Encoding\", encoding);\n\t\t\t\t\tc.header(\"Vary\", \"Accept-Encoding\", { append: true });\n\t\t\t\t\tstats = precompressedStats;\n\t\t\t\t\tpath = path + ENCODINGS[encoding];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet result;\n\t\tconst size = stats.size;\n\t\tconst range = c.req.header(\"range\") || \"\";\n\t\tc.header(\"Last-Modified\", stats.mtime.toUTCString());\n\t\tif (c.req.method == \"HEAD\" || c.req.method == \"OPTIONS\") {\n\t\t\tc.header(\"Content-Length\", size.toString());\n\t\t\tc.status(200);\n\t\t\tresult = c.body(null);\n\t\t} else if (!range) {\n\t\t\tc.header(\"Content-Length\", size.toString());\n\t\t\tresult = c.body(createStreamBody(createReadStream(path)), 200);\n\t\t} else {\n\t\t\tc.header(\"Accept-Ranges\", \"bytes\");\n\t\t\tconst resolvedRange = resolveByteRange(parseByteRange(range) ?? {\n\t\t\t\ttype: \"open-ended\",\n\t\t\t\tstart: 0\n\t\t\t}, size);\n\t\t\tif (!resolvedRange) {\n\t\t\t\tc.header(\"Content-Range\", `bytes */${size}`);\n\t\t\t\tresult = c.body(null, 416);\n\t\t\t} else {\n\t\t\t\tconst { start, end } = resolvedRange;\n\t\t\t\tconst chunkSize = end - start + 1;\n\t\t\t\tconst stream = createReadStream(path, {\n\t\t\t\t\tstart,\n\t\t\t\t\tend\n\t\t\t\t});\n\t\t\t\tc.header(\"Content-Length\", chunkSize.toString());\n\t\t\t\tc.header(\"Content-Range\", `bytes ${start}-${end}/${size}`);\n\t\t\t\tresult = c.body(createStreamBody(stream), 206);\n\t\t\t}\n\t\t}\n\t\tawait options.onFound?.(path, c);\n\t\treturn result;\n\t};\n};\n\n//#endregion\nexport { serveStatic };","import { html } from \"hono/html\";\n\n//#region src/swagger/renderer.ts\nconst RENDER_TYPE = {\n\tSTRING_ARRAY: \"string_array\",\n\tSTRING: \"string\",\n\tJSON_STRING: \"json_string\",\n\tRAW: \"raw\"\n};\nconst RENDER_TYPE_MAP = {\n\tconfigUrl: RENDER_TYPE.STRING,\n\tdeepLinking: RENDER_TYPE.RAW,\n\tpresets: RENDER_TYPE.STRING_ARRAY,\n\tplugins: RENDER_TYPE.STRING_ARRAY,\n\tspec: RENDER_TYPE.JSON_STRING,\n\turl: RENDER_TYPE.STRING,\n\turls: RENDER_TYPE.JSON_STRING,\n\tlayout: RENDER_TYPE.STRING,\n\tdocExpansion: RENDER_TYPE.STRING,\n\tmaxDisplayedTags: RENDER_TYPE.RAW,\n\toperationsSorter: RENDER_TYPE.RAW,\n\trequestInterceptor: RENDER_TYPE.RAW,\n\tresponseInterceptor: RENDER_TYPE.RAW,\n\tpersistAuthorization: RENDER_TYPE.RAW,\n\tdefaultModelsExpandDepth: RENDER_TYPE.RAW,\n\tdefaultModelExpandDepth: RENDER_TYPE.RAW,\n\tdefaultModelRendering: RENDER_TYPE.STRING,\n\tdisplayRequestDuration: RENDER_TYPE.RAW,\n\tfilter: RENDER_TYPE.RAW,\n\tshowExtensions: RENDER_TYPE.RAW,\n\tshowCommonExtensions: RENDER_TYPE.RAW,\n\tqueryConfigEnabled: RENDER_TYPE.RAW,\n\tdisplayOperationId: RENDER_TYPE.RAW,\n\ttagsSorter: RENDER_TYPE.RAW,\n\tonComplete: RENDER_TYPE.RAW,\n\tsyntaxHighlight: RENDER_TYPE.JSON_STRING,\n\ttryItOutEnabled: RENDER_TYPE.RAW,\n\trequestSnippetsEnabled: RENDER_TYPE.RAW,\n\trequestSnippets: RENDER_TYPE.JSON_STRING,\n\toauth2RedirectUrl: RENDER_TYPE.STRING,\n\tshowMutabledRequest: RENDER_TYPE.RAW,\n\trequest: RENDER_TYPE.JSON_STRING,\n\tsupportedSubmitMethods: RENDER_TYPE.JSON_STRING,\n\tvalidatorUrl: RENDER_TYPE.STRING,\n\twithCredentials: RENDER_TYPE.RAW,\n\tmodelPropertyMacro: RENDER_TYPE.RAW,\n\tparameterMacro: RENDER_TYPE.RAW\n};\nconst renderSwaggerUIOptions = (options) => {\n\treturn Object.entries(options).map(([k, v]) => {\n\t\tconst key = k;\n\t\tif (!RENDER_TYPE_MAP[key] || v === void 0) return \"\";\n\t\tswitch (RENDER_TYPE_MAP[key]) {\n\t\t\tcase RENDER_TYPE.STRING: return `${key}: '${v}'`;\n\t\t\tcase RENDER_TYPE.STRING_ARRAY:\n\t\t\t\tif (!Array.isArray(v)) return \"\";\n\t\t\t\treturn `${key}: [${v.map((ve) => `${ve}`).join(\",\")}]`;\n\t\t\tcase RENDER_TYPE.JSON_STRING: return `${key}: ${JSON.stringify(v)}`;\n\t\t\tcase RENDER_TYPE.RAW: return `${key}: ${v}`;\n\t\t\tdefault: return \"\";\n\t\t}\n\t}).filter((item) => item !== \"\").join(\",\");\n};\n\n//#endregion\n//#region src/swagger/resource.ts\nconst remoteAssets = ({ version }) => {\n\tconst url = `https://cdn.jsdelivr.net/npm/swagger-ui-dist${version !== void 0 ? `@${version}` : \"\"}`;\n\treturn {\n\t\tcss: [`${url}/swagger-ui.css`],\n\t\tjs: [`${url}/swagger-ui-bundle.js`]\n\t};\n};\n\n//#endregion\n//#region src/index.ts\nconst SwaggerUI = (options) => {\n\tconst asset = remoteAssets({ version: options?.version });\n\tdelete options.version;\n\tif (options.manuallySwaggerUIHtml) return options.manuallySwaggerUIHtml(asset);\n\tconst optionsStrings = renderSwaggerUIOptions(options);\n\treturn `\n <div>\n <div id=\"swagger-ui\"></div>\n ${asset.css.map((url) => html`<link rel=\"stylesheet\" href=\"${url}\" />`)}\n ${asset.js.map((url) => html`<script src=\"${url}\" crossorigin=\"anonymous\"><\\/script>`)}\n <script>\n window.onload = () => {\n window.ui = SwaggerUIBundle({\n dom_id: '#swagger-ui',${optionsStrings},\n })\n }\n <\\/script>\n </div>\n `;\n};\nconst middleware = (options) => async (c) => {\n\tconst title = options?.title ?? \"SwaggerUI\";\n\treturn c.html(`\n <!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta name=\"description\" content=\"SwaggerUI\" />\n <title>${title}</title>\n </head>\n <body>\n ${SwaggerUI(options)}\n </body>\n </html>\n `);\n};\n\n//#endregion\nexport { SwaggerUI, middleware as swaggerUI };\n//# sourceMappingURL=index.js.map","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\nimport util from \"node:util\";\n/* These items copied from Node.js: node/lib/internal/errors.js */\nconst classRegExp = /^([A-Z][a-z0-9]*)+$/;\n// Sorted by a rough estimate on most frequently used entries.\nconst kTypes = [\n \"string\",\n \"function\",\n \"number\",\n \"object\",\n // Accept 'Function' and 'Object' as alternative to the lower cased version.\n \"Function\",\n \"Object\",\n \"boolean\",\n \"bigint\",\n \"symbol\",\n];\n/**\n * Determine the specific type of a value for type-mismatch errors.\n * @param {*} value\n * @returns {string}\n */\nfunction determineSpecificType(value) {\n if (value == null) {\n return \"\" + value;\n }\n if (typeof value === \"function\" && value.name) {\n return `function ${value.name}`;\n }\n if (typeof value === \"object\") {\n if (value.constructor?.name) {\n return `an instance of ${value.constructor.name}`;\n }\n return `${util.inspect(value, { depth: -1 })}`;\n }\n let inspected = util.inspect(value, { colors: false });\n if (inspected.length > 28) {\n inspected = `${inspected.slice(0, 25)}...`;\n }\n return `type ${typeof value} (${inspected})`;\n}\n// The following classes are adaptations of a subset of the ERR_* classes\n// declared in Node.js in the file - node/lib/internal/errors.js.\nexport class ERR_HTTP_BODY_NOT_ALLOWED extends Error {\n constructor() {\n super(\"Adding content for this request method or response status is not allowed.\");\n }\n}\nexport class ERR_HTTP_CONTENT_LENGTH_MISMATCH extends Error {\n constructor(actual, expected) {\n super(`Response body's content-length of ${actual} byte(s) does not match the content-length of ${expected} byte(s) set in header`);\n }\n}\nexport class ERR_HTTP_HEADERS_SENT extends Error {\n constructor(arg) {\n super(`Cannot ${arg} headers after they are sent to the client`);\n }\n}\nexport class ERR_INVALID_ARG_VALUE extends TypeError /*, RangeError */ {\n constructor(name, value, reason = \"is invalid\") {\n let inspected = util.inspect(value);\n if (inspected.length > 128) {\n inspected = `${inspected.slice(0, 128)}...`;\n }\n const type = name.includes(\".\") ? \"property\" : \"argument\";\n super(`The ${type} '${name}' ${reason}. Received ${inspected}`);\n }\n}\nexport class ERR_INVALID_CHAR extends TypeError {\n constructor(name, field) {\n let msg = `Invalid character in ${name}`;\n if (field !== undefined) {\n msg += ` [\"${field}\"]`;\n }\n super(msg);\n }\n}\nexport class ERR_HTTP_INVALID_HEADER_VALUE extends TypeError {\n constructor(value, name) {\n super(`Invalid value \"${value}\" for header \"${name}\"`);\n }\n}\nexport class ERR_HTTP_INVALID_STATUS_CODE extends RangeError {\n originalStatusCode;\n constructor(originalStatusCode) {\n super(`Invalid status code: ${originalStatusCode}`);\n this.originalStatusCode = originalStatusCode;\n }\n}\nexport class ERR_HTTP_TRAILER_INVALID extends Error {\n constructor() {\n super(`Trailers are invalid with this transfer encoding`);\n }\n}\nexport class ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n // assert(typeof name === 'string', \"'name' must be a string\");\n if (!Array.isArray(expected)) {\n expected = [expected];\n }\n let msg = \"The \";\n if (name.endsWith(\" argument\")) {\n // For cases like 'first argument'\n msg += `${name} `;\n }\n else {\n const type = name.includes(\".\") ? \"property\" : \"argument\";\n msg += `\"${name}\" ${type} `;\n }\n msg += \"must be \";\n const types = [];\n const instances = [];\n const other = [];\n for (const value of expected) {\n // assert(typeof value === 'string',\n // 'All expected entries have to be of type string');\n if (kTypes.includes(value)) {\n types.push(value.toLowerCase());\n }\n else if (classRegExp.exec(value) !== null) {\n instances.push(value);\n }\n else {\n // assert(value !== 'object',\n // 'The value \"object\" should be written as \"Object\"');\n other.push(value);\n }\n }\n // Special handle `object` in case other instances are allowed to outline\n // the differences between each other.\n if (instances.length > 0) {\n const pos = types.indexOf(\"object\");\n if (pos !== -1) {\n types.splice(pos, 1);\n instances.push(\"Object\");\n }\n }\n if (types.length > 0) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}`;\n }\n else {\n msg += `of type ${types[0]}`;\n }\n if (instances.length > 0 || other.length > 0)\n msg += \" or \";\n }\n if (instances.length > 0) {\n if (instances.length > 2) {\n const last = instances.pop();\n msg += `an instance of ${instances.join(\", \")}, or ${last}`;\n }\n else {\n msg += `an instance of ${instances[0]}`;\n if (instances.length === 2) {\n msg += ` or ${instances[1]}`;\n }\n }\n if (other.length > 0)\n msg += \" or \";\n }\n if (other.length > 0) {\n if (other.length > 2) {\n const last = other.pop();\n msg += `one of ${other.join(\", \")}, or ${last}`;\n }\n else if (other.length === 2) {\n msg += `one of ${other[0]} or ${other[1]}`;\n }\n else {\n if (other[0].toLowerCase() !== other[0])\n msg += \"an \";\n msg += `${other[0]}`;\n }\n }\n msg += `. Received ${determineSpecificType(actual)}`;\n super(msg);\n }\n}\nexport class ERR_INVALID_HTTP_TOKEN extends TypeError {\n constructor(name, field) {\n super(`${name} must be a valid HTTP token [\"${field}\"]`);\n }\n}\nexport class ERR_METHOD_NOT_IMPLEMENTED extends Error {\n constructor(methodName) {\n super(`The ${methodName} method is not implemented`);\n }\n}\nexport class ERR_STREAM_ALREADY_FINISHED extends Error {\n constructor(methodName) {\n super(`Cannot call ${methodName} after a stream was finished`);\n }\n}\nexport class ERR_STREAM_CANNOT_PIPE extends Error {\n constructor() {\n super(`Cannot pipe, not readable`);\n }\n}\nexport class ERR_STREAM_DESTROYED extends Error {\n constructor(methodName) {\n super(`Cannot call ${methodName} after a stream was destroyed`);\n }\n}\nexport class ERR_STREAM_NULL_VALUES extends TypeError {\n constructor() {\n super(`May not write null values to stream`);\n }\n}\nexport class ERR_STREAM_WRITE_AFTER_END extends Error {\n constructor() {\n super(`write after end`);\n }\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n// This file modeled after Node.js - node/lib/_http_incoming.js\nimport { Readable } from \"node:stream\";\nimport { ERR_METHOD_NOT_IMPLEMENTED } from \"../utils/errors.js\";\nconst kHeaders = Symbol(\"kHeaders\");\nconst kHeadersDistinct = Symbol(\"kHeadersDistinct\");\nconst kHeadersCount = Symbol(\"kHeadersCount\");\nconst kTrailers = Symbol(\"kTrailers\");\nconst kTrailersDistinct = Symbol(\"kTrailersDistinct\");\nconst kTrailersCount = Symbol(\"kTrailersCount\");\n/**\n * This is an implementation of IncomingMessage from Node.js intended to run in\n * a WinterTC runtime. The 'Readable' interface of this class is wired to a 'Request'\n * object's 'body'.\n *\n * This instance can be used in normal ways, but it does not give access to the\n * underlying socket (because there isn't one. req.socket will always return null).\n *\n * Some code in this class is transplanted/adapted from node/lib/_http_incoming.js\n */\nexport class FetchIncomingMessage extends Readable {\n get socket() {\n // Difference from Node.js -\n // We don't really have a way to support direct access to the socket\n return null;\n }\n set socket(_val) {\n // Difference from Node.js -\n // We don't really have a way to support direct access to the socket\n throw new ERR_METHOD_NOT_IMPLEMENTED(\"socket\");\n }\n httpVersionMajor;\n httpVersionMinor;\n httpVersion;\n complete = false;\n [kHeaders] = null;\n [kHeadersDistinct] = null;\n [kHeadersCount] = 0;\n rawHeaders = [];\n [kTrailers] = null;\n [kTrailersDistinct] = null;\n [kTrailersCount] = 0;\n rawTrailers = [];\n joinDuplicateHeaders = false;\n aborted = false;\n upgrade = false;\n // request (server) only\n url = \"\";\n method;\n // TODO: Support ClientRequest\n // statusCode = null;\n // statusMessage = null;\n // client = socket;\n _consuming;\n _dumped;\n // The underlying ReadableStream\n _stream = null;\n constructor() {\n const streamOptions = {};\n // Difference from Node.js -\n // In Node.js, if the IncomingMessages is associated with a socket then\n // that socket's 'readableHighWaterMark' would be used to set\n // streamOptions.highWaterMark before calling parent constructor.\n super(streamOptions);\n this._readableState.readingMore = true;\n this._consuming = false;\n // Flag for when we decide that this message cannot possibly be\n // read by the user, so there's no point continuing to handle it.\n this._dumped = false;\n }\n get connection() {\n // Difference from Node.js -\n // We don't really have a way to support direct access to the socket\n return null;\n }\n set connection(_socket) {\n // Difference from Node.js -\n // We don't really have a way to support direct access to the socket\n console.error(\"No support for IncomingMessage.connection\");\n }\n get headers() {\n if (!this[kHeaders]) {\n this[kHeaders] = {};\n const src = this.rawHeaders;\n const dst = this[kHeaders];\n for (let n = 0; n < this[kHeadersCount]; n += 2) {\n this._addHeaderLine(src[n], src[n + 1], dst);\n }\n }\n return this[kHeaders];\n }\n set headers(val) {\n this[kHeaders] = val;\n }\n get headersDistinct() {\n if (!this[kHeadersDistinct]) {\n this[kHeadersDistinct] = {};\n const src = this.rawHeaders;\n const dst = this[kHeadersDistinct];\n for (let n = 0; n < this[kHeadersCount]; n += 2) {\n this._addHeaderLineDistinct(src[n], src[n + 1], dst);\n }\n }\n return this[kHeadersDistinct];\n }\n set headersDistinct(val) {\n this[kHeadersDistinct] = val;\n }\n get trailers() {\n if (!this[kTrailers]) {\n this[kTrailers] = {};\n const src = this.rawTrailers;\n const dst = this[kTrailers];\n for (let n = 0; n < this[kTrailersCount]; n += 2) {\n this._addHeaderLine(src[n], src[n + 1], dst);\n }\n }\n return this[kTrailers];\n }\n set trailers(val) {\n this[kTrailers] = val;\n }\n get trailersDistinct() {\n if (!this[kTrailersDistinct]) {\n this[kTrailersDistinct] = {};\n const src = this.rawTrailers;\n const dst = this[kTrailersDistinct];\n for (let n = 0; n < this[kTrailersCount]; n += 2) {\n this._addHeaderLineDistinct(src[n], src[n + 1], dst);\n }\n }\n return this[kTrailersDistinct];\n }\n set trailersDistinct(val) {\n this[kTrailersDistinct] = val;\n }\n setTimeout(msecs, callback) {\n // Difference from Node.js -\n // In Node.js, this is supposed to set the underlying socket to time out\n // after some time and then run a callback.\n // We do nothing here since we don't really have a way to support direct\n // access to the socket.\n return this;\n }\n async _read(n) {\n // As this is an implementation of stream.Readable, we provide a _read()\n // function that pumps the next chunk out of the underlying ReadableStream.\n if (!this._consuming) {\n this._readableState.readingMore = false;\n this._consuming = true;\n }\n // Difference from Node.js -\n // The Node.js implementation will already have its internal buffer\n // filled by the parserOnBody function.\n // For our implementation, we use the ReadableStream instance.\n if (this._stream == null) {\n // For GET and HEAD requests, the stream would be empty.\n // Simply signal that we're done.\n this.complete = true;\n this.push(null);\n return;\n }\n const reader = this._stream.getReader();\n try {\n const data = await reader.read();\n if (data.done) {\n // Done with stream, tell Readable we have no more data;\n this.complete = true;\n this.push(null);\n }\n else {\n this.push(data.value);\n }\n }\n catch (e) {\n this.destroy(e);\n }\n finally {\n reader.releaseLock();\n }\n }\n _destroy(err, cb) {\n if (!this.readableEnded || !this.complete) {\n this.aborted = true;\n this.emit(\"aborted\");\n }\n // Difference from Node.js -\n // Node.js would check for the existence of the socket and do some additional\n // cleanup.\n // By the way, I believe this name 'onError' is misleading, it is called\n // regardless of whether there was an error. The callback is expected to\n // check for the existence of the error to decide whether the result was\n // actually an error.\n setTimeout(onError, 0, this, err, cb);\n }\n _addHeaderLines(headers, n) {\n if (headers?.length) {\n let dest;\n if (this.complete) {\n this.rawTrailers = headers;\n this[kTrailersCount] = n;\n dest = this[kTrailers];\n }\n else {\n this.rawHeaders = headers;\n this[kHeadersCount] = n;\n dest = this[kHeaders];\n }\n if (dest) {\n for (let i = 0; i < n; i += 2) {\n this._addHeaderLine(headers[i], headers[i + 1], dest);\n }\n }\n }\n }\n // Add the given (field, value) pair to the message\n //\n // Per RFC2616, section 4.2 it is acceptable to join multiple instances of the\n // same header with a ', ' if the header in question supports specification of\n // multiple values this way. The one exception to this is the Cookie header,\n // which has multiple values joined with a '; ' instead. If a header's values\n // cannot be joined in either of these ways, we declare the first instance the\n // winner and drop the second. Extended header fields (those beginning with\n // 'x-') are always joined.\n _addHeaderLine(field, value, dest) {\n field = matchKnownFields(field);\n const flag = field.charCodeAt(0);\n if (flag === 0 || flag === 2) {\n field = field.slice(1);\n // Make a delimited list\n if (typeof dest[field] === \"string\") {\n dest[field] += (flag === 0 ? \", \" : \"; \") + value;\n }\n else {\n dest[field] = value;\n }\n }\n else if (flag === 1) {\n // Array header -- only Set-Cookie at the moment\n if (dest[\"set-cookie\"] !== undefined) {\n dest[\"set-cookie\"].push(value);\n }\n else {\n dest[\"set-cookie\"] = [value];\n }\n }\n else if (this.joinDuplicateHeaders) {\n // RFC 9110 https://www.rfc-editor.org/rfc/rfc9110#section-5.2\n // https://github.com/nodejs/node/issues/45699\n // allow authorization multiple fields\n // Make a delimited list\n if (dest[field] === undefined) {\n dest[field] = value;\n }\n else {\n dest[field] += \", \" + value;\n }\n }\n else if (dest[field] === undefined) {\n // Drop duplicates\n dest[field] = value;\n }\n }\n _addHeaderLineDistinct(field, value, dest) {\n field = field.toLowerCase();\n if (!dest[field]) {\n dest[field] = [value];\n }\n else {\n dest[field].push(value);\n }\n }\n // Call this instead of resume() if we want to just\n // dump all the data to /dev/null\n _dump() {\n if (!this._dumped) {\n this._dumped = true;\n // If there is buffered data, it may trigger 'data' events.\n // Remove 'data' event listeners explicitly.\n this.removeAllListeners(\"data\");\n this.resume();\n }\n }\n}\n/* These items copied from Node.js: node/lib/_http_incoming.js, because they are not exported from that file. */\n// This function is used to help avoid the lowercasing of a field name if it\n// matches a 'traditional cased' version of a field name. It then returns the\n// lowercased name to both avoid calling toLowerCase() a second time and to\n// indicate whether the field was a 'no duplicates' field. If a field is not a\n// 'no duplicates' field, a `0` byte is prepended as a flag. The one exception\n// to this is the Set-Cookie header which is indicated by a `1` byte flag, since\n// it is an 'array' field and thus is treated differently in _addHeaderLines().\n// TODO: perhaps http_parser could be returning both raw and lowercased versions\n// of known header names to avoid us having to call toLowerCase() for those\n// headers.\nfunction matchKnownFields(field, lowercased = false) {\n switch (field.length) {\n case 3:\n if (field === \"Age\" || field === \"age\")\n return \"age\";\n break;\n case 4:\n if (field === \"Host\" || field === \"host\")\n return \"host\";\n if (field === \"From\" || field === \"from\")\n return \"from\";\n if (field === \"ETag\" || field === \"etag\")\n return \"etag\";\n if (field === \"Date\" || field === \"date\")\n return \"\\u0000date\";\n if (field === \"Vary\" || field === \"vary\")\n return \"\\u0000vary\";\n break;\n case 6:\n if (field === \"Server\" || field === \"server\")\n return \"server\";\n if (field === \"Cookie\" || field === \"cookie\")\n return \"\\u0002cookie\";\n if (field === \"Origin\" || field === \"origin\")\n return \"\\u0000origin\";\n if (field === \"Expect\" || field === \"expect\")\n return \"\\u0000expect\";\n if (field === \"Accept\" || field === \"accept\")\n return \"\\u0000accept\";\n break;\n case 7:\n if (field === \"Referer\" || field === \"referer\")\n return \"referer\";\n if (field === \"Expires\" || field === \"expires\")\n return \"expires\";\n if (field === \"Upgrade\" || field === \"upgrade\")\n return \"\\u0000upgrade\";\n break;\n case 8:\n if (field === \"Location\" || field === \"location\")\n return \"location\";\n if (field === \"If-Match\" || field === \"if-match\")\n return \"\\u0000if-match\";\n break;\n case 10:\n if (field === \"User-Agent\" || field === \"user-agent\")\n return \"user-agent\";\n if (field === \"Set-Cookie\" || field === \"set-cookie\")\n return \"\\u0001\";\n if (field === \"Connection\" || field === \"connection\")\n return \"\\u0000connection\";\n break;\n case 11:\n if (field === \"Retry-After\" || field === \"retry-after\")\n return \"retry-after\";\n break;\n case 12:\n if (field === \"Content-Type\" || field === \"content-type\")\n return \"content-type\";\n if (field === \"Max-Forwards\" || field === \"max-forwards\")\n return \"max-forwards\";\n break;\n case 13:\n if (field === \"Authorization\" || field === \"authorization\")\n return \"authorization\";\n if (field === \"Last-Modified\" || field === \"last-modified\")\n return \"last-modified\";\n if (field === \"Cache-Control\" || field === \"cache-control\")\n return \"\\u0000cache-control\";\n if (field === \"If-None-Match\" || field === \"if-none-match\")\n return \"\\u0000if-none-match\";\n break;\n case 14:\n if (field === \"Content-Length\" || field === \"content-length\")\n return \"content-length\";\n break;\n case 15:\n if (field === \"Accept-Encoding\" || field === \"accept-encoding\")\n return \"\\u0000accept-encoding\";\n if (field === \"Accept-Language\" || field === \"accept-language\")\n return \"\\u0000accept-language\";\n if (field === \"X-Forwarded-For\" || field === \"x-forwarded-for\")\n return \"\\u0000x-forwarded-for\";\n break;\n case 16:\n if (field === \"Content-Encoding\" || field === \"content-encoding\")\n return \"\\u0000content-encoding\";\n if (field === \"X-Forwarded-Host\" || field === \"x-forwarded-host\")\n return \"\\u0000x-forwarded-host\";\n break;\n case 17:\n if (field === \"If-Modified-Since\" || field === \"if-modified-since\")\n return \"if-modified-since\";\n if (field === \"Transfer-Encoding\" || field === \"transfer-encoding\")\n return \"\\u0000transfer-encoding\";\n if (field === \"X-Forwarded-Proto\" || field === \"x-forwarded-proto\")\n return \"\\u0000x-forwarded-proto\";\n break;\n case 19:\n if (field === \"Proxy-Authorization\" || field === \"proxy-authorization\")\n return \"proxy-authorization\";\n if (field === \"If-Unmodified-Since\" || field === \"if-unmodified-since\")\n return \"if-unmodified-since\";\n break;\n }\n if (lowercased) {\n return \"\\u0000\" + field;\n }\n return matchKnownFields(field.toLowerCase(), true);\n}\nfunction onError(self, error, cb) {\n // This is to keep backward compatible behavior.\n // An error is emitted only if there are listeners attached to the event.\n if (self.listenerCount(\"error\") === 0) {\n cb();\n }\n else {\n cb(error);\n }\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\nimport { ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE } from \"./errors.js\";\n/* These items copied from Node.js: node/lib/internal/validators.js */\nexport function validateString(value, name) {\n if (typeof value !== \"string\")\n throw new ERR_INVALID_ARG_TYPE(name, \"string\", value);\n}\nconst linkValueRegExp = /^(?:<[^>]*>)(?:\\s*;\\s*[^;\"\\s]+(?:=(\")?[^;\"\\s]*\\1)?)*$/;\nexport function validateLinkHeaderFormat(value, name) {\n if (typeof value === \"undefined\" || !linkValueRegExp.exec(value)) {\n throw new ERR_INVALID_ARG_VALUE(name, value, 'must be an array or string of format \"</styles.css>; rel=preload; as=style\"');\n }\n}\nexport function validateLinkHeaderValue(hints) {\n if (typeof hints === \"string\") {\n validateLinkHeaderFormat(hints, \"hints\");\n return hints;\n }\n else if (Array.isArray(hints)) {\n const hintsLength = hints.length;\n let result = \"\";\n if (hintsLength === 0) {\n return result;\n }\n for (let i = 0; i < hintsLength; i++) {\n const link = hints[i];\n validateLinkHeaderFormat(link, \"hints\");\n result += link;\n if (i !== hintsLength - 1) {\n result += \", \";\n }\n }\n return result;\n }\n throw new ERR_INVALID_ARG_VALUE(\"hints\", hints, 'must be an array or string of format \"</styles.css>; rel=preload; as=style\"');\n}\n/* These items copied from Node.js: node/lib/internal/util/types.js */\nexport function isUint8Array(value) {\n return value != null && value[Symbol.toStringTag] === \"Uint8Array\";\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n/* These items copied from Node.js: node/lib/internal/http.js. */\nexport const kNeedDrain = Symbol(\"kNeedDrain\");\nexport const kOutHeaders = Symbol(\"kOutHeaders\");\n// In Node.js this utcDate is cached for 1 second, for use across\n// all http connections. However, in C@E we just create a new one\n// since we're not able to share this data across separate invocations.\nexport function utcDate() {\n return new Date().toUTCString();\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n/* These items copied from Node.js: node/lib/internal/streams/state.js. */\nexport function getDefaultHighWaterMark(objectMode) {\n return objectMode ? 16 : 64 * 1024;\n}\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n/* These items copied from Node.js: node/lib/_http_common.js. */\nconst tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/;\n/**\n * Verifies that the given val is a valid HTTP token\n * per the rules defined in RFC 7230\n * See https://tools.ietf.org/html/rfc7230#section-3.2.6\n */\nexport function checkIsHttpToken(val) {\n return tokenRegExp.test(val);\n}\nconst headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n/**\n * True if val contains an invalid field-vchar\n * field-value = *( field-content / obs-fold )\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n */\nexport function checkInvalidHeaderChar(val) {\n return headerCharRegex.test(val);\n}\nexport const chunkExpression = /(?:^|\\W)chunked(?:$|\\W)/i;\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\n// This file modeled after Node.js - node/lib/_http_outgoing.js\nimport { Buffer } from \"node:buffer\";\nimport { Writable } from \"node:stream\";\nimport { ERR_HTTP_BODY_NOT_ALLOWED, ERR_HTTP_CONTENT_LENGTH_MISMATCH, ERR_HTTP_HEADERS_SENT, ERR_HTTP_INVALID_HEADER_VALUE, ERR_HTTP_TRAILER_INVALID, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_INVALID_CHAR, ERR_INVALID_HTTP_TOKEN, ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_ALREADY_FINISHED, ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END, } from \"../utils/errors.js\";\nimport { isUint8Array, validateString } from \"../utils/types.js\";\nimport { kNeedDrain, kOutHeaders, utcDate } from \"./internal-http.js\";\nimport { getDefaultHighWaterMark } from \"./internal-streams-state.js\";\nimport { checkInvalidHeaderChar, checkIsHttpToken, chunkExpression as RE_TE_CHUNKED, } from \"./http-common.js\";\n/* These items copied from Node.js: node/lib/_http_outgoing.js. */\nfunction debug(format) {\n // console.log(\"http \" + format);\n}\nconst kCorked = Symbol(\"corked\");\nconst kChunkedBuffer = Symbol(\"kChunkedBuffer\");\nconst kChunkedLength = Symbol(\"kChunkedLength\");\nconst kUniqueHeaders = Symbol(\"kUniqueHeaders\");\nconst kBytesWritten = Symbol(\"kBytesWritten\");\nconst kErrored = Symbol(\"errored\");\nconst kHighWaterMark = Symbol(\"kHighWaterMark\");\nconst kRejectNonStandardBodyWrites = Symbol(\"kRejectNonStandardBodyWrites\");\nconst nop = () => { };\nconst RE_CONN_CLOSE = /(?:^|\\W)close(?:$|\\W)/i;\n// isCookieField performs a case-insensitive comparison of a provided string\n// against the word \"cookie.\" As of V8 6.6 this is faster than handrolling or\n// using a case-insensitive RegExp.\nfunction isCookieField(s) {\n return s.length === 6 && s.toLowerCase() === \"cookie\";\n}\nfunction isContentDispositionField(s) {\n return s.length === 19 && s.toLowerCase() === \"content-disposition\";\n}\n/**\n * An in-memory buffer that stores the chunks that have been streamed to an\n * OutgoingMessage instance.\n */\nexport class WrittenDataBuffer {\n [kCorked] = 0;\n [kHighWaterMark] = getDefaultHighWaterMark();\n entries = [];\n onWrite;\n constructor(params = {}) {\n this.onWrite = params.onWrite;\n }\n write(data, encoding, callback) {\n this.entries.push({\n data,\n length: data.length,\n encoding,\n callback,\n written: false,\n });\n this._flush();\n return true;\n }\n cork() {\n this[kCorked]++;\n }\n uncork() {\n this[kCorked]--;\n this._flush();\n }\n _flush() {\n if (this[kCorked] <= 0) {\n for (const [index, entry] of this.entries.entries()) {\n if (!entry.written) {\n entry.written = true;\n if (this.onWrite != null) {\n this.onWrite(index, entry);\n }\n if (entry.callback != null) {\n entry.callback.call(undefined);\n }\n }\n }\n }\n }\n get writableLength() {\n return this.entries.reduce((acc, entry) => {\n return acc + (entry.written && entry.length ? entry.length : 0);\n }, 0);\n }\n get writableHighWaterMark() {\n return this[kHighWaterMark];\n }\n get writableCorked() {\n return this[kCorked];\n }\n}\n/**\n * This is an implementation of OutgoingMessage from Node.js intended to run in\n * a WinterTC runtime. The 'Writable' interface of this class is wired to an in-memory\n * buffer.\n *\n * This instance can be used in normal ways, but it does not give access to the\n * underlying socket (because there isn't one. req.socket will always return null).\n *\n * Some code in this class is transplanted/adapted from node/lib/_http_outgoing.js\n */\nexport class FetchOutgoingMessage extends Writable {\n req;\n outputData;\n outputSize;\n // Difference from Node.js -\n // `writtenHeaderBytes` is the number of bytes the header has taken.\n // Since Node.js writes both the headers and body into the same outgoing\n // stream, it helps to keep track of this so that we can skip that many bytes\n // from the beginning of the stream when providing the outgoing stream.\n writtenHeaderBytes = 0;\n _last;\n chunkedEncoding;\n shouldKeepAlive;\n maxRequestsOnConnectionReached;\n _defaultKeepAlive;\n useChunkedEncodingByDefault;\n sendDate;\n _removedConnection;\n _removedContLen;\n _removedTE;\n strictContentLength;\n [kBytesWritten];\n _contentLength;\n _hasBody;\n _trailer;\n [kNeedDrain];\n finished;\n _headerSent;\n [kCorked];\n [kChunkedBuffer];\n [kChunkedLength];\n _closed;\n // Difference from Node.js -\n // In Node.js, this is a socket object.\n // [kSocket]: null;\n _header;\n [kOutHeaders];\n _keepAliveTimeout;\n _maxRequestsPerSocket;\n _onPendingData;\n [kUniqueHeaders];\n [kErrored];\n [kHighWaterMark];\n [kRejectNonStandardBodyWrites];\n _writtenDataBuffer = new WrittenDataBuffer({\n onWrite: this._onDataWritten.bind(this),\n });\n constructor(req, options) {\n super();\n this.req = req;\n // Queue that holds all currently pending data, until the response will be\n // assigned to the socket (until it will its turn in the HTTP pipeline).\n this.outputData = [];\n // `outputSize` is an approximate measure of how much data is queued on this\n // response. `_onPendingData` will be invoked to update similar global\n // per-connection counter. That counter will be used to pause/unpause the\n // TCP socket and HTTP Parser and thus handle the backpressure.\n this.outputSize = 0;\n // Cannot assign to this.writable because it is a readonly property\n // this.writable = true;\n this.destroyed = false;\n this._last = false;\n this.chunkedEncoding = false;\n this.shouldKeepAlive = true;\n this.maxRequestsOnConnectionReached = false;\n this._defaultKeepAlive = true;\n this.useChunkedEncodingByDefault = true;\n this.sendDate = false;\n this._removedConnection = false;\n this._removedContLen = false;\n this._removedTE = false;\n this.strictContentLength = false;\n this[kBytesWritten] = 0;\n this._contentLength = null;\n this._hasBody = true;\n this._trailer = \"\";\n this[kNeedDrain] = false;\n this.finished = false;\n this._headerSent = false;\n this[kCorked] = 0;\n this[kChunkedBuffer] = [];\n this[kChunkedLength] = 0;\n this._closed = false;\n this._header = null;\n this[kOutHeaders] = null;\n this._keepAliveTimeout = 0;\n this._onPendingData = nop;\n this[kErrored] = null;\n this[kHighWaterMark] = options?.highWaterMark ?? getDefaultHighWaterMark();\n this[kRejectNonStandardBodyWrites] =\n options?.rejectNonStandardBodyWrites ?? false;\n this[kUniqueHeaders] = null;\n }\n _renderHeaders() {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"render\");\n }\n const headersMap = this[kOutHeaders];\n const headers = {};\n if (headersMap !== null) {\n const keys = Object.keys(headersMap);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0, l = keys.length; i < l; i++) {\n const key = keys[i];\n headers[headersMap[key][0]] = headersMap[key][1];\n }\n }\n return headers;\n }\n cork() {\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would call cork() on the socket instead\n // In our implementation, we do the same to the \"written data buffer\" instead.\n this[kCorked]++;\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.cork();\n }\n }\n uncork() {\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would call uncork() on the socket instead\n // In our implementation, we do the same to the \"written data buffer\" instead.\n this[kCorked]--;\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.uncork();\n }\n if (this[kCorked] || this[kChunkedBuffer].length === 0) {\n return;\n }\n // Difference from Node.js -\n // Chunked transfer encoding doesn't need to use the low-level protocol\n // (with each chunk preceded by its length)\n // All commented out code below is from Node.js used for this purpose.\n // const len = this[kChunkedLength];\n const buf = this[kChunkedBuffer];\n // assert(this.chunkedEncoding);\n // let callbacks: (WriteCallback | undefined)[] | undefined;\n // this._send(len.toString(16), \"latin1\", null);\n // this._send(crlf_buf, null, null);\n for (const { data, encoding, callback } of buf) {\n // this._send(data ?? \"\", encoding, null);\n // if (callback) {\n // callbacks ??= [];\n // callbacks.push(callback);\n // }\n this._send(data ?? \"\", encoding, callback);\n }\n // this._send(\n // crlf_buf,\n // null,\n // callbacks?.length\n // ? (err) => {\n // for (const callback of callbacks) {\n // callback?.(err);\n // }\n // }\n // : null\n // );\n this[kChunkedBuffer].length = 0;\n this[kChunkedLength] = 0;\n }\n setTimeout(msecs, callback) {\n // Difference from Node.js -\n // In Node.js, this is supposed to set the underlying socket to time out\n // after some time and then run a callback.\n // We do nothing here since we don't really have a way to support direct\n // access to the socket.\n return this;\n }\n destroy(error) {\n if (this.destroyed) {\n return this;\n }\n this.destroyed = true;\n this[kErrored] = error;\n // Difference from Node.js -\n // In Node.js, we would also attempt to destroy the underlying socket.\n return this;\n }\n _send(data, encoding, callback, byteLength) {\n // This is a shameful hack to get the headers and first body chunk onto\n // the same packet. Future versions of Node are going to take care of\n // this at a lower level and in a more general way.\n if (!this._headerSent) {\n const header = this._header;\n if (typeof data === \"string\" &&\n (encoding === \"utf8\" || encoding === \"latin1\" || !encoding)) {\n data = header + data;\n }\n else {\n this.outputData.unshift({\n data: header,\n encoding: \"latin1\",\n callback: undefined,\n });\n this.outputSize += header.length;\n this._onPendingData(header.length);\n }\n this._headerSent = true;\n // Difference from Node.js -\n // Parse headers here and trigger _headersSent\n this.writtenHeaderBytes = header.length;\n // Save written headers as object\n const [statusLine, ...headerLines] = this._header.split(\"\\r\\n\");\n const STATUS_LINE_REGEXP = /^HTTP\\/1\\.1 (?<statusCode>\\d+) (?<statusMessage>.*)$/;\n const statusLineResult = STATUS_LINE_REGEXP.exec(statusLine);\n if (statusLineResult == null) {\n throw new Error(\"Unexpected! Status line was \" + statusLine);\n }\n const { statusCode: statusCodeText, statusMessage } = statusLineResult.groups ?? {};\n const statusCode = parseInt(statusCodeText, 10);\n const headers = [];\n for (const headerLine of headerLines) {\n if (headerLine !== \"\") {\n const pos = headerLine.indexOf(\": \");\n const k = headerLine.slice(0, pos);\n const v = headerLine.slice(pos + 2); // Skip the colon and the space\n headers.push([k, v]);\n }\n }\n const event = {\n statusCode,\n statusMessage,\n headers,\n };\n this.emit(\"_headersSent\", event);\n }\n return this._writeRaw(data, encoding, callback, byteLength);\n }\n _writeRaw(data, encoding, callback, size) {\n // Difference from Node.js -\n // In Node.js, we would check for an underlying socket, and if that socket\n // exists and is already destroyed, simply return false.\n if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n // Difference from Node.js -\n // In Node.js, we would check for an underlying socket, and if that socket\n // exists and is currently writable, it would flush any pending data to the socket and then\n // write the current chunk's data directly into the socket. Afterwards, it would return with the\n // value returned from socket.write().\n // In our implementation, instead we do the same for the \"written data buffer\".\n if (this._writtenDataBuffer != null) {\n // There might be pending data in the this.output buffer.\n if (this.outputData.length) {\n this._flushOutput(this._writtenDataBuffer);\n }\n // Directly write to the buffer.\n return this._writtenDataBuffer.write(data, encoding, callback);\n }\n // Buffer, as long as we're not destroyed.\n this.outputData.push({ data, encoding, callback });\n this.outputSize += data.length;\n this._onPendingData(data.length);\n return this.outputSize < this[kHighWaterMark];\n }\n _onDataWritten(index, entry) {\n const event = { index, entry };\n this.emit(\"_dataWritten\", event);\n }\n _storeHeader(firstLine, headers) {\n // firstLine in the case of request is: 'GET /index.html HTTP/1.1\\r\\n'\n // in the case of response it is: 'HTTP/1.1 200 OK\\r\\n'\n const state = {\n connection: false,\n contLen: false,\n te: false,\n date: false,\n expect: false,\n trailer: false,\n header: firstLine,\n };\n if (headers) {\n if (headers === this[kOutHeaders]) {\n for (const key in headers) {\n const entry = headers[key];\n processHeader(this, state, entry[0], entry[1], false);\n }\n }\n else if (Array.isArray(headers)) {\n if (headers.length && Array.isArray(headers[0])) {\n for (let i = 0; i < headers.length; i++) {\n const entry = headers[i];\n processHeader(this, state, entry[0], entry[1], true);\n }\n }\n else {\n if (headers.length % 2 !== 0) {\n throw new ERR_INVALID_ARG_VALUE(\"headers\", headers);\n }\n for (let n = 0; n < headers.length; n += 2) {\n processHeader(this, state, headers[n], headers[n + 1], true);\n }\n }\n }\n else {\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n const _headers = headers;\n processHeader(this, state, key, _headers[key], true);\n }\n }\n }\n }\n let { header } = state;\n // Date header\n if (this.sendDate && !state.date) {\n header += \"Date: \" + utcDate() + \"\\r\\n\";\n }\n // Force the connection to close when the response is a 204 No Content or\n // a 304 Not Modified and the user has set a \"Transfer-Encoding: chunked\"\n // header.\n //\n // RFC 2616 mandates that 204 and 304 responses MUST NOT have a body but\n // node.js used to send out a zero chunk anyway to accommodate clients\n // that don't have special handling for those responses.\n //\n // It was pointed out that this might confuse reverse proxies to the point\n // of creating security liabilities, so suppress the zero chunk and force\n // the connection to close.\n // NOTE: the \"as any\" here is needed because 'statusCode' is only\n // defined on the subclass but is used here.\n if (this.chunkedEncoding &&\n (this.statusCode === 204 || this.statusCode === 304)) {\n debug(this.statusCode +\n \" response should not use chunked encoding,\" +\n \" closing connection.\");\n this.chunkedEncoding = false;\n this.shouldKeepAlive = false;\n }\n // keep-alive logic\n if (this._removedConnection) {\n // shouldKeepAlive is generally true for HTTP/1.1. In that common case,\n // even if the connection header isn't sent, we still persist by default.\n this._last = !this.shouldKeepAlive;\n }\n else if (!state.connection) {\n // this.agent would only exist on class ClientRequest\n const shouldSendKeepAlive = this.shouldKeepAlive &&\n (state.contLen || this.useChunkedEncodingByDefault); /* || this.agent */\n if (shouldSendKeepAlive && this.maxRequestsOnConnectionReached) {\n header += \"Connection: close\\r\\n\";\n }\n else if (shouldSendKeepAlive) {\n header += \"Connection: keep-alive\\r\\n\";\n if (this._keepAliveTimeout && this._defaultKeepAlive) {\n const timeoutSeconds = Math.floor(this._keepAliveTimeout / 1000);\n let max = \"\";\n if (this._maxRequestsPerSocket && ~~this._maxRequestsPerSocket > 0) {\n max = `, max=${this._maxRequestsPerSocket}`;\n }\n header += `Keep-Alive: timeout=${timeoutSeconds}${max}\\r\\n`;\n }\n }\n else {\n this._last = true;\n header += \"Connection: close\\r\\n\";\n }\n }\n if (!state.contLen && !state.te) {\n if (!this._hasBody) {\n // Make sure we don't end the 0\\r\\n\\r\\n at the end of the message.\n this.chunkedEncoding = false;\n }\n else if (!this.useChunkedEncodingByDefault) {\n this._last = true;\n }\n else if (!state.trailer &&\n !this._removedContLen &&\n typeof this._contentLength === \"number\") {\n header += \"Content-Length: \" + this._contentLength + \"\\r\\n\";\n }\n else if (!this._removedTE) {\n header += \"Transfer-Encoding: chunked\\r\\n\";\n this.chunkedEncoding = true;\n }\n else {\n // We should only be able to get here if both Content-Length and\n // Transfer-Encoding are removed by the user.\n // See: test/parallel/test-http-remove-header-stays-removed.js\n debug(\"Both Content-Length and Transfer-Encoding are removed\");\n // We can't keep alive in this case, because with no header info the body\n // is defined as all data until the connection is closed.\n this._last = true;\n }\n }\n // Test non-chunked message does not have trailer header set,\n // message will be terminated by the first empty line after the\n // header fields, regardless of the header fields present in the\n // message, and thus cannot contain a message body or 'trailers'.\n if (this.chunkedEncoding !== true && state.trailer) {\n throw new ERR_HTTP_TRAILER_INVALID();\n }\n this._header = header + \"\\r\\n\";\n this._headerSent = false;\n // Wait until the first body chunk, or close(), is sent to flush,\n // UNLESS we're sending Expect: 100-continue.\n if (state.expect) {\n this._send(\"\");\n }\n }\n get _headers() {\n console.warn(\"DEP0066: OutgoingMessage.prototype._headers is deprecated\");\n return this.getHeaders();\n }\n set _headers(val) {\n console.warn(\"DEP0066: OutgoingMessage.prototype._headers is deprecated\");\n if (val == null) {\n this[kOutHeaders] = null;\n }\n else if (typeof val === \"object\") {\n const headers = (this[kOutHeaders] = Object.create(null));\n const keys = Object.keys(val);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; ++i) {\n const name = keys[i];\n headers[name.toLowerCase()] = [name, val[name]];\n }\n }\n }\n get connection() {\n // Difference from Node.js -\n // Connection is not supported\n return null;\n }\n set connection(_socket) {\n // Difference from Node.js -\n // Connection is not supported\n console.error(\"No support for OutgoingMessage.connection\");\n }\n get socket() {\n // Difference from Node.js -\n // socket is not supported\n return null;\n }\n set socket(_socket) {\n // Difference from Node.js -\n // socket is not supported\n console.error(\"No support for OutgoingMessage.socket\");\n }\n get _headerNames() {\n console.warn(\"DEP0066: OutgoingMessage.prototype._headerNames is deprecated\");\n const headers = this[kOutHeaders];\n if (headers !== null) {\n const out = Object.create(null);\n const keys = Object.keys(headers);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n const val = headers[key][0];\n out[key] = val;\n }\n return out;\n }\n return null;\n }\n set _headerNames(val) {\n console.warn(\"DEP0066: OutgoingMessage.prototype._headerNames is deprecated\");\n if (typeof val === \"object\" && val !== null) {\n const headers = this[kOutHeaders];\n if (!headers)\n return;\n const keys = Object.keys(val);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; ++i) {\n const header = headers[keys[i]];\n if (header)\n header[0] = val[keys[i]];\n }\n }\n }\n setHeader(name, value) {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"set\");\n }\n validateHeaderName(name);\n validateHeaderValue(name, value);\n let headers = this[kOutHeaders];\n if (headers === null) {\n this[kOutHeaders] = headers = { __proto__: null };\n }\n headers[name.toLowerCase()] = [name, value];\n return this;\n }\n setHeaders(headers) {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"set\");\n }\n if (!headers ||\n Array.isArray(headers) ||\n typeof headers.keys !== \"function\" ||\n typeof headers.get !== \"function\") {\n throw new ERR_INVALID_ARG_TYPE(\"headers\", [\"Headers\", \"Map\"], headers);\n }\n // Headers object joins multiple cookies with a comma when using\n // the getter to retrieve the value,\n // unless iterating over the headers directly.\n // We also cannot safely split by comma.\n // To avoid setHeader overwriting the previous value we push\n // set-cookie values in array and set them all at once.\n const cookies = [];\n for (const { 0: key, 1: value } of headers) {\n if (key === \"set-cookie\") {\n if (Array.isArray(value)) {\n cookies.push(...value);\n }\n else {\n cookies.push(value);\n }\n continue;\n }\n this.setHeader(key, value);\n }\n if (cookies.length) {\n this.setHeader(\"set-cookie\", cookies);\n }\n return this;\n }\n appendHeader(name, value) {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"append\");\n }\n validateHeaderName(name);\n validateHeaderValue(name, value);\n const field = name.toLowerCase();\n const headers = this[kOutHeaders];\n if (headers === null || !headers[field]) {\n return this.setHeader(name, value);\n }\n // Prepare the field for appending, if required\n if (!Array.isArray(headers[field][1])) {\n headers[field][1] = [headers[field][1]];\n }\n const existingValues = headers[field][1];\n if (Array.isArray(value)) {\n for (let i = 0, length = value.length; i < length; i++) {\n existingValues.push(value[i]);\n }\n }\n else {\n existingValues.push(value);\n }\n return this;\n }\n getHeader(name) {\n validateString(name, \"name\");\n const headers = this[kOutHeaders];\n if (headers === null) {\n return;\n }\n const entry = headers[name.toLowerCase()];\n return entry?.[1];\n }\n getHeaderNames() {\n return this[kOutHeaders] !== null ? Object.keys(this[kOutHeaders]) : [];\n }\n getRawHeaderNames() {\n const headersMap = this[kOutHeaders];\n if (headersMap === null)\n return [];\n const values = Object.values(headersMap);\n const headers = Array(values.length);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0, l = values.length; i < l; i++) {\n headers[i] = values[i][0];\n }\n return headers;\n }\n getHeaders() {\n const headers = this[kOutHeaders];\n const ret = { __proto__: null };\n if (headers) {\n const keys = Object.keys(headers);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n const val = headers[key][1];\n ret[key] = val;\n }\n }\n return ret;\n }\n hasHeader(name) {\n validateString(name, \"name\");\n return (this[kOutHeaders] !== null && !!this[kOutHeaders][name.toLowerCase()]);\n }\n removeHeader(name) {\n validateString(name, \"name\");\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"remove\");\n }\n const key = name.toLowerCase();\n switch (key) {\n case \"connection\":\n this._removedConnection = true;\n break;\n case \"content-length\":\n this._removedContLen = true;\n break;\n case \"transfer-encoding\":\n this._removedTE = true;\n break;\n case \"date\":\n this.sendDate = false;\n break;\n }\n if (this[kOutHeaders] !== null) {\n delete this[kOutHeaders][key];\n }\n }\n _implicitHeader() {\n throw new ERR_METHOD_NOT_IMPLEMENTED(\"_implicitHeader()\");\n }\n get headersSent() {\n return !!this._header;\n }\n write(chunk, encoding, callback) {\n if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n const ret = write_(this, chunk, encoding, callback, false);\n if (!ret) {\n this[kNeedDrain] = true;\n }\n return ret;\n }\n addTrailers(headers) {\n this._trailer = \"\";\n const isArray = Array.isArray(headers);\n const keys = isArray ? [...headers.keys()] : Object.keys(headers);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0, l = keys.length; i < l; i++) {\n let field, value;\n if (isArray) {\n const _headers = headers;\n const key = keys[i];\n field = _headers[key][0];\n value = _headers[key][1];\n }\n else {\n const _headers = headers;\n const key = keys[i];\n field = key;\n value = _headers[key];\n }\n validateHeaderName(field, \"Trailer name\");\n // Check if the field must be sent several times\n if (Array.isArray(value) &&\n value.length > 1 &&\n (!this[kUniqueHeaders] ||\n !this[kUniqueHeaders].has(field.toLowerCase()))) {\n for (let j = 0, l = value.length; j < l; j++) {\n if (checkInvalidHeaderChar(value[j])) {\n debug(`Trailer \"${field}\"[${j}] contains invalid characters`);\n throw new ERR_INVALID_CHAR(\"trailer content\", field);\n }\n this._trailer += field + \": \" + value[j] + \"\\r\\n\";\n }\n }\n else {\n if (Array.isArray(value)) {\n value = value.join(\"; \");\n }\n if (checkInvalidHeaderChar(String(value))) {\n debug(`Trailer \"${field}\" contains invalid characters`);\n throw new ERR_INVALID_CHAR(\"trailer content\", field);\n }\n this._trailer += field + \": \" + value + \"\\r\\n\";\n }\n }\n }\n end(chunk, encoding, callback) {\n if (typeof chunk === \"function\") {\n callback = chunk;\n chunk = null;\n encoding = null;\n }\n else if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n if (chunk) {\n if (this.finished) {\n onError(this, new ERR_STREAM_WRITE_AFTER_END(), typeof callback !== \"function\" ? nop : callback);\n return this;\n }\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would also call socket.cork() at this point.\n // For our implementation we do the same for the \"written data buffer\"\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.cork();\n }\n write_(this, chunk, encoding, null, true);\n }\n else if (this.finished) {\n if (typeof callback === \"function\") {\n if (!this.writableFinished) {\n this.on(\"finish\", callback);\n }\n else {\n callback(new ERR_STREAM_ALREADY_FINISHED(\"end\"));\n }\n }\n return this;\n }\n else if (!this._header) {\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would also call socket.cork() at this point.\n // For our implementation we do the same for the \"written data buffer\"\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.cork();\n }\n this._contentLength = 0;\n this._implicitHeader();\n }\n if (typeof callback === \"function\")\n this.once(\"finish\", callback);\n if (strictContentLength(this) &&\n this[kBytesWritten] !== this._contentLength) {\n throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten], this._contentLength);\n }\n const finish = onFinish.bind(undefined, this);\n if (this._hasBody && this.chunkedEncoding) {\n // Difference from Node.js -\n // Chunked transfer encoding doesn't need to use the low-level protocol\n // (with each chunk preceded by its length)\n // So here we just send an empty chunk. Trailers are not supported\n // this._send(\"0\\r\\n\" + this._trailer + \"\\r\\n\", \"latin1\", finish);\n this._send(\"\", \"latin1\", finish);\n }\n else if (!this._headerSent || this.writableLength || chunk) {\n this._send(\"\", \"latin1\", finish);\n }\n else {\n setTimeout(finish, 0);\n }\n // Difference from Node.js -\n // In Node.js, if a socket exists, we would also call socket.uncork() at this point.\n // For our implementation we do the same for the \"written data buffer\"\n if (this._writtenDataBuffer != null) {\n this._writtenDataBuffer.uncork();\n }\n this[kCorked] = 1;\n this.uncork();\n this.finished = true;\n // There is the first message on the outgoing queue, and we've sent\n // everything to the socket.\n debug(\"outgoing message end.\");\n // Difference from Node.js -\n // In Node.js, if a socket exists, and there is no pending output data,\n // we would also call this._finish() at this point.\n // For our implementation we do the same for the \"written data buffer\"\n if (this.outputData.length === 0 && this._writtenDataBuffer != null) {\n this._finish();\n }\n return this;\n }\n _finish() {\n // Difference from Node.js -\n // In Node.js, this function is only called if a socket exists.\n // This function would assert() for a socket and then emit 'prefinish'.\n // For our implementation we do the same for the \"written data buffer\"\n this.emit(\"prefinish\");\n }\n // No _flush() implementation?\n _flush() {\n // Difference from Node.js -\n // In Node.js, this function is only called if a socket exists.\n // For our implementation we do the same for the \"written data buffer\"\n if (this._writtenDataBuffer != null) {\n // There might be remaining data in this.output; write it out\n const ret = this._flushOutput(this._writtenDataBuffer);\n if (this.finished) {\n // This is a queue to the server or client to bring in the next this.\n this._finish();\n }\n else if (ret && this[kNeedDrain]) {\n this[kNeedDrain] = false;\n this.emit(\"drain\");\n }\n }\n }\n _flushOutput(dataBuffer) {\n while (this[kCorked]) {\n this[kCorked]--;\n dataBuffer.cork();\n }\n const outputLength = this.outputData.length;\n if (outputLength <= 0) {\n return undefined;\n }\n const outputData = this.outputData;\n dataBuffer.cork();\n let ret;\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < outputLength; i++) {\n const { data, encoding, callback } = outputData[i]; // Avoid any potential ref to Buffer in new generation from old generation\n outputData[i].data = null;\n ret = dataBuffer.write(data ?? \"\", encoding, callback);\n }\n dataBuffer.uncork();\n this.outputData = [];\n this._onPendingData(-this.outputSize);\n this.outputSize = 0;\n return ret;\n }\n flushHeaders() {\n if (!this._header) {\n this._implicitHeader();\n }\n // Force-flush the headers.\n this._send(\"\");\n }\n pipe(destination) {\n // OutgoingMessage should be write-only. Piping from it is disabled.\n this.emit(\"error\", new ERR_STREAM_CANNOT_PIPE());\n return destination;\n }\n}\nfunction processHeader(self, state, key, value, validate) {\n if (validate) {\n validateHeaderName(key);\n }\n // If key is content-disposition and there is content-length\n // encode the value in latin1\n // https://www.rfc-editor.org/rfc/rfc6266#section-4.3\n // Refs: https://github.com/nodejs/node/pull/46528\n if (isContentDispositionField(key) && self._contentLength) {\n // The value could be an array here\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n value[i] = String(Buffer.from(String(value[i]), \"latin1\"));\n }\n }\n else {\n value = String(Buffer.from(String(value), \"latin1\"));\n }\n }\n if (Array.isArray(value)) {\n if ((value.length < 2 || !isCookieField(key)) &&\n (!self[kUniqueHeaders] || !self[kUniqueHeaders].has(key.toLowerCase()))) {\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < value.length; i++) {\n storeHeader(self, state, key, value[i], validate);\n }\n return;\n }\n value = value.join(\"; \");\n }\n storeHeader(self, state, key, String(value), validate);\n}\nfunction storeHeader(self, state, key, value, validate) {\n if (validate) {\n validateHeaderValue(key, value);\n }\n state.header += key + \": \" + value + \"\\r\\n\";\n matchHeader(self, state, key, value);\n}\nfunction validateHeaderName(name, label) {\n if (typeof name !== \"string\" || !name || !checkIsHttpToken(name)) {\n throw new ERR_INVALID_HTTP_TOKEN(label || \"Header name\", name);\n }\n}\nfunction validateHeaderValue(name, value) {\n if (value === undefined) {\n throw new ERR_HTTP_INVALID_HEADER_VALUE(String(value), name);\n }\n if (checkInvalidHeaderChar(String(value))) {\n debug(`Header \"${name}\" contains invalid characters`);\n throw new ERR_INVALID_CHAR(\"header content\", name);\n }\n}\nfunction matchHeader(self, state, field, value) {\n if (field.length < 4 || field.length > 17)\n return;\n field = field.toLowerCase();\n switch (field) {\n case \"connection\":\n state.connection = true;\n self._removedConnection = false;\n if (RE_CONN_CLOSE.exec(value) !== null)\n self._last = true;\n else\n self.shouldKeepAlive = true;\n break;\n case \"transfer-encoding\":\n state.te = true;\n self._removedTE = false;\n if (RE_TE_CHUNKED.exec(value) !== null)\n self.chunkedEncoding = true;\n break;\n case \"content-length\":\n state.contLen = true;\n self._contentLength = +value;\n self._removedContLen = false;\n break;\n case \"date\":\n case \"expect\":\n case \"trailer\":\n state[field] = true;\n break;\n case \"keep-alive\":\n self._defaultKeepAlive = false;\n break;\n }\n}\n// const crlf_buf = Buffer.from(\"\\r\\n\");\nfunction onError(msg, err, callback) {\n if (msg.destroyed) {\n return;\n }\n // Difference from Node.js -\n // In Node.js, we would check for the existence of a socket. If one exists, we would\n // use that async ID to scope the error.\n // Instead, we do this.\n setTimeout(emitErrorNt, 0, msg, err, callback);\n}\nfunction emitErrorNt(msg, err, callback) {\n callback(err);\n if (typeof msg.emit === \"function\" && !msg.destroyed) {\n msg.emit(\"error\", err);\n }\n}\nfunction strictContentLength(msg) {\n return (msg.strictContentLength &&\n msg._contentLength != null &&\n msg._hasBody &&\n !msg._removedContLen &&\n !msg.chunkedEncoding &&\n !msg.hasHeader(\"transfer-encoding\"));\n}\nfunction write_(msg, chunk, encoding, callback, fromEnd) {\n if (typeof callback !== \"function\") {\n callback = nop;\n }\n if (chunk === null) {\n throw new ERR_STREAM_NULL_VALUES();\n }\n else if (typeof chunk !== \"string\" && !isUint8Array(chunk)) {\n throw new ERR_INVALID_ARG_TYPE(\"chunk\", [\"string\", \"Buffer\", \"Uint8Array\"], chunk);\n }\n let err = undefined;\n if (msg.finished) {\n err = new ERR_STREAM_WRITE_AFTER_END();\n }\n else if (msg.destroyed) {\n err = new ERR_STREAM_DESTROYED(\"write\");\n }\n if (err) {\n if (!msg.destroyed) {\n onError(msg, err, callback);\n }\n else {\n setTimeout(callback, 0, err);\n }\n return false;\n }\n let len = undefined;\n if (msg.strictContentLength) {\n len ??=\n typeof chunk === \"string\"\n ? Buffer.byteLength(chunk, encoding ?? undefined)\n : chunk.byteLength;\n if (strictContentLength(msg) &&\n (fromEnd\n ? msg[kBytesWritten] + len !== msg._contentLength\n : msg[kBytesWritten] + len > (msg._contentLength ?? 0))) {\n throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(len + msg[kBytesWritten], msg._contentLength);\n }\n msg[kBytesWritten] += len;\n }\n if (!msg._header) {\n if (fromEnd) {\n len ??=\n typeof chunk === \"string\"\n ? Buffer.byteLength(chunk, encoding ?? undefined)\n : chunk.byteLength;\n msg._contentLength = len;\n }\n msg._implicitHeader();\n }\n if (!msg._hasBody) {\n if (msg[kRejectNonStandardBodyWrites]) {\n throw new ERR_HTTP_BODY_NOT_ALLOWED();\n }\n else {\n debug(\"This type of response MUST NOT have a body. \" +\n \"Ignoring write() calls.\");\n setTimeout(callback, 0);\n return true;\n }\n }\n // Difference from Node.js -\n // In Node.js, we would also check at this point if a socket exists and is not corked.\n // If so, we'd cork the socket and then queue up an 'uncork' for the next tick.\n // In our implementation we do the same for \"written data buffer\"\n if (!fromEnd &&\n msg._writtenDataBuffer != null &&\n !msg._writtenDataBuffer.writableCorked) {\n msg._writtenDataBuffer.cork();\n setTimeout(connectionCorkNT, 0, msg._writtenDataBuffer);\n }\n let ret;\n if (msg.chunkedEncoding && chunk.length !== 0) {\n len ??=\n typeof chunk === \"string\"\n ? Buffer.byteLength(chunk, encoding ?? undefined)\n : chunk.byteLength;\n if (msg[kCorked] && msg._headerSent) {\n msg[kChunkedBuffer].push({ data: chunk, encoding, callback });\n msg[kChunkedLength] += len;\n ret = msg[kChunkedLength] < msg[kHighWaterMark];\n }\n else {\n // Difference from Node.js -\n // Chunked transfer encoding doesn't need to use the low-level protocol\n // (with each chunk preceded by its length)\n // msg._send(len.toString(16), \"latin1\", null);\n // msg._send(crlf_buf, null, null);\n // msg._send(chunk, encoding, null, len);\n // ret = msg._send(crlf_buf, null, callback);\n ret = msg._send(chunk, encoding, callback, len);\n }\n }\n else {\n ret = msg._send(chunk, encoding, callback, len);\n }\n debug(\"write ret = \" + ret);\n return ret;\n}\nfunction connectionCorkNT(dataBuffer) {\n dataBuffer.uncork();\n}\nfunction onFinish(outmsg) {\n // Difference from Node.js -\n // In Node.js, if a socket exists and already had an error, we would simply return.\n outmsg.emit(\"finish\");\n}\n// Override some properties this way, because TypeScript won't let us override\n// properties with accessors.\nObject.defineProperties(FetchOutgoingMessage.prototype, {\n errored: {\n get() {\n return this[kErrored];\n },\n },\n closed: {\n get() {\n return this._closed;\n },\n },\n writableFinished: {\n get() {\n // Difference from Node.js -\n // In Node.js, there is one additional requirement --\n // there must be no underlying socket (or its writableLength must be 0).\n // In this implementation we will do the same against \"written data buffer\".\n return (this.finished &&\n this.outputSize === 0 &&\n (this._writtenDataBuffer == null ||\n this._writtenDataBuffer.writableLength === 0));\n },\n },\n writableObjectMode: {\n get() {\n return false;\n },\n },\n writableLength: {\n get() {\n // Difference from Node.js -\n // In Node.js, if a socket exists then that socket's writableLength is added to\n // this value.\n // In this implementation we will do the same against \"written data buffer\".\n return (this.outputSize +\n this[kChunkedLength] +\n (this._writtenDataBuffer != null\n ? this._writtenDataBuffer.writableLength\n : 0));\n },\n },\n writableHighWaterMark: {\n get() {\n // Difference from Node.js -\n // In Node.js, if a socket exists then use that socket's writableHighWaterMark\n // In this implementation we will do the same against \"written data buffer\".\n return this._writtenDataBuffer != null\n ? this._writtenDataBuffer.writableHighWaterMark\n : this[kHighWaterMark];\n },\n },\n writableCorked: {\n get() {\n return this[kCorked];\n },\n },\n writableEnded: {\n get() {\n return this.finished;\n },\n },\n writableNeedDrain: {\n get() {\n return !this.destroyed && !this.finished && this[kNeedDrain];\n },\n },\n});\n","/*\n * Copyright Michael Hart\n * Licensed under the MIT license. See LICENSE file for details.\n *\n * Portions of this file Copyright Fastly, Inc. See LICENSE file for details.\n * Portions of this file Copyright Joyent, Inc. and other Node contributors. See LICENSE file for details.\n */\nimport { Buffer } from \"node:buffer\";\nimport { ERR_HTTP_HEADERS_SENT, ERR_HTTP_INVALID_STATUS_CODE, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_INVALID_CHAR, ERR_METHOD_NOT_IMPLEMENTED, } from \"../utils/errors.js\";\nimport { FetchOutgoingMessage, } from \"./http-outgoing.js\";\nimport { chunkExpression } from \"./http-common.js\";\nimport { FetchIncomingMessage } from \"./http-incoming.js\";\nimport { kOutHeaders } from \"./internal-http.js\";\nimport { validateLinkHeaderValue } from \"../utils/types.js\";\n/* These items copied from Node.js: node/lib/_http_common.js. */\nconst headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n/**\n * True if val contains an invalid field-vchar\n * field-value = *( field-content / obs-fold )\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n */\nfunction checkInvalidHeaderChar(val) {\n return headerCharRegex.test(val);\n}\n// This file modeled after Node.js - node/lib/_http_server.js\nexport const STATUS_CODES = {\n 100: \"Continue\", // RFC 7231 6.2.1\n 101: \"Switching Protocols\", // RFC 7231 6.2.2\n 102: \"Processing\", // RFC 2518 10.1 (obsoleted by RFC 4918)\n 103: \"Early Hints\", // RFC 8297 2\n 200: \"OK\", // RFC 7231 6.3.1\n 201: \"Created\", // RFC 7231 6.3.2\n 202: \"Accepted\", // RFC 7231 6.3.3\n 203: \"Non-Authoritative Information\", // RFC 7231 6.3.4\n 204: \"No Content\", // RFC 7231 6.3.5\n 205: \"Reset Content\", // RFC 7231 6.3.6\n 206: \"Partial Content\", // RFC 7233 4.1\n 207: \"Multi-Status\", // RFC 4918 11.1\n 208: \"Already Reported\", // RFC 5842 7.1\n 226: \"IM Used\", // RFC 3229 10.4.1\n 300: \"Multiple Choices\", // RFC 7231 6.4.1\n 301: \"Moved Permanently\", // RFC 7231 6.4.2\n 302: \"Found\", // RFC 7231 6.4.3\n 303: \"See Other\", // RFC 7231 6.4.4\n 304: \"Not Modified\", // RFC 7232 4.1\n 305: \"Use Proxy\", // RFC 7231 6.4.5\n 307: \"Temporary Redirect\", // RFC 7231 6.4.7\n 308: \"Permanent Redirect\", // RFC 7238 3\n 400: \"Bad Request\", // RFC 7231 6.5.1\n 401: \"Unauthorized\", // RFC 7235 3.1\n 402: \"Payment Required\", // RFC 7231 6.5.2\n 403: \"Forbidden\", // RFC 7231 6.5.3\n 404: \"Not Found\", // RFC 7231 6.5.4\n 405: \"Method Not Allowed\", // RFC 7231 6.5.5\n 406: \"Not Acceptable\", // RFC 7231 6.5.6\n 407: \"Proxy Authentication Required\", // RFC 7235 3.2\n 408: \"Request Timeout\", // RFC 7231 6.5.7\n 409: \"Conflict\", // RFC 7231 6.5.8\n 410: \"Gone\", // RFC 7231 6.5.9\n 411: \"Length Required\", // RFC 7231 6.5.10\n 412: \"Precondition Failed\", // RFC 7232 4.2\n 413: \"Payload Too Large\", // RFC 7231 6.5.11\n 414: \"URI Too Long\", // RFC 7231 6.5.12\n 415: \"Unsupported Media Type\", // RFC 7231 6.5.13\n 416: \"Range Not Satisfiable\", // RFC 7233 4.4\n 417: \"Expectation Failed\", // RFC 7231 6.5.14\n 418: \"I'm a Teapot\", // RFC 7168 2.3.3\n 421: \"Misdirected Request\", // RFC 7540 9.1.2\n 422: \"Unprocessable Entity\", // RFC 4918 11.2\n 423: \"Locked\", // RFC 4918 11.3\n 424: \"Failed Dependency\", // RFC 4918 11.4\n 425: \"Too Early\", // RFC 8470 5.2\n 426: \"Upgrade Required\", // RFC 2817 and RFC 7231 6.5.15\n 428: \"Precondition Required\", // RFC 6585 3\n 429: \"Too Many Requests\", // RFC 6585 4\n 431: \"Request Header Fields Too Large\", // RFC 6585 5\n 451: \"Unavailable For Legal Reasons\", // RFC 7725 3\n 500: \"Internal Server Error\", // RFC 7231 6.6.1\n 501: \"Not Implemented\", // RFC 7231 6.6.2\n 502: \"Bad Gateway\", // RFC 7231 6.6.3\n 503: \"Service Unavailable\", // RFC 7231 6.6.4\n 504: \"Gateway Timeout\", // RFC 7231 6.6.5\n 505: \"HTTP Version Not Supported\", // RFC 7231 6.6.6\n 506: \"Variant Also Negotiates\", // RFC 2295 8.1\n 507: \"Insufficient Storage\", // RFC 4918 11.5\n 508: \"Loop Detected\", // RFC 5842 7.2\n 509: \"Bandwidth Limit Exceeded\",\n 510: \"Not Extended\", // RFC 2774 7\n 511: \"Network Authentication Required\", // RFC 6585 6\n};\n/**\n * This is an implementation of ServerResponse from Node.js intended to run in\n * a WinterTC runtime. The 'Writable' interface of this class is wired to an in-memory\n * buffer. This class also provides a method that creates a Response object that\n * can be handled by the runtime.\n *\n * This instance can be used in normal ways, but it does not give access to the\n * underlying socket (because there isn't one. req.socket will always return null).\n *\n * Some code in this class is transplanted/adapted from node/lib/_httpserver.js\n *\n * NOTE: Node.js doesn't really separate the body from headers, the entire \"stream\"\n * contains the headers and the body. So we provide functions that lets us pull\n * the headers and body out individually at a later time.\n */\nexport class FetchServerResponse extends FetchOutgoingMessage {\n static encoder = new TextEncoder();\n statusCode = 200;\n statusMessage;\n _sent100;\n _expect_continue;\n [kOutHeaders] = null;\n constructor(req, options) {\n super(req, options);\n if (req.method === \"HEAD\") {\n this._hasBody = false;\n }\n // this.req = req; // super() actually does this\n this.sendDate = true;\n this._sent100 = false;\n this._expect_continue = false;\n if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) {\n this.useChunkedEncodingByDefault =\n chunkExpression.exec(String(req.headers.te)) !== null;\n this.shouldKeepAlive = false;\n }\n // Difference from Node.js -\n // In Node.js, in addition to the above, we would check if an observer is enabled for\n // http, and if it is, we would start performance measurement of server response statistics.\n this.fetchResponse = new Promise((resolve) => {\n let finished = false;\n this.on(\"finish\", () => {\n finished = true;\n });\n const initialDataChunks = [];\n const initialDataWrittenHandler = (e) => {\n if (finished) {\n return;\n }\n initialDataChunks[e.index] = this.dataFromDataWrittenEvent(e);\n };\n this.on(\"_dataWritten\", initialDataWrittenHandler);\n this.on(\"_headersSent\", (e) => {\n this.off(\"_dataWritten\", initialDataWrittenHandler);\n // Convert the response object to a Response object and return it\n const { statusCode, statusMessage, headers } = e;\n resolve(this._toFetchResponse(statusCode, statusMessage, headers, initialDataChunks, finished));\n });\n });\n }\n dataFromDataWrittenEvent(e) {\n const { index, entry } = e;\n let { data, encoding } = entry;\n if (index === 0) {\n if (typeof data !== \"string\") {\n console.error(\"First chunk should be string, not sure what happened.\");\n throw new ERR_INVALID_ARG_TYPE(\"packet.data\", [\"string\", \"Buffer\", \"Uint8Array\"], data);\n }\n // The first X bytes are header material, so we remove it.\n data = data.slice(this.writtenHeaderBytes);\n }\n if (typeof data === \"string\") {\n if (encoding === undefined ||\n encoding === \"utf8\" ||\n encoding === \"utf-8\") {\n data = FetchServerResponse.encoder.encode(data);\n }\n else {\n data = Buffer.from(data, encoding ?? undefined);\n }\n }\n return data ?? Buffer.from([]);\n }\n _finish() {\n // Difference from Node.js -\n // In Node.js, if server response statistics performance is being measured, we would stop it.\n super._finish();\n }\n assignSocket(socket) {\n // Difference from Node.js -\n // Socket is not supported\n throw new ERR_METHOD_NOT_IMPLEMENTED(\"assignSocket\");\n }\n detachSocket(socket) {\n // Difference from Node.js -\n // Socket is not supported\n throw new ERR_METHOD_NOT_IMPLEMENTED(\"detachSocket\");\n }\n writeContinue(callback) {\n this._writeRaw(\"HTTP/1.1 100 Continue\\r\\n\\r\\n\", \"ascii\", callback);\n this._sent100 = true;\n }\n writeProcessing(callback) {\n this._writeRaw(\"HTTP/1.1 102 Processing\\r\\n\\r\\n\", \"ascii\", callback);\n }\n writeEarlyHints(hints, callback) {\n let head = \"HTTP/1.1 103 Early Hints\\r\\n\";\n // Difference from Node.js -\n // In Node.js, we would validate the hints object here.\n // validateObject(hints, 'hints');\n if (hints.link === null || hints.link === undefined) {\n return;\n }\n const link = validateLinkHeaderValue(hints.link);\n if (link.length === 0) {\n return;\n }\n head += \"Link: \" + link + \"\\r\\n\";\n for (const key of Object.keys(hints)) {\n if (key !== \"link\") {\n head += key + \": \" + hints[key] + \"\\r\\n\";\n }\n }\n head += \"\\r\\n\";\n this._writeRaw(head, \"ascii\", callback);\n }\n _implicitHeader() {\n this.writeHead(this.statusCode);\n }\n writeHead(statusCode, reason, obj) {\n if (this._header) {\n throw new ERR_HTTP_HEADERS_SENT(\"write\");\n }\n const originalStatusCode = statusCode;\n statusCode |= 0;\n if (statusCode < 100 || statusCode > 999) {\n throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);\n }\n if (typeof reason === \"string\") {\n // writeHead(statusCode, reasonPhrase[, headers])\n this.statusMessage = reason;\n }\n else {\n // writeHead(statusCode[, headers])\n this.statusMessage ||= STATUS_CODES[statusCode] || \"unknown\";\n obj ??= reason;\n }\n this.statusCode = statusCode;\n let headers;\n if (this[kOutHeaders]) {\n // Slow-case: when progressive API and header fields are passed.\n let k;\n if (Array.isArray(obj)) {\n if (obj.length % 2 !== 0) {\n throw new ERR_INVALID_ARG_VALUE(\"headers\", obj);\n }\n // Headers in obj should override previous headers but still\n // allow explicit duplicates. To do so, we first remove any\n // existing conflicts, then use appendHeader.\n for (let n = 0; n < obj.length; n += 2) {\n k = obj[n + 0];\n this.removeHeader(String(k));\n }\n for (let n = 0; n < obj.length; n += 2) {\n k = obj[n];\n if (k) {\n this.appendHeader(String(k), obj[n + 1]);\n }\n }\n }\n else if (obj) {\n const keys = Object.keys(obj);\n // Retain for(;;) loop for performance reasons\n // Refs: https://github.com/nodejs/node/pull/30958\n for (let i = 0; i < keys.length; i++) {\n k = keys[i];\n if (k) {\n this.setHeader(k, obj[k]);\n }\n }\n }\n // Only progressive api is used\n headers = this[kOutHeaders];\n }\n else {\n // Only writeHead() called\n headers = obj;\n }\n if (checkInvalidHeaderChar(this.statusMessage)) {\n throw new ERR_INVALID_CHAR(\"statusMessage\");\n }\n const statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}\\r\\n`;\n if (statusCode === 204 ||\n statusCode === 304 ||\n (statusCode >= 100 && statusCode <= 199)) {\n // RFC 2616, 10.2.5:\n // The 204 response MUST NOT include a message-body, and thus is always\n // terminated by the first empty line after the header fields.\n // RFC 2616, 10.3.5:\n // The 304 response MUST NOT contain a message-body, and thus is always\n // terminated by the first empty line after the header fields.\n // RFC 2616, 10.1 Informational 1xx:\n // This class of status code indicates a provisional response,\n // consisting only of the Status-Line and optional headers, and is\n // terminated by an empty line.\n this._hasBody = false;\n }\n // Don't keep alive connections where the client expects 100 Continue\n // but we sent a final status; they may put extra bytes on the wire.\n if (this._expect_continue && !this._sent100) {\n this.shouldKeepAlive = false;\n }\n // Convert headers to a compatible type for _storeHeader\n const convertedHeaders = headers && !Array.isArray(headers)\n ? headers\n : headers;\n this._storeHeader(statusLine, convertedHeaders ?? null);\n return this;\n }\n // Docs-only deprecated: DEP0063\n writeHeader = this.writeHead;\n fetchResponse;\n _toFetchResponse(status, statusText, sentHeaders, initialDataChunks, finished) {\n const headers = new Headers();\n for (const [header, value] of sentHeaders) {\n headers.append(header, value);\n }\n const _this = this;\n let body = this._hasBody\n ? new ReadableStream({\n start(controller) {\n for (const dataChunk of initialDataChunks) {\n controller.enqueue(dataChunk);\n }\n if (finished) {\n controller.close();\n }\n else {\n _this.on(\"finish\", () => {\n finished = true;\n controller.close();\n });\n _this.on(\"_dataWritten\", (e) => {\n if (finished) {\n return;\n }\n const data = _this.dataFromDataWrittenEvent(e);\n controller.enqueue(data);\n });\n }\n },\n })\n : null;\n // @ts-expect-error this is (currently) a cloudflare-specific class\n if (body != null && typeof FixedLengthStream !== \"undefined\") {\n const contentLength = parseInt(headers.get(\"content-length\") ?? \"\", 10); // will be NaN if not set\n if (contentLength >= 0) {\n // @ts-expect-error this is (currently) a cloudflare-specific class\n body = body.pipeThrough(new FixedLengthStream(contentLength));\n }\n }\n return new Response(body, {\n status,\n statusText,\n headers,\n });\n }\n}\nexport function toReqRes(req, options) {\n const { createIncomingMessage = () => new FetchIncomingMessage(), createServerResponse = (incoming) => new FetchServerResponse(incoming), ctx, } = options ?? {};\n const incoming = createIncomingMessage(ctx);\n const serverResponse = createServerResponse(incoming, ctx);\n const reqUrl = new URL(req.url);\n const versionMajor = 1;\n const versionMinor = 1;\n incoming.httpVersionMajor = versionMajor;\n incoming.httpVersionMinor = versionMinor;\n incoming.httpVersion = `${versionMajor}.${versionMinor}`;\n incoming.url = reqUrl.pathname + reqUrl.search;\n incoming.upgrade = false;\n const headers = [];\n for (const [headerName, headerValue] of req.headers) {\n headers.push(headerName);\n headers.push(headerValue);\n }\n incoming._addHeaderLines(headers, headers.length);\n incoming.method = req.method;\n incoming._stream = req.body;\n return {\n req: incoming,\n res: serverResponse,\n };\n}\nexport function toFetchResponse(res) {\n if (!(res instanceof FetchServerResponse)) {\n throw new Error(\"toFetchResponse must be called on a ServerResponse generated by toReqRes\");\n }\n return res.fetchResponse;\n}\n","import { MASTRA_FRAMEWORK_PUBLIC_KEY, MASTRA_FRAMEWORK_PUBLIC_KEY as MASTRA_FRAMEWORK_PUBLIC_KEY$1, MastraServer as MastraServer$1, checkRouteFGA, isZodError, normalizeQueryParams, redactStreamChunk, serializeStreamChunk } from \"@mastra/server/server-adapter\";\nimport { toFetchResponse, toReqRes } from \"fetch-to-node\";\nimport { bodyLimit } from \"hono/body-limit\";\nimport { stream } from \"hono/streaming\";\nimport { RequestContext } from \"@mastra/core/request-context\";\nimport { coreAuthMiddleware } from \"@mastra/server/auth\";\nimport { ViewerRegistry, handleInputMessage } from \"@mastra/server/browser-stream\";\n//#region src/mcp-disconnect.ts\n/**\n* Propagates a client disconnect to the simulated Node response produced by `toReqRes`.\n*\n* `fetch-to-node` builds the outgoing body from `res` events but never observes cancellation\n* of the stream it hands back. When an MCP Streamable HTTP client drops its session, nothing\n* tells `res` that the socket is gone, so the MCP transport keeps its SSE keep-alive timer\n* armed. The next keep-alive tick writes into an already-closed stream controller, and because\n* that write originates in a timer callback the resulting `ERR_INVALID_STATE` is unhandled and\n* takes down the process.\n*\n* Emitting `close` on `res` is the signal the MCP Node transport listens for: it aborts the\n* request's AbortController, which breaks the write loop and tears down the SSE stream,\n* clearing the keep-alive timer. No post-disconnect write is ever attempted.\n*/\nfunction propagateClientDisconnect(fetchResponse, res) {\n\tconst upstream = fetchResponse.body;\n\tif (!upstream) return fetchResponse;\n\tlet disconnected = false;\n\tconst disconnect = () => {\n\t\tif (disconnected) return;\n\t\tdisconnected = true;\n\t\ttry {\n\t\t\tres.emit(\"close\");\n\t\t} catch {}\n\t\treader.read().then(function drain({ done }) {\n\t\t\treturn done ? void 0 : reader.read().then(drain);\n\t\t}, () => {});\n\t};\n\tconst reader = upstream.getReader();\n\tconst body = new ReadableStream({\n\t\tasync pull(controller) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tcontroller.close();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontroller.enqueue(value);\n\t\t},\n\t\tcancel() {\n\t\t\tdisconnect();\n\t\t}\n\t});\n\treturn new Response(body, {\n\t\tstatus: fetchResponse.status,\n\t\tstatusText: fetchResponse.statusText,\n\t\theaders: fetchResponse.headers\n\t});\n}\n//#endregion\n//#region src/auth-middleware.ts\nfunction createAuthMiddleware({ mastra, requiresAuth = true }) {\n\treturn async (c, next) => {\n\t\tif (!requiresAuth) return next();\n\t\tconst authConfig = mastra.getServer()?.auth;\n\t\tif (!authConfig) return next();\n\t\tconst requestContext = c.get(\"requestContext\") ?? new RequestContext();\n\t\tc.set(\"requestContext\", requestContext);\n\t\tc.set(\"mastra\", c.get(\"mastra\") ?? mastra);\n\t\tconst path = c.req.path;\n\t\tconst method = c.req.method;\n\t\tconst customRouteAuthConfig = new Map(c.get(\"customRouteAuthConfig\") ?? []);\n\t\tcustomRouteAuthConfig.set(`${method}:${path}`, true);\n\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\tlet token = authHeader ? authHeader.replace(\"Bearer \", \"\") : null;\n\t\tif (!token) token = c.req.query(\"apiKey\") || null;\n\t\tconst result = await coreAuthMiddleware({\n\t\t\tpath,\n\t\t\tmethod,\n\t\t\tgetHeader: (name) => c.req.header(name),\n\t\t\tmastra,\n\t\t\tauthConfig,\n\t\t\tcustomRouteAuthConfig,\n\t\t\trequestContext,\n\t\t\trawRequest: c.req.raw,\n\t\t\ttoken,\n\t\t\tbuildAuthorizeContext: () => c\n\t\t});\n\t\tif (result.action === \"next\") return next();\n\t\treturn c.json(result.body, result.status);\n\t};\n}\n//#endregion\n//#region src/browser-stream/index.ts\n/**\n* Set up WebSocket-based browser stream endpoint for real-time screencast viewing.\n*\n* Creates a WebSocket route at `/browser/:agentId/stream` that:\n* - Accepts viewer connections\n* - Starts screencast when first viewer connects\n* - Broadcasts frames to all connected viewers\n* - Stops screencast when last viewer disconnects\n*\n* **Note**: Requires `ws` package to be installed. If not available, returns null\n* and logs a warning. Browser streaming will be disabled but everything else works.\n*\n* @param app - The Hono application instance\n* @param config - Configuration for browser stream\n* @returns Object containing injectWebSocket function and registry instance, or null if ws is not available\n*\n* @example\n* ```typescript\n* import { Hono } from 'hono';\n* import { serve } from '@hono/node-server';\n* import { setupBrowserStream } from '@mastra/hono';\n*\n* const app = new Hono();\n* const browserStream = await setupBrowserStream(app, {\n* getToolset: (agentId) => browserToolsets.get(agentId),\n* });\n*\n* const server = serve({ fetch: app.fetch, port: 4111 });\n* browserStream?.injectWebSocket(server);\n* ```\n*/\nasync function setupBrowserStream(app, config) {\n\tlet createNodeWebSocket;\n\ttry {\n\t\tcreateNodeWebSocket = (await import(\n\t\t\t/* @vite-ignore */\n\t\t\t/* webpackIgnore: true */\n\t\t\t\"@hono/node-ws\"\n)).createNodeWebSocket;\n\t} catch {\n\t\treturn null;\n\t}\n\tconst { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });\n\tconst registry = new ViewerRegistry();\n\tconst rawPrefix = config.apiPrefix ?? \"/api\";\n\tconst apiPrefix = (rawPrefix.endsWith(\"/\") ? rawPrefix.slice(0, -1) : rawPrefix) || \"/api\";\n\tapp.get(\"/browser/:agentId/stream\", upgradeWebSocket((c) => {\n\t\tconst agentId = c.req.param(\"agentId\");\n\t\tconst threadId = c.req.query(\"threadId\");\n\t\tconst viewerKey = threadId ? `${agentId}:${threadId}` : agentId;\n\t\treturn {\n\t\t\tonOpen(_event, ws) {\n\t\t\t\tws.send(JSON.stringify({ status: \"connected\" }));\n\t\t\t\tregistry.addViewer(viewerKey, ws, config.getToolset, agentId, threadId);\n\t\t\t},\n\t\t\tonMessage(event, _ws) {\n\t\t\t\tconst data = typeof event.data === \"string\" ? event.data : null;\n\t\t\t\tif (data) handleInputMessage(data, config.getToolset, agentId, threadId);\n\t\t\t},\n\t\t\tonClose(_event, ws) {\n\t\t\t\tregistry.removeViewer(viewerKey, ws);\n\t\t\t},\n\t\t\tonError(event, ws) {\n\t\t\t\tconsole.error(\"[BrowserStream] WebSocket error:\", event);\n\t\t\t\tregistry.removeViewer(viewerKey, ws);\n\t\t\t}\n\t\t};\n\t}));\n\tapp.get(`${apiPrefix}/agents/:agentId/browser/session`, async (c) => {\n\t\tconst agentId = c.req.param(\"agentId\");\n\t\tif (!agentId) return c.json({ error: \"Agent ID is required\" }, 400);\n\t\tconst threadId = c.req.query(\"threadId\");\n\t\tconst toolset = await config.getToolset(agentId);\n\t\tif (!toolset) return c.json({\n\t\t\thasSession: false,\n\t\t\tscreencastAvailable: true\n\t\t});\n\t\tconst hasSession = threadId ? toolset.hasThreadSession(threadId) : false;\n\t\treturn c.json({\n\t\t\thasSession,\n\t\t\tscreencastAvailable: true\n\t\t});\n\t});\n\tapp.post(`${apiPrefix}/agents/:agentId/browser/close`, async (c) => {\n\t\tconst agentId = c.req.param(\"agentId\");\n\t\tif (!agentId) return c.json({ error: \"Agent ID is required\" }, 400);\n\t\tconst toolset = await config.getToolset(agentId);\n\t\tif (!toolset) return c.json({ error: \"No browser session for this agent\" }, 404);\n\t\ttry {\n\t\t\tlet threadId;\n\t\t\ttry {\n\t\t\t\tthreadId = (await c.req.json())?.threadId;\n\t\t\t} catch {}\n\t\t\tconst scope = toolset.getScope();\n\t\t\tconst viewerKey = threadId ? `${agentId}:${threadId}` : agentId;\n\t\t\tif (scope === \"thread\" && threadId) {\n\t\t\t\tawait registry.closeBrowserSession(viewerKey);\n\t\t\t\tif (\"closeThreadSession\" in toolset && typeof toolset.closeThreadSession === \"function\") await toolset.closeThreadSession(threadId);\n\t\t\t} else {\n\t\t\t\tawait registry.closeBrowserSession(viewerKey);\n\t\t\t\tawait toolset.close();\n\t\t\t}\n\t\t\treturn c.json({ success: true });\n\t\t} catch (error) {\n\t\t\tconsole.error(`[BrowserStream] Error closing browser for ${agentId}:`, error);\n\t\t\treturn c.json({ error: \"Failed to close browser\" }, 500);\n\t\t}\n\t});\n\treturn {\n\t\tinjectWebSocket,\n\t\tregistry\n\t};\n}\n//#endregion\n//#region src/index.ts\nlet _hasPermissionPromise;\nfunction loadHasPermission() {\n\tif (!_hasPermissionPromise) _hasPermissionPromise = import(\"@mastra/core/auth/ee\").then((m) => m.hasPermission).catch(() => {\n\t\tconsole.error(\"[@mastra/hono] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest\");\n\t});\n\treturn _hasPermissionPromise;\n}\n/**\n* Wrap a Hono middleware handler so it becomes a no-op for framework-public\n* routes (routes registered with `requiresAuth: false`).\n*\n* Adapters that expose user-provided middleware — for example `serverMiddleware`\n* on the Mastra instance or `server.middleware` in Mastra config — MUST wrap\n* those handlers with this before registering them. This is the framework's\n* guarantee that user middleware cannot accidentally (or intentionally) 401\n* routes the framework needs to keep reachable (e.g. Studio sign-in endpoints).\n*\n* The framework-public flag is computed once per request by\n* {@link MastraServer.registerContextMiddleware} and stashed on the Hono\n* context under `MASTRA_FRAMEWORK_PUBLIC_KEY`.\n*/\nconst skipIfFrameworkPublic = (handler) => {\n\treturn async (c, next) => {\n\t\tif (c.get(MASTRA_FRAMEWORK_PUBLIC_KEY$1)) return next();\n\t\treturn handler(c, next);\n\t};\n};\nvar MastraServer = class extends MastraServer$1 {\n\tcreateContextMiddleware() {\n\t\treturn async (c, next) => {\n\t\t\tconst originalJson = c.req.json.bind(c.req);\n\t\t\tlet jsonPromise;\n\t\t\tc.req.json = () => {\n\t\t\t\tif (!jsonPromise) jsonPromise = originalJson().then((body) => {\n\t\t\t\t\tc.set(\"cachedBody\", body);\n\t\t\t\t\treturn body;\n\t\t\t\t});\n\t\t\t\treturn jsonPromise;\n\t\t\t};\n\t\t\tlet bodyRequestContext;\n\t\t\tlet paramsRequestContext;\n\t\t\tif (c.req.method === \"POST\" || c.req.method === \"PUT\") {\n\t\t\t\tconst contentType = c.req.header(\"content-type\");\n\t\t\t\tconst contentLength = c.req.header(\"content-length\");\n\t\t\t\tif (contentType?.includes(\"application/json\") && contentLength !== \"0\") try {\n\t\t\t\t\tconst body = await c.req.raw.clone().json();\n\t\t\t\t\tif (body.requestContext) bodyRequestContext = body.requestContext;\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tif (c.req.method === \"GET\") try {\n\t\t\t\tconst encodedRequestContext = c.req.query(\"requestContext\");\n\t\t\t\tif (encodedRequestContext) try {\n\t\t\t\t\tparamsRequestContext = JSON.parse(encodedRequestContext);\n\t\t\t\t} catch {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst json = Buffer.from(encodedRequestContext, \"base64\").toString(\"utf-8\");\n\t\t\t\t\t\tparamsRequestContext = JSON.parse(json);\n\t\t\t\t\t} catch {}\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t\tconst requestContext = this.mergeRequestContext({\n\t\t\t\tparamsRequestContext,\n\t\t\t\tbodyRequestContext\n\t\t\t});\n\t\t\tthis.applyRequestMetadataToContext({\n\t\t\t\trequestContext,\n\t\t\t\tgetHeader: (name) => c.req.header(name)\n\t\t\t});\n\t\t\tc.set(\"requestContext\", requestContext);\n\t\t\tc.set(\"mastra\", this.mastra);\n\t\t\tc.set(\"registeredTools\", this.tools || {});\n\t\t\tc.set(\"taskStore\", this.taskStore);\n\t\t\tc.set(\"abortSignal\", c.req.raw.signal);\n\t\t\tc.set(\"customRouteAuthConfig\", this.customRouteAuthConfig);\n\t\t\treturn next();\n\t\t};\n\t}\n\tasync stream(route, res, result) {\n\t\tconst streamFormat = route.streamFormat || \"stream\";\n\t\tif (streamFormat === \"sse\") {\n\t\t\tres.header(\"Content-Type\", \"text/event-stream\");\n\t\t\tres.header(\"Cache-Control\", \"no-cache\");\n\t\t\tres.header(\"Connection\", \"keep-alive\");\n\t\t\tres.header(\"X-Accel-Buffering\", \"no\");\n\t\t} else res.header(\"Content-Type\", \"text/plain\");\n\t\tres.header(\"Transfer-Encoding\", \"chunked\");\n\t\treturn stream(res, async (stream) => {\n\t\t\tif (streamFormat === \"sse\" && route.sseFlushOnConnect) await stream.write(\": connected\\n\\n\");\n\t\t\tconst reader = (result instanceof ReadableStream ? result : result.fullStream).getReader();\n\t\t\tstream.onAbort(() => {\n\t\t\t\treader.cancel(\"request aborted\").catch(() => {});\n\t\t\t});\n\t\t\ttry {\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\tif (streamFormat === \"sse\" && typeof value === \"string\" && value.startsWith(\":\")) {\n\t\t\t\t\t\t\tawait stream.write(value);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst outputValue = this.streamOptions?.redact ?? true ? redactStreamChunk(value) : value;\n\t\t\t\t\t\tconst serialized = serializeStreamChunk(outputValue);\n\t\t\t\t\t\tif (!serialized.ok) {\n\t\t\t\t\t\t\tthis.mastra.getLogger()?.error(\"Failed to serialize stream chunk, skipping\", {\n\t\t\t\t\t\t\t\tpath: route.path,\n\t\t\t\t\t\t\t\tchunkType: outputValue?.type,\n\t\t\t\t\t\t\t\terror: serialized.error.message\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (streamFormat === \"sse\") await stream.write(`data: ${serialized.json}\\n\\n`);\n\t\t\t\t\t\telse await stream.write(serialized.json + \"\u001e\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (streamFormat === \"sse\") await stream.write(\"data: [DONE]\\n\\n\");\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Error in stream processing\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t} finally {\n\t\t\t\tawait stream.close();\n\t\t\t}\n\t\t}, async (err) => {\n\t\t\tthis.mastra.getLogger()?.error(\"Stream error callback\", { error: err instanceof Error ? {\n\t\t\t\tmessage: err.message,\n\t\t\t\tstack: err.stack\n\t\t\t} : err });\n\t\t});\n\t}\n\tasync getParams(route, request) {\n\t\tconst urlParams = request.param();\n\t\tconst queryParams = normalizeQueryParams(request.queries());\n\t\tlet body;\n\t\tlet bodyParseError;\n\t\tif (route.method === \"POST\" || route.method === \"PUT\" || route.method === \"PATCH\" || route.method === \"DELETE\") {\n\t\t\tconst contentType = request.header(\"content-type\") || \"\";\n\t\t\tif (contentType.includes(\"multipart/form-data\")) try {\n\t\t\t\tconst formData = await request.formData();\n\t\t\t\tbody = await this.parseFormData(formData);\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Failed to parse multipart form data\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t\tif (error instanceof Error && error.message.toLowerCase().includes(\"size\")) throw error;\n\t\t\t\tbodyParseError = { message: error instanceof Error ? error.message : \"Failed to parse multipart form data\" };\n\t\t\t}\n\t\t\telse if (contentType.includes(\"application/json\")) {\n\t\t\t\tconst bodyText = await request.raw.clone().text();\n\t\t\t\tif (bodyText && bodyText.trim().length > 0) try {\n\t\t\t\t\tbody = JSON.parse(bodyText);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.mastra.getLogger()?.error(\"Failed to parse JSON body\", { error: error instanceof Error ? {\n\t\t\t\t\t\tmessage: error.message,\n\t\t\t\t\t\tstack: error.stack\n\t\t\t\t\t} : error });\n\t\t\t\t\tbodyParseError = { message: error instanceof Error ? error.message : \"Invalid JSON in request body\" };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\turlParams,\n\t\t\tqueryParams,\n\t\t\tbody,\n\t\t\tbodyParseError\n\t\t};\n\t}\n\t/**\n\t* Parse FormData into a plain object, converting File objects to Buffers.\n\t*/\n\tasync parseFormData(formData) {\n\t\tconst result = {};\n\t\tfor (const [key, value] of formData.entries()) if (value instanceof File) {\n\t\t\tconst arrayBuffer = await value.arrayBuffer();\n\t\t\tresult[key] = Buffer.from(arrayBuffer);\n\t\t} else if (typeof value === \"string\") try {\n\t\t\tresult[key] = JSON.parse(value);\n\t\t} catch {\n\t\t\tresult[key] = value;\n\t\t}\n\t\telse result[key] = value;\n\t\treturn result;\n\t}\n\tasync sendResponse(route, response, result, prefix) {\n\t\tconst resolvedPrefix = prefix ?? this.prefix ?? \"\";\n\t\tif (result && typeof result === \"object\" && \"__refreshHeaders\" in result) {\n\t\t\tconst refreshHeaders = result.__refreshHeaders;\n\t\t\tfor (const [key, value] of Object.entries(refreshHeaders)) response.header(key, value);\n\t\t\tdelete result.__refreshHeaders;\n\t\t}\n\t\tif (route.responseType === \"json\") return response.json(result, 200);\n\t\telse if (route.responseType === \"stream\") return this.stream(route, response, result);\n\t\telse if (route.responseType === \"datastream-response\") return result;\n\t\telse if (route.responseType === \"mcp-http\") {\n\t\t\tconst { server, httpPath, mcpOptions: routeMcpOptions } = result;\n\t\t\tconst { req, res } = toReqRes(response.req.raw);\n\t\t\tconst options = {\n\t\t\t\t...this.mcpOptions,\n\t\t\t\t...routeMcpOptions\n\t\t\t};\n\t\t\tserver.startHTTP({\n\t\t\t\turl: new URL(response.req.url),\n\t\t\t\thttpPath: `${resolvedPrefix}${httpPath}`,\n\t\t\t\treq,\n\t\t\t\tres,\n\t\t\t\toptions: Object.keys(options).length > 0 ? options : void 0\n\t\t\t}).catch((e) => {\n\t\t\t\tthis.mastra.getLogger()?.error(\"[MCP HTTP] Error in background startHTTP:\", { error: e instanceof Error ? {\n\t\t\t\t\tmessage: e.message,\n\t\t\t\t\tstack: e.stack\n\t\t\t\t} : e });\n\t\t\t\ttry {\n\t\t\t\t\tif (!res.headersSent) {\n\t\t\t\t\t\tres.writeHead(500, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\tres.end(JSON.stringify({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: -32603,\n\t\t\t\t\t\t\t\tmessage: \"Internal server error\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tid: null\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\t\t\t\t} catch {}\n\t\t\t});\n\t\t\treturn propagateClientDisconnect(await toFetchResponse(res), res);\n\t\t} else if (route.responseType === \"mcp-sse\") {\n\t\t\tconst { server, ssePath, messagePath } = result;\n\t\t\ttry {\n\t\t\t\treturn await server.startHonoSSE({\n\t\t\t\t\turl: new URL(response.req.url),\n\t\t\t\t\tssePath: `${resolvedPrefix}${ssePath}`,\n\t\t\t\t\tmessagePath: `${resolvedPrefix}${messagePath}`,\n\t\t\t\t\tcontext: response\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\treturn response.json({ error: \"Error handling MCP SSE request\" }, 500);\n\t\t\t}\n\t\t} else return response.status(500);\n\t}\n\tasync registerRoute(app, route, { prefix: prefixParam } = {}) {\n\t\tconst prefix = prefixParam ?? this.prefix ?? \"\";\n\t\tconst shouldApplyBodyLimit = this.bodyLimitOptions && [\n\t\t\t\"POST\",\n\t\t\t\"PUT\",\n\t\t\t\"PATCH\",\n\t\t\t\"DELETE\"\n\t\t].includes(route.method.toUpperCase());\n\t\tconst maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n\t\tconst middlewares = [];\n\t\tif (shouldApplyBodyLimit && maxSize && this.bodyLimitOptions) {\n\t\t\tconst { onError } = this.bodyLimitOptions;\n\t\t\tmiddlewares.push(bodyLimit({\n\t\t\t\tmaxSize,\n\t\t\t\tonError: (c) => c.json(onError({ error: \"Request body too large\" }), 413)\n\t\t\t}));\n\t\t}\n\t\tapp[route.method.toLowerCase()](`${prefix}${route.path}`, ...middlewares, async (c) => {\n\t\t\tconst authResult = await this.checkRouteAuth(route, {\n\t\t\t\tpath: c.req.path,\n\t\t\t\tmethod: c.req.method,\n\t\t\t\tgetHeader: (name) => c.req.header(name),\n\t\t\t\tgetQuery: (name) => c.req.query(name),\n\t\t\t\trequestContext: c.get(\"requestContext\"),\n\t\t\t\trequest: c.req.raw,\n\t\t\t\tbuildAuthorizeContext: () => c\n\t\t\t});\n\t\t\tif (authResult) {\n\t\t\t\tif (authResult.headers) for (const [key, value] of Object.entries(authResult.headers)) c.header(key, value);\n\t\t\t\tif (authResult.error) return c.json({ error: authResult.error }, authResult.status);\n\t\t\t}\n\t\t\tconst params = await this.getParams(route, c.req);\n\t\t\tif (params.bodyParseError) return c.json({\n\t\t\t\terror: \"Invalid request body\",\n\t\t\t\tissues: [{\n\t\t\t\t\tfield: \"body\",\n\t\t\t\t\tmessage: params.bodyParseError.message\n\t\t\t\t}]\n\t\t\t}, 400);\n\t\t\tif (params.queryParams) try {\n\t\t\t\tparams.queryParams = await this.parseQueryParams(route, params.queryParams);\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Error parsing query params\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t\tif (isZodError(error)) {\n\t\t\t\t\tconst { status, body } = this.resolveValidationError(route, error, \"query\");\n\t\t\t\t\treturn c.json(body, status);\n\t\t\t\t}\n\t\t\t\treturn c.json({\n\t\t\t\t\terror: \"Invalid query parameters\",\n\t\t\t\t\tissues: [{\n\t\t\t\t\t\tfield: \"unknown\",\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t\t}]\n\t\t\t\t}, 400);\n\t\t\t}\n\t\t\tif (params.body) try {\n\t\t\t\tparams.body = await this.parseBody(route, params.body);\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Error parsing body\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t\tif (isZodError(error)) {\n\t\t\t\t\tconst { status, body } = this.resolveValidationError(route, error, \"body\");\n\t\t\t\t\treturn c.json(body, status);\n\t\t\t\t}\n\t\t\t\treturn c.json({\n\t\t\t\t\terror: \"Invalid request body\",\n\t\t\t\t\tissues: [{\n\t\t\t\t\t\tfield: \"unknown\",\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t\t}]\n\t\t\t\t}, 400);\n\t\t\t}\n\t\t\tif (params.urlParams) try {\n\t\t\t\tparams.urlParams = await this.parsePathParams(route, params.urlParams);\n\t\t\t} catch (error) {\n\t\t\t\tthis.mastra.getLogger()?.error(\"Error parsing path params\", { error: error instanceof Error ? {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tstack: error.stack\n\t\t\t\t} : error });\n\t\t\t\tif (isZodError(error)) {\n\t\t\t\t\tconst { status, body } = this.resolveValidationError(route, error, \"path\");\n\t\t\t\t\treturn c.json(body, status);\n\t\t\t\t}\n\t\t\t\treturn c.json({\n\t\t\t\t\terror: \"Invalid path parameters\",\n\t\t\t\t\tissues: [{\n\t\t\t\t\t\tfield: \"unknown\",\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t\t}]\n\t\t\t\t}, 400);\n\t\t\t}\n\t\t\tconst handlerParams = {\n\t\t\t\t...params.urlParams,\n\t\t\t\t...params.queryParams,\n\t\t\t\t...typeof params.body === \"object\" ? params.body : {},\n\t\t\t\trequestContext: c.get(\"requestContext\"),\n\t\t\t\tmastra: this.mastra,\n\t\t\t\tregisteredTools: c.get(\"registeredTools\"),\n\t\t\t\ttaskStore: c.get(\"taskStore\"),\n\t\t\t\tabortSignal: c.get(\"abortSignal\"),\n\t\t\t\troutePrefix: prefix,\n\t\t\t\trequest: c.req.raw\n\t\t\t};\n\t\t\tconst requestContext = c.get(\"requestContext\");\n\t\t\tif (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {\n\t\t\t\tconst hasPermission = await loadHasPermission();\n\t\t\t\tif (hasPermission) {\n\t\t\t\t\tconst userPermissions = requestContext.get(\"mastra__userPermissions\");\n\t\t\t\t\tconst permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, requestContext);\n\t\t\t\t\tif (permissionError) return c.json({\n\t\t\t\t\t\terror: permissionError.error,\n\t\t\t\t\t\tmessage: permissionError.message\n\t\t\t\t\t}, permissionError.status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst fgaError = await checkRouteFGA(this.mastra, route, c.get(\"requestContext\"), {\n\t\t\t\t...params.urlParams,\n\t\t\t\t...params.queryParams,\n\t\t\t\t...typeof params.body === \"object\" ? params.body : {}\n\t\t\t});\n\t\t\tif (fgaError) return c.json({\n\t\t\t\terror: fgaError.error,\n\t\t\t\tmessage: fgaError.message\n\t\t\t}, fgaError.status);\n\t\t\ttry {\n\t\t\t\tconst result = await route.handler(handlerParams);\n\t\t\t\treturn this.sendResponse(route, c, result, prefix);\n\t\t\t} catch (error) {\n\t\t\t\tconst httpStatus = error && typeof error === \"object\" && \"status\" in error ? error.status : void 0;\n\t\t\t\tif (!(typeof httpStatus === \"number\" && httpStatus >= 400 && httpStatus < 500)) this.mastra.getLogger()?.error(\"Error calling handler\", {\n\t\t\t\t\terror: error instanceof Error ? {\n\t\t\t\t\t\tmessage: error.message,\n\t\t\t\t\t\tstack: error.stack\n\t\t\t\t\t} : error,\n\t\t\t\t\tpath: route.path,\n\t\t\t\t\tmethod: route.method\n\t\t\t\t});\n\t\t\t\tif (error && typeof error === \"object\") {\n\t\t\t\t\tif (\"status\" in error) {\n\t\t\t\t\t\tconst status = error.status;\n\t\t\t\t\t\tlet safeCause;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst raw = error instanceof Error ? error.cause : void 0;\n\t\t\t\t\t\t\tif (raw && typeof raw === \"object\" && !Array.isArray(raw) && \"failingItems\" in raw && Array.isArray(raw.failingItems)) safeCause = { failingItems: raw.failingItems };\n\t\t\t\t\t\t} catch {}\n\t\t\t\t\t\treturn c.json({\n\t\t\t\t\t\t\terror: error instanceof Error ? error.message : \"Unknown error\",\n\t\t\t\t\t\t\t...safeCause ? { cause: safeCause } : {}\n\t\t\t\t\t\t}, status);\n\t\t\t\t\t}\n\t\t\t\t\tif (\"details\" in error && error.details && typeof error.details === \"object\" && \"status\" in error.details) {\n\t\t\t\t\t\tconst status = error.details.status;\n\t\t\t\t\t\treturn c.json({ error: error instanceof Error ? error.message : \"Unknown error\" }, status);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: error instanceof Error ? error.message : \"Unknown error\" }, 500);\n\t\t\t}\n\t\t});\n\t}\n\tasync registerCustomApiRoutes() {\n\t\tconst routes = await this.registerSchemaApiRoutes();\n\t\tif (!await this.buildCustomRouteHandler(routes)) return;\n\t\tfor (const route of routes) {\n\t\t\tconst serverRoute = {\n\t\t\t\tmethod: route.method,\n\t\t\t\tpath: route.path,\n\t\t\t\tresponseType: \"json\",\n\t\t\t\thandler: async () => {},\n\t\t\t\trequiresAuth: route.requiresAuth,\n\t\t\t\trequiresPermission: route.requiresPermission,\n\t\t\t\tfga: route.fga\n\t\t\t};\n\t\t\tconst routeHandler = async (c) => {\n\t\t\t\tconst authError = await this.checkRouteAuth(serverRoute, {\n\t\t\t\t\tpath: c.req.path,\n\t\t\t\t\tmethod: c.req.method,\n\t\t\t\t\tgetHeader: (name) => c.req.header(name),\n\t\t\t\t\tgetQuery: (name) => c.req.query(name),\n\t\t\t\t\trequestContext: c.get(\"requestContext\"),\n\t\t\t\t\trequest: c.req.raw,\n\t\t\t\t\tbuildAuthorizeContext: () => c\n\t\t\t\t});\n\t\t\t\tif (authError) {\n\t\t\t\t\tif (authError.headers) for (const [key, value] of Object.entries(authError.headers)) c.header(key, value);\n\t\t\t\t\tif (authError.error) return c.json({ error: authError.error }, authError.status);\n\t\t\t\t}\n\t\t\t\tconst requestContext = c.get(\"requestContext\");\n\t\t\t\tif (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {\n\t\t\t\t\tconst hasPermission = await loadHasPermission();\n\t\t\t\t\tif (hasPermission) {\n\t\t\t\t\t\tconst userPermissions = requestContext.get(\"mastra__userPermissions\");\n\t\t\t\t\t\tconst permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission, requestContext);\n\t\t\t\t\t\tif (permissionError) return c.json({\n\t\t\t\t\t\t\terror: permissionError.error,\n\t\t\t\t\t\t\tmessage: permissionError.message\n\t\t\t\t\t\t}, permissionError.status);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlet bodyParams = {};\n\t\t\t\tconst contentType = c.req.header(\"content-type\");\n\t\t\t\tif (contentType?.includes(\"application/json\")) try {\n\t\t\t\t\tconst body = await c.req.raw.clone().json();\n\t\t\t\t\tif (body && typeof body === \"object\" && !Array.isArray(body)) bodyParams = body;\n\t\t\t\t} catch {\n\t\t\t\t\tbodyParams = {};\n\t\t\t\t}\n\t\t\t\telse if (contentType?.includes(\"application/x-www-form-urlencoded\") || contentType?.includes(\"multipart/form-data\")) try {\n\t\t\t\t\tbodyParams = Object.fromEntries(await c.req.raw.clone().formData());\n\t\t\t\t} catch {\n\t\t\t\t\tbodyParams = {};\n\t\t\t\t}\n\t\t\t\tconst fgaError = await checkRouteFGA(this.mastra, serverRoute, c.get(\"requestContext\"), {\n\t\t\t\t\t...c.req.param(),\n\t\t\t\t\t...Object.fromEntries(new URL(c.req.url).searchParams.entries()),\n\t\t\t\t\t...bodyParams\n\t\t\t\t});\n\t\t\t\tif (fgaError) return c.json({\n\t\t\t\t\terror: fgaError.error,\n\t\t\t\t\tmessage: fgaError.message\n\t\t\t\t}, fgaError.status);\n\t\t\t\tconst reqHeaders = {};\n\t\t\t\tc.req.raw.headers.forEach((v, k) => {\n\t\t\t\t\treqHeaders[k] = v;\n\t\t\t\t});\n\t\t\t\tlet executionCtx;\n\t\t\t\ttry {\n\t\t\t\t\texecutionCtx = c.executionCtx;\n\t\t\t\t} catch {\n\t\t\t\t\texecutionCtx = void 0;\n\t\t\t\t}\n\t\t\t\tconst response = await this.handleCustomRouteRequest(c.req.url, c.req.method, reqHeaders, c.req.raw.body, c.get(\"requestContext\"), c.req.raw.signal, executionCtx);\n\t\t\t\tif (!response) return c.json({ error: \"Not Found\" }, 404);\n\t\t\t\treturn response;\n\t\t\t};\n\t\t\tconst method = route.method.toLowerCase();\n\t\t\tthis.app[method](route.path, routeHandler);\n\t\t}\n\t}\n\tregisterContextMiddleware() {\n\t\tconst isFrameworkPublic = this.getFrameworkPublicMatcher();\n\t\tthis.app.use(\"*\", this.createContextMiddleware());\n\t\tthis.app.use(\"*\", async (c, next) => {\n\t\t\tc.set(MASTRA_FRAMEWORK_PUBLIC_KEY$1, isFrameworkPublic(c.req.path, c.req.method));\n\t\t\treturn next();\n\t\t});\n\t\tthis.app.use(\"*\", async (c, next) => {\n\t\t\tawait next();\n\t\t\tthis.warnIfUnregisteredChannelWebhook(c.req.path, c.req.method, c.res.status);\n\t\t});\n\t}\n\tregisterAuthMiddleware() {}\n\tregisterHttpLoggingMiddleware() {\n\t\tif (!this.httpLoggingConfig?.enabled) return;\n\t\tthis.app.use(\"*\", async (c, next) => {\n\t\t\tif (!this.shouldLogRequest(c.req.path)) return next();\n\t\t\tconst start = Date.now();\n\t\t\tconst method = c.req.method;\n\t\t\tconst path = c.req.path;\n\t\t\tawait next();\n\t\t\tconst duration = Date.now() - start;\n\t\t\tconst status = c.res.status;\n\t\t\tconst level = this.httpLoggingConfig?.level || \"info\";\n\t\t\tconst logData = {\n\t\t\t\tmethod,\n\t\t\t\tpath,\n\t\t\t\tstatus,\n\t\t\t\tduration: `${duration}ms`\n\t\t\t};\n\t\t\tif (this.httpLoggingConfig?.includeQueryParams) logData.query = c.req.query();\n\t\t\tif (this.httpLoggingConfig?.includeHeaders) {\n\t\t\t\tconst headers = Object.fromEntries(c.req.raw.headers.entries());\n\t\t\t\t(this.httpLoggingConfig.redactHeaders || []).forEach((h) => {\n\t\t\t\t\tconst key = h.toLowerCase();\n\t\t\t\t\tif (headers[key] !== void 0) headers[key] = \"[REDACTED]\";\n\t\t\t\t});\n\t\t\t\tlogData.headers = headers;\n\t\t\t}\n\t\t\tthis.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n\t\t});\n\t}\n};\n//#endregion\nexport { MASTRA_FRAMEWORK_PUBLIC_KEY, MastraServer, createAuthMiddleware, setupBrowserStream, skipIfFrameworkPublic };\n\n//# sourceMappingURL=index.js.map","import { findTargetHandler } from 'hono/utils/handler';\nimport { sValidator } from '@hono/standard-validator';\nimport { loadVendor as loadVendor$1, toJsonSchema } from '@standard-community/standard-json';\nimport { loadVendor as loadVendor$2, toOpenAPISchema } from '@standard-community/standard-openapi';\n\nconst uniqueSymbol = Symbol(\"openapi\");\nconst ALLOWED_METHODS = [\n \"GET\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"OPTIONS\",\n \"HEAD\",\n \"PATCH\",\n \"TRACE\"\n];\nconst toOpenAPIPathSegment = (segment) => {\n let tmp = segment;\n if (tmp.startsWith(\":\")) {\n const match = tmp.match(/^:([^{?]+)(?:{(.+)})?(\\?)?$/);\n if (match) {\n const paramName = match[1];\n tmp = `{${paramName}}`;\n } else {\n tmp = tmp.slice(1, tmp.length);\n if (tmp.endsWith(\"?\")) tmp = tmp.slice(0, -1);\n tmp = `{${tmp}}`;\n }\n }\n return tmp;\n};\nconst toOpenAPIPath = (path) => path.split(\"/\").map(toOpenAPIPathSegment).join(\"/\");\nconst toPascalCase = (text) => text.split(/[\\W_]+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(\"\");\nconst generateOperationId = (route) => {\n let operationId = route.method.toLowerCase();\n if (route.path === \"/\") return `${operationId}Index`;\n for (const segment of route.path.split(\"/\")) {\n const openApiPathSegment = toOpenAPIPathSegment(segment);\n if (openApiPathSegment.charCodeAt(0) === 123) {\n operationId += `By${toPascalCase(openApiPathSegment.slice(1, -1))}`;\n } else {\n operationId += toPascalCase(openApiPathSegment);\n }\n }\n return operationId;\n};\nconst paramKey = (param) => \"$ref\" in param ? param.$ref : `${param.in} ${param.name}`;\nfunction mergeParameters(...params) {\n const merged = params.flatMap((x) => x ?? []).reduce((acc, param) => {\n acc.set(paramKey(param), param);\n return acc;\n }, /* @__PURE__ */ new Map());\n return Array.from(merged.values());\n}\nconst specsByPathContext = /* @__PURE__ */ new Map();\nfunction getPathContext(path) {\n const context = [];\n for (const [key, data] of specsByPathContext) {\n if (data && path.match(key)) {\n context.push(data);\n }\n }\n return context;\n}\nfunction clearSpecsContext() {\n specsByPathContext.clear();\n}\nfunction mergeSpecs(route, ...specs) {\n return specs.reduce(\n (prev, spec) => {\n if (!spec || !prev) return prev;\n for (const [key, value] of Object.entries(spec)) {\n if (value == null) continue;\n if (key in prev && (typeof value === \"object\" || typeof value === \"function\" && key === \"operationId\")) {\n if (Array.isArray(value)) {\n const values = [...prev[key] ?? [], ...value];\n if (key === \"tags\") {\n prev[key] = Array.from(new Set(values));\n } else if (key === \"parameters\") {\n prev[key] = mergeParameters(values);\n } else {\n prev[key] = values;\n }\n } else if (typeof value === \"function\") {\n prev[key] = value(route);\n } else {\n if (key === \"parameters\") {\n prev[key] = mergeParameters(prev[key], value);\n } else {\n prev[key] = {\n ...prev[key],\n ...value\n };\n }\n }\n } else {\n prev[key] = value;\n }\n }\n return prev;\n },\n {\n operationId: generateOperationId(route)\n }\n );\n}\nfunction registerSchemaPath({\n route,\n specs,\n paths\n}) {\n const path = toOpenAPIPath(route.path);\n const method = route.method.toLowerCase();\n if (method === \"all\") {\n if (!specs) return;\n if (specsByPathContext.has(path)) {\n const prev = specsByPathContext.get(path) ?? {};\n specsByPathContext.set(path, mergeSpecs(route, prev, specs));\n } else {\n specsByPathContext.set(path, specs);\n }\n } else {\n const pathContext = getPathContext(path);\n if (!(path in paths)) {\n paths[path] = {};\n }\n if (paths[path]) {\n paths[path][method] = mergeSpecs(\n route,\n ...pathContext,\n paths[path]?.[method],\n specs\n );\n }\n }\n}\nfunction removeExcludedPaths(paths, ctx) {\n const { exclude, excludeStaticFile } = ctx.options;\n const newPaths = {};\n const _exclude = Array.isArray(exclude) ? exclude : [exclude];\n for (const [key, value] of Object.entries(paths)) {\n if (value == null) continue;\n const isExplicitlyExcluded = _exclude.some((x) => {\n if (typeof x === \"string\") return key === x;\n return x.test(key);\n });\n if (isExplicitlyExcluded) continue;\n const isWildcardWithoutParameters = key.includes(\"*\") && !key.includes(\"{\");\n if (isWildcardWithoutParameters) continue;\n if (excludeStaticFile) {\n const hasPathParameters = key.includes(\"{\");\n const lastSegment = key.split(\"/\").pop() || \"\";\n const looksLikeStaticFile = lastSegment.includes(\".\");\n const shouldExcludeAsStaticFile = !hasPathParameters && looksLikeStaticFile;\n if (shouldExcludeAsStaticFile) continue;\n }\n for (const method of Object.keys(value)) {\n const schema = value[method];\n if (schema == null) continue;\n if (key.includes(\"{\")) {\n schema.parameters = schema.parameters ? [...schema.parameters] : [];\n const pathParameters = key.split(\"/\").filter(\n (x) => x.startsWith(\"{\") && !schema.parameters.find(\n (params) => params.in === \"path\" && params.name === x.slice(1, x.length - 1)\n )\n );\n for (const param of pathParameters) {\n const paramName = param.slice(1, param.length - 1);\n const index = schema.parameters.findIndex(\n (x) => {\n if (\"$ref\" in x) {\n const pos = x.$ref.split(\"/\").pop();\n if (pos) {\n const param2 = ctx.components.parameters?.[pos];\n if (param2 && !(\"$ref\" in param2)) {\n return param2.in === \"path\" && param2.name === paramName;\n }\n }\n return false;\n }\n return x.in === \"path\" && x.name === paramName;\n }\n );\n if (index === -1) {\n schema.parameters.push({\n schema: { type: \"string\" },\n in: \"path\",\n name: paramName,\n required: true\n });\n }\n }\n }\n if (!schema.responses) {\n schema.responses = {\n 200: {}\n };\n }\n }\n const filteredValue = {};\n for (const method of Object.keys(value)) {\n if (value[method] != null) {\n filteredValue[method] = value[method];\n }\n }\n if (Object.keys(filteredValue).length > 0) {\n newPaths[key] = filteredValue;\n }\n }\n return newPaths;\n}\n\nconst DEFAULT_OPTIONS = {\n documentation: {},\n excludeStaticFile: true,\n exclude: [],\n excludeMethods: [\"OPTIONS\"],\n excludeTags: []\n};\nfunction openAPIRouteHandler(hono, options) {\n let specs;\n return async (c) => {\n if (specs) return c.json(specs);\n specs = await generateSpecs(hono, options, c);\n return c.json(specs);\n };\n}\nasync function generateSpecs(hono, options = DEFAULT_OPTIONS, c) {\n const ctx = {\n components: {},\n // @ts-expect-error\n options: {\n ...DEFAULT_OPTIONS,\n ...options\n }\n };\n const _documentation = ctx.options.documentation ?? {};\n clearSpecsContext();\n const paths = await generatePaths(hono, ctx);\n for (const path in paths) {\n for (const method in paths[path]) {\n const isHidden = getHiddenValue({\n valueOrFunc: paths[path][method]?.hide,\n method,\n path,\n c\n });\n if (isHidden) {\n paths[path][method] = void 0;\n }\n }\n }\n const { components: resolvedDocComponents } = _documentation.components?.responses ? await resolveResponseSchemas(_documentation.components.responses) : { components: {} };\n const components = mergeComponentsObjects(\n _documentation.components,\n resolvedDocComponents,\n ctx.components\n );\n return {\n openapi: \"3.1.0\",\n ..._documentation,\n tags: _documentation.tags?.filter(\n (tag) => !ctx.options.excludeTags?.includes(tag?.name)\n ),\n info: {\n title: \"Hono Documentation\",\n description: \"Development documentation\",\n version: \"0.0.0\",\n ..._documentation.info\n },\n paths: {\n ...removeExcludedPaths(paths, ctx),\n ..._documentation.paths\n },\n components\n };\n}\nasync function generatePaths(hono, ctx) {\n const paths = {};\n for (const route of hono.routes) {\n const middlewareHandler = findTargetHandler(route.handler)[uniqueSymbol];\n if (!middlewareHandler) {\n if (ctx.options.includeEmptyPaths) {\n registerSchemaPath({\n route,\n paths\n });\n }\n continue;\n }\n const routeMethod = route.method;\n if (routeMethod !== \"ALL\") {\n if (ctx.options.excludeMethods?.includes(routeMethod)) {\n continue;\n }\n if (!ALLOWED_METHODS.includes(routeMethod)) {\n continue;\n }\n }\n const defaultOptionsForThisMethod = ctx.options.defaultOptions?.[routeMethod] && { ...ctx.options.defaultOptions[routeMethod] };\n const { schema: routeSpecs, components = {} } = await getSpec(\n middlewareHandler,\n defaultOptionsForThisMethod\n );\n ctx.components = mergeComponentsObjects(ctx.components, components);\n registerSchemaPath({\n route,\n specs: routeSpecs,\n paths\n });\n }\n return paths;\n}\nfunction getHiddenValue(options) {\n const { valueOrFunc, c, method, path } = options;\n if (valueOrFunc != null) {\n if (typeof valueOrFunc === \"boolean\") {\n return valueOrFunc;\n }\n if (typeof valueOrFunc === \"function\") {\n return valueOrFunc({ c, method, path });\n }\n }\n return false;\n}\nasync function getSpec(middlewareHandler, defaultOptions) {\n if (\"spec\" in middlewareHandler) {\n const tmp = {\n ...defaultOptions,\n ...middlewareHandler.spec,\n responses: {\n ...defaultOptions?.responses,\n ...middlewareHandler.spec.responses\n }\n };\n let components = {};\n if (tmp.responses) {\n const resolved = await resolveResponseSchemas(tmp.responses);\n components = resolved.components;\n }\n return { schema: tmp, components };\n }\n const result = await middlewareHandler.toOpenAPISchema();\n const docs = { ...defaultOptions };\n if (middlewareHandler.target === \"form\" || middlewareHandler.target === \"json\") {\n const media = middlewareHandler.options?.media ?? middlewareHandler.target === \"json\" ? \"application/json\" : \"multipart/form-data\";\n if (!docs.requestBody || !(\"content\" in docs.requestBody) || !docs.requestBody.content) {\n docs.requestBody = {\n required: true,\n content: {\n [media]: {\n schema: result.schema\n }\n }\n };\n } else {\n docs.requestBody.content[media] = {\n schema: result.schema\n };\n }\n } else {\n let parameters = [];\n if (\"$ref\" in result.schema) {\n const ref = result.schema.$ref;\n const pos = ref.split(\"/\").pop();\n if (pos && result.components?.schemas?.[pos]) {\n const schema = result.components.schemas[pos];\n const newParameters = generateParameters(\n middlewareHandler.target,\n schema\n )[0];\n if (!result.components.parameters) {\n result.components.parameters = {};\n }\n result.components.parameters[pos] = newParameters;\n delete result.components.schemas[pos];\n parameters.push({\n $ref: `#/components/parameters/${pos}`\n });\n }\n } else {\n parameters = generateParameters(middlewareHandler.target, result.schema);\n }\n docs.parameters = parameters;\n }\n return { schema: docs, components: result.components };\n}\nfunction generateParameters(target, schema) {\n const parameters = [];\n for (const [key, value] of Object.entries(schema.properties ?? {})) {\n const def = {\n in: target === \"param\" ? \"path\" : target,\n name: key,\n // @ts-expect-error\n schema: value\n };\n const isRequired = schema.required?.includes(key);\n if (isRequired) {\n def.required = true;\n }\n if (def.schema && \"description\" in def.schema && def.schema.description) {\n def.description = def.schema.description;\n def.schema.description = void 0;\n }\n parameters.push(def);\n }\n return parameters;\n}\nasync function resolveResponseSchemas(responses) {\n let components = {};\n for (const key of Object.keys(responses)) {\n const response = responses[key];\n if (!response || !(\"content\" in response)) continue;\n for (const contentKey of Object.keys(response.content ?? {})) {\n const raw = response.content?.[contentKey];\n if (!raw) continue;\n if (raw.schema && \"toOpenAPISchema\" in raw.schema) {\n const result = await raw.schema.toOpenAPISchema();\n raw.schema = result.schema;\n if (result.components) {\n components = mergeComponentsObjects(components, result.components);\n }\n }\n }\n }\n return { responses, components };\n}\nfunction mergeComponentsObjects(...components) {\n return components.reduce(\n (prev, component, index) => {\n if (component == null || index === 0) return prev;\n if (prev.schemas && Object.keys(prev.schemas).length > 0 || component.schemas && Object.keys(component.schemas).length > 0) {\n prev.schemas = {\n ...prev.schemas,\n ...component.schemas\n };\n }\n if (prev.parameters && Object.keys(prev.parameters).length > 0 || component.parameters && Object.keys(component.parameters).length > 0) {\n prev.parameters = {\n ...prev.parameters,\n ...component.parameters\n };\n }\n return prev;\n },\n components[0] ?? {}\n );\n}\n\nfunction loadVendor(vendor, fn) {\n if (fn.toJSONSchema) {\n loadVendor$1(vendor, fn.toJSONSchema);\n }\n if (fn.toOpenAPISchema) {\n loadVendor$2(vendor, fn.toOpenAPISchema);\n }\n}\nconst arktypeMorphFallback = (ctx) => ctx.base;\nconst zodV4DateOverride = (ctx) => {\n if (ctx.zodSchema._zod.def.type === \"date\") {\n ctx.jsonSchema.type = \"string\";\n ctx.jsonSchema.format = \"date-time\";\n }\n};\nfunction resolver(schema, userDefinedOptions) {\n const vendor = schema[\"~standard\"].vendor;\n return {\n vendor,\n validate: schema[\"~standard\"].validate,\n toJSONSchema: (customOptions) => toJsonSchema(schema, { ...userDefinedOptions, ...customOptions }),\n toOpenAPISchema: (customOptions) => toOpenAPISchema(schema, {\n ...userDefinedOptions,\n ...customOptions,\n ...vendor === \"arktype\" ? injectArktypeFallback(userDefinedOptions, customOptions) : void 0,\n ...vendor === \"zod\" ? injectZodV4DateOverride(schema, userDefinedOptions, customOptions) : void 0\n })\n };\n}\nfunction injectArktypeFallback(userDefined, custom) {\n const userNested = userDefined?.options;\n const customNested = custom?.options;\n if (userDefined?.fallback || userNested?.fallback || custom?.fallback || customNested?.fallback) {\n return void 0;\n }\n return {\n options: {\n fallback: arktypeMorphFallback,\n ...userNested,\n ...customNested\n }\n };\n}\nfunction injectZodV4DateOverride(schema, userDefined, custom) {\n if (!(\"_zod\" in schema)) return void 0;\n const userNested = userDefined?.options;\n const customNested = custom?.options;\n if (userDefined?.override || userNested?.override || custom?.override || customNested?.override) {\n return void 0;\n }\n return {\n options: {\n unrepresentable: \"any\",\n override: zodV4DateOverride,\n ...userNested,\n ...customNested\n }\n };\n}\nfunction validator(target, schema, hook, options) {\n const middleware = sValidator(target, schema, hook);\n Object.defineProperty(middleware, \"name\", {\n value: \"validator\",\n configurable: true\n });\n return Object.assign(middleware, {\n [uniqueSymbol]: {\n target,\n ...resolver(schema, options),\n options\n }\n });\n}\nfunction describeRoute(spec) {\n const middleware = async (_c, next) => {\n await next();\n };\n Object.defineProperty(middleware, \"name\", {\n value: \"describeRoute\",\n configurable: true\n });\n return Object.assign(middleware, {\n [uniqueSymbol]: {\n spec\n }\n });\n}\nfunction describeResponse(handler, responses, options) {\n const _responses = Object.entries(responses).reduce(\n (acc, [statusCode, response]) => {\n if (response.content) {\n const content = Object.entries(response.content).reduce(\n (contentAcc, [mediaType, media]) => {\n if (media.vSchema) {\n const { vSchema, ...rest } = media;\n contentAcc[mediaType] = {\n ...rest,\n schema: resolver(vSchema, options)\n };\n } else {\n contentAcc[mediaType] = media;\n }\n return contentAcc;\n },\n {}\n );\n acc[statusCode] = { ...response, content };\n } else {\n acc[statusCode] = response;\n }\n return acc;\n },\n {}\n );\n return Object.assign(handler, {\n [uniqueSymbol]: {\n spec: { responses: _responses }\n }\n });\n}\n\nexport { ALLOWED_METHODS, clearSpecsContext, describeResponse, describeRoute, generateSpecs, loadVendor, openAPIRouteHandler, registerSchemaPath, removeExcludedPaths, resolver, uniqueSymbol, validator };\n","import process from 'node:process';\nimport type { Context } from 'hono';\n\nconst DEFAULT_AGENT_LEARNING_ENDPOINT = 'https://output.signals.mastra.ai';\nconst AGENT_LEARNING_TIMEOUT_MS = 8_000;\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport async function agentLearningProxyHandler(c: Context): Promise<Response> {\n const requestUrl = new URL(c.req.url);\n if (!LOOPBACK_HOSTS.has(requestUrl.hostname)) {\n return c.json({ error: 'Agent Learning development proxy is only available on loopback hosts' }, 403);\n }\n\n const origin = c.req.header('Origin');\n if (origin && origin !== requestUrl.origin) {\n return c.json({ error: 'Cross-origin Agent Learning requests are not allowed' }, 403);\n }\n\n const accessToken = process.env.MASTRA_PLATFORM_ACCESS_TOKEN;\n const projectId = process.env.MASTRA_PROJECT_ID;\n if (!accessToken || !projectId) {\n return c.json(\n {\n error: 'MASTRA_PLATFORM_ACCESS_TOKEN and MASTRA_PROJECT_ID are required for Agent Learning',\n },\n 503,\n );\n }\n\n const endpoint = process.env.MASTRA_PLATFORM_AGENT_LEARNING_ENDPOINT || DEFAULT_AGENT_LEARNING_ENDPOINT;\n let upstreamUrl: URL;\n try {\n upstreamUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, `${endpoint.replace(/\\/+$/, '')}/`);\n } catch {\n return c.json({ error: 'MASTRA_PLATFORM_AGENT_LEARNING_ENDPOINT must be a valid URL' }, 503);\n }\n\n try {\n const upstream = await fetch(upstreamUrl, {\n method: 'GET',\n headers: {\n Accept: c.req.header('Accept') || 'application/json',\n Authorization: `Bearer ${accessToken}`,\n 'X-Mastra-Project-Id': projectId,\n },\n signal: AbortSignal.timeout(AGENT_LEARNING_TIMEOUT_MS),\n });\n\n const headers = new Headers();\n const contentType = upstream.headers.get('content-type');\n const cacheControl = upstream.headers.get('cache-control');\n if (contentType) headers.set('content-type', contentType);\n if (cacheControl) headers.set('cache-control', cacheControl);\n\n return new Response(upstream.body, {\n status: upstream.status,\n statusText: upstream.statusText,\n headers,\n });\n } catch {\n return c.json({ error: 'Agent Learning upstream unavailable' }, 502);\n }\n}\n","import type { Context } from 'hono';\n\nconst clients = new Set<ReadableStreamDefaultController>();\nlet hotReloadDisabled = false;\n\nexport function handleClientsRefresh(c: Context): Response {\n const stream = new ReadableStream({\n start(controller) {\n clients.add(controller);\n controller.enqueue('data: connected\\n\\n');\n\n c.req.raw.signal.addEventListener('abort', () => {\n clients.delete(controller);\n });\n },\n });\n\n return new Response(stream, {\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'Access-Control-Allow-Origin': '*',\n },\n });\n}\n\nexport function handleTriggerClientsRefresh(c: Context) {\n clients.forEach(controller => {\n try {\n controller.enqueue('data: refresh\\n\\n');\n } catch {\n clients.delete(controller);\n }\n });\n return c.json({ success: true, clients: clients.size });\n}\n\n// Functions to control hot reload during template installation\nexport function disableHotReload() {\n hotReloadDisabled = true;\n console.info('🔒 Hot reload disabled for template installation');\n}\n\nexport function enableHotReload() {\n hotReloadDisabled = false;\n console.info('🔓 Hot reload re-enabled after template installation');\n}\n\nexport function isHotReloadDisabled(): boolean {\n return hotReloadDisabled;\n}\n","import type { Context } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport type { ContentfulStatusCode } from 'hono/utils/http-status';\n\nimport type { ApiError } from '../types';\n\n// Helper to handle errors consistently\nexport function handleError(error: unknown, defaultMessage: string): Promise<Response> {\n const apiError = error as ApiError;\n throw new HTTPException((apiError.status || 500) as ContentfulStatusCode, {\n message: apiError.message || defaultMessage,\n cause: apiError.cause,\n });\n}\nexport function errorHandler(err: Error, c: Context, isDev?: boolean): Response {\n if (err instanceof HTTPException) {\n if (isDev) {\n return c.json({ error: err.message, cause: err.cause, stack: err.stack }, err.status);\n }\n return c.json({ error: err.message }, err.status);\n }\n\n c.get('mastra').getLogger().error(err);\n return c.json({ error: 'Internal Server Error' }, 500);\n}\n","import type { Context } from 'hono';\n\n// Health check handler\nexport async function healthHandler(c: Context) {\n return c.json({ success: true }, 200);\n}\n","import type { Mastra } from '@mastra/core/mastra';\nimport type { Context } from 'hono';\n\nimport { handleError } from './error';\n\nexport async function restartAllActiveWorkflowRunsHandler(c: Context) {\n try {\n const mastra: Mastra = c.get('mastra');\n void mastra.restartAllActiveWorkflowRuns().catch(error => {\n mastra.getLogger().error('Failed to restart active workflow runs during server startup', { error });\n });\n\n // Opt-in boot-time recovery for orphaned RUNNING durable-agent runs.\n // Gated by `recovery.durableAgents === 'auto'` so we don't silently\n // re-issue LLM calls / re-execute tools on restart.\n if (mastra.recoveryConfig?.durableAgents === 'auto') {\n void mastra.recoverAllDurableAgents().catch(error => {\n mastra.getLogger().error('Failed to recover durable agent runs during server startup', { error });\n });\n }\n\n return c.json({ message: 'Restarting all active workflow runs...' });\n } catch (error) {\n return handleError(error, 'Error restarting active workflow runs');\n }\n}\n","import type { Context } from 'hono';\n\n// Root handler\nexport async function rootHandler(c: Context) {\n const baseUrl = new URL(c.req.url).origin;\n\n return c.html(\n /* html */\n `\n <!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Mastra API</title>\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/inter-ui/3.19.3/inter.min.css\" />\n <style>\n body {\n margin: 0;\n padding: 0;\n background-color: #0d0d0d;\n color: #ffffff;\n font-family:\n 'Inter',\n -apple-system,\n BlinkMacSystemFont,\n system-ui,\n sans-serif;\n min-height: 100vh;\n display: flex;\n flex-direction: column;\n }\n\n main {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 2rem;\n text-align: center;\n }\n\n h1 {\n font-size: 4rem;\n font-weight: 600;\n margin: 0 0 1rem 0;\n background: linear-gradient(to right, #fff, #ccc);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n line-height: 1.2;\n }\n\n .subtitle {\n color: #9ca3af;\n font-size: 1.25rem;\n max-width: 600px;\n margin: 0 auto 3rem auto;\n line-height: 1.6;\n }\n\n .link {\n color: #ffffff;\n }\n\n .link:hover {\n text-decoration: none;\n }\n\n .docs-link {\n background-color: #1a1a1a;\n padding: 1rem 2rem;\n border-radius: 0.5rem;\n display: flex;\n align-items: center;\n gap: 1rem;\n font-family: monospace;\n font-size: 1rem;\n color: #ffffff;\n text-decoration: none;\n transition: background-color 0.2s;\n }\n\n .docs-link:hover {\n background-color: #252525;\n }\n\n .arrow-icon {\n transition: transform 0.2s;\n }\n\n .docs-link:hover .arrow-icon {\n transform: translateX(4px);\n }\n </style>\n </head>\n <body>\n <main>\n <h1>Welcome to the Mastra API</h1>\n <p class=\"subtitle\">\n Discover all available endpoints through Swagger UI. You can also define your own <a href=\"https://mastra.ai/docs/server-db/custom-api-routes\" target=\"_blank\" class=\"link\">API routes</a>.\n </p>\n <a href=\"${baseUrl}/swagger-ui\" target=\"_blank\" class=\"docs-link\">\n Browse Swagger UI\n <svg\n class=\"arrow-icon\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <path d=\"M5 12h14M12 5l7 7-7 7\" />\n </svg>\n </a>\n </main>\n </body>\n </html>\n `,\n );\n}\n","/**\n * Trim leading and trailing slashes. Index scan instead of regex to avoid\n * backtracking (CodeQL js/polynomial-redos).\n */\nfunction trimSlashes(value: string): string {\n let start = 0;\n let end = value.length;\n while (start < end && value[start] === '/') start++;\n while (end > start && value[end - 1] === '/') end--;\n return value.slice(start, end);\n}\n\nexport function welcomeHtml(apiPrefix: string = '/api') {\n // Normalize: ensure single leading slash, no trailing slash.\n const prefix = '/' + trimSlashes(apiPrefix);\n const prefixNoSlash = prefix.slice(1);\n return `\n<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Mastra Server</title>\n <style>\n * { box-sizing: border-box; }\n\n body {\n margin: 0;\n padding: 0;\n background-color: #0a0a0a;\n color: #e4e4e7;\n font-family: -apple-system, BlinkMacSystemFont, system-ui, sans-serif;\n min-height: 100vh;\n line-height: 1.6;\n }\n\n .page {\n max-width: 720px;\n margin: 0 auto;\n padding: 3rem 1.5rem 4rem;\n }\n\n header {\n margin-bottom: 2.5rem;\n }\n\n header h1 {\n font-size: 1.75rem;\n font-weight: 600;\n margin: 0 0 0.25rem;\n color: #fff;\n }\n\n header p {\n color: #71717a;\n font-size: 0.9rem;\n margin: 0;\n }\n\n .status-bar {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n margin-top: 1rem;\n font-size: 0.8rem;\n color: #a1a1aa;\n }\n\n .status-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: #22c55e;\n flex-shrink: 0;\n }\n\n section {\n margin-bottom: 2rem;\n }\n\n section h2 {\n font-size: 0.75rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: #71717a;\n margin: 0 0 0.75rem;\n }\n\n .card {\n background: #18181b;\n border: 1px solid #27272a;\n border-radius: 8px;\n overflow: hidden;\n }\n\n .card + .card {\n margin-top: 0.75rem;\n }\n\n .card-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0.75rem 1rem;\n gap: 0.75rem;\n }\n\n .card-row + .card-row {\n border-top: 1px solid #27272a;\n }\n\n .card-row-left {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n min-width: 0;\n }\n\n .method {\n font-family: 'SF Mono', SFMono-Regular, ui-monospace, Menlo, monospace;\n font-size: 0.7rem;\n font-weight: 600;\n padding: 2px 6px;\n border-radius: 4px;\n flex-shrink: 0;\n }\n\n .method-get { background: #052e16; color: #4ade80; }\n .method-post { background: #172554; color: #60a5fa; }\n\n .endpoint-path {\n font-family: 'SF Mono', SFMono-Regular, ui-monospace, Menlo, monospace;\n font-size: 0.8rem;\n color: #d4d4d8;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .endpoint-desc {\n font-size: 0.75rem;\n color: #71717a;\n flex-shrink: 0;\n }\n\n .curl-block {\n position: relative;\n background: #111113;\n border: 1px solid #27272a;\n border-radius: 8px;\n overflow: hidden;\n }\n\n .curl-block + .curl-block {\n margin-top: 0.75rem;\n }\n\n .curl-label {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0.5rem 1rem;\n border-bottom: 1px solid #27272a;\n font-size: 0.75rem;\n color: #a1a1aa;\n }\n\n .copy-btn {\n background: none;\n border: 1px solid #3f3f46;\n border-radius: 4px;\n color: #a1a1aa;\n font-size: 0.7rem;\n padding: 2px 8px;\n cursor: pointer;\n font-family: inherit;\n transition: all 0.15s;\n }\n\n .copy-btn:hover {\n background: #27272a;\n color: #e4e4e7;\n }\n\n .curl-code {\n padding: 0.75rem 1rem;\n font-family: 'SF Mono', SFMono-Regular, ui-monospace, Menlo, monospace;\n font-size: 0.8rem;\n line-height: 1.5;\n color: #d4d4d8;\n overflow-x: auto;\n white-space: pre;\n margin: 0;\n }\n\n .curl-code .c-cmd { color: #a78bfa; }\n .curl-code .c-flag { color: #60a5fa; }\n .curl-code .c-url { color: #fbbf24; }\n .curl-code .c-str { color: #4ade80; }\n\n .links-grid {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 0.75rem;\n }\n\n .link-card {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n padding: 0.875rem 1rem;\n background: #18181b;\n border: 1px solid #27272a;\n border-radius: 8px;\n color: #d4d4d8;\n text-decoration: none;\n font-size: 0.85rem;\n transition: all 0.15s;\n }\n\n .link-card:hover {\n background: #1f1f23;\n border-color: #3f3f46;\n color: #fff;\n }\n\n .link-icon {\n flex-shrink: 0;\n width: 18px;\n height: 18px;\n color: #71717a;\n }\n\n .link-card:hover .link-icon { color: #a1a1aa; }\n\n footer {\n margin-top: 3rem;\n padding-top: 1.5rem;\n border-top: 1px solid #1c1c1f;\n font-size: 0.75rem;\n color: #52525b;\n }\n\n @media (max-width: 480px) {\n .page { padding: 2rem 1rem 3rem; }\n header h1 { font-size: 1.5rem; }\n .links-grid { grid-template-columns: 1fr; }\n .endpoint-desc { display: none; }\n }\n </style>\n </head>\n <body>\n <div class=\"page\">\n <header>\n <h1>Mastra Server</h1>\n <p>Your server is running. Use the endpoints below to get started.</p>\n <div class=\"status-bar\">\n <span class=\"status-dot\"></span>\n <span id=\"base-url\"></span>\n </div>\n </header>\n\n <section>\n <h2>Quick Start</h2>\n\n <div class=\"curl-block\">\n <div class=\"curl-label\">\n <span>Check server health</span>\n <button class=\"copy-btn\" onclick=\"copyCode(this)\">Copy</button>\n </div>\n <pre class=\"curl-code\" data-tpl=\"curl <base>/health\"><span class=\"c-cmd\">curl</span> <span class=\"c-url\" data-url=\"health\"></span></pre>\n </div>\n\n <div class=\"curl-block\">\n <div class=\"curl-label\">\n <span>List your agents</span>\n <button class=\"copy-btn\" onclick=\"copyCode(this)\">Copy</button>\n </div>\n <pre class=\"curl-code\" data-tpl=\"curl <base>${prefix}/agents\"><span class=\"c-cmd\">curl</span> <span class=\"c-url\" data-url=\"${prefixNoSlash}/agents\"></span></pre>\n </div>\n\n <div class=\"curl-block\">\n <div class=\"curl-label\">\n <span>Chat with an agent</span>\n <button class=\"copy-btn\" onclick=\"copyCode(this)\">Copy</button>\n </div>\n <pre class=\"curl-code\" data-tpl=\"curl -X POST <base>${prefix}/agents/:agent-id/generate -H 'Content-Type: application/json' -d '{&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Hello&quot;}]}'\"><span class=\"c-cmd\">curl</span> <span class=\"c-flag\">-X POST</span> <span class=\"c-url\" data-url=\"${prefixNoSlash}/agents/:agent-id/generate\"></span> \\\\\n <span class=\"c-flag\">-H</span> <span class=\"c-str\">'Content-Type: application/json'</span> \\\\\n <span class=\"c-flag\">-d</span> <span class=\"c-str\">'{\"messages\":[{\"role\":\"user\",\"content\":\"Hello\"}]}'</span></pre>\n </div>\n\n <div class=\"curl-block\">\n <div class=\"curl-label\">\n <span>Stream an agent response</span>\n <button class=\"copy-btn\" onclick=\"copyCode(this)\">Copy</button>\n </div>\n <pre class=\"curl-code\" data-tpl=\"curl -N -X POST <base>${prefix}/agents/:agent-id/stream -H 'Content-Type: application/json' -d '{&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Hello&quot;}]}'\"><span class=\"c-cmd\">curl</span> <span class=\"c-flag\">-N -X POST</span> <span class=\"c-url\" data-url=\"${prefixNoSlash}/agents/:agent-id/stream\"></span> \\\\\n <span class=\"c-flag\">-H</span> <span class=\"c-str\">'Content-Type: application/json'</span> \\\\\n <span class=\"c-flag\">-d</span> <span class=\"c-str\">'{\"messages\":[{\"role\":\"user\",\"content\":\"Hello\"}]}'</span></pre>\n </div>\n </section>\n\n <section>\n <h2>API Endpoints</h2>\n <div class=\"card\">\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-get\">GET</span>\n <span class=\"endpoint-path\">${prefix}/agents</span>\n </div>\n <span class=\"endpoint-desc\">List all agents</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-post\">POST</span>\n <span class=\"endpoint-path\">${prefix}/agents/:id/generate</span>\n </div>\n <span class=\"endpoint-desc\">Generate a response</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-post\">POST</span>\n <span class=\"endpoint-path\">${prefix}/agents/:id/stream</span>\n </div>\n <span class=\"endpoint-desc\">Stream a response</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-get\">GET</span>\n <span class=\"endpoint-path\">${prefix}/workflows</span>\n </div>\n <span class=\"endpoint-desc\">List all workflows</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-post\">POST</span>\n <span class=\"endpoint-path\">${prefix}/workflows/:id/start</span>\n </div>\n <span class=\"endpoint-desc\">Run a workflow</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-get\">GET</span>\n <span class=\"endpoint-path\">${prefix}/tools</span>\n </div>\n <span class=\"endpoint-desc\">List all tools</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-post\">POST</span>\n <span class=\"endpoint-path\">${prefix}/tools/:id/execute</span>\n </div>\n <span class=\"endpoint-desc\">Execute a tool</span>\n </div>\n <div class=\"card-row\">\n <div class=\"card-row-left\">\n <span class=\"method method-get\">GET</span>\n <span class=\"endpoint-path\">${prefix}/memory/threads</span>\n </div>\n <span class=\"endpoint-desc\">List memory threads</span>\n </div>\n </div>\n </section>\n\n <section>\n <h2>Resources</h2>\n <div class=\"links-grid\">\n <a href=\"https://mastra.ai/docs\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"link-card\">\n <svg class=\"link-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 19.5A2.5 2.5 0 0 1 6.5 17H20\"/><path d=\"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z\"/></svg>\n Documentation\n </a>\n <a href=\"https://mastra.ai/docs/server-db/custom-api-routes\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"link-card\">\n <svg class=\"link-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M16 18l6-6-6-6\"/><path d=\"M8 6l-6 6 6 6\"/></svg>\n Custom API Routes\n </a>\n <a href=\"https://mastra.ai/docs/agents/overview\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"link-card\">\n <svg class=\"link-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"3\"/><path d=\"M12 1v4m0 14v4m-7.8-15.4 2.8 2.8m9.6 9.6 2.8 2.8M1 12h4m14 0h4M4.2 19.8l2.8-2.8m9.6-9.6 2.8-2.8\"/></svg>\n Agents Guide\n </a>\n <a href=\"https://mastra.ai/docs/workflows/overview\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"link-card\">\n <svg class=\"link-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"16 3 21 3 21 8\"/><line x1=\"4\" y1=\"20\" x2=\"21\" y2=\"3\"/><polyline points=\"21 16 21 21 16 21\"/><line x1=\"15\" y1=\"15\" x2=\"21\" y2=\"21\"/><line x1=\"4\" y1=\"4\" x2=\"9\" y2=\"9\"/></svg>\n Workflows Guide\n </a>\n </div>\n </section>\n\n <footer>\n Powered by <a href=\"https://mastra.ai\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"color:#71717a;\">Mastra</a>\n </footer>\n </div>\n\n <script>\n (function() {\n var base = location.origin;\n document.getElementById('base-url').textContent = base;\n\n var els = document.querySelectorAll('[data-url]');\n for (var i = 0; i < els.length; i++) {\n els[i].textContent = base + '/' + els[i].getAttribute('data-url');\n }\n\n var tpls = document.querySelectorAll('[data-tpl]');\n for (var i = 0; i < tpls.length; i++) {\n tpls[i].setAttribute('data-tpl', tpls[i].getAttribute('data-tpl').replace(/<base>/g, base));\n }\n })();\n\n function copyCode(btn) {\n var pre = btn.closest('.curl-block').querySelector('.curl-code');\n var text = pre.getAttribute('data-tpl');\n if (!navigator.clipboard || !navigator.clipboard.writeText) {\n btn.textContent = 'Unavailable';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n return;\n }\n navigator.clipboard.writeText(text).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n }).catch(function() {\n btn.textContent = 'Failed';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n }\n </script>\n </body>\n</html>\n`;\n}\n","import { readFile } from 'node:fs/promises';\nimport * as https from 'node:https';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { serve } from '@hono/node-server';\nimport { serveStatic } from '@hono/node-server/serve-static';\nimport { swaggerUI } from '@hono/swagger-ui';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { ApiRoute, CorsOptions } from '@mastra/core/server';\nimport { Tool } from '@mastra/core/tools';\nimport { MastraServer, setupBrowserStream, skipIfFrameworkPublic } from '@mastra/hono';\nimport type { HonoBindings, HonoVariables } from '@mastra/hono';\nimport { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport { findMatchingCustomRoute } from '@mastra/server/auth';\nimport type { Context, MiddlewareHandler as HonoMiddlewareHandler } from 'hono';\nimport { Hono } from 'hono';\nimport { compress } from 'hono/compress';\nimport { cors } from 'hono/cors';\nimport { logger } from 'hono/logger';\nimport { timeout } from 'hono/timeout';\nimport { describeRoute } from 'hono-openapi';\nimport type { DescribeRouteOptions } from 'hono-openapi';\nimport { escapeStudioHtmlValue, injectStudioHtmlConfig, normalizeStudioBase } from '../build/utils';\nimport { agentLearningProxyHandler } from './handlers/agent-learning';\nimport { handleClientsRefresh, handleTriggerClientsRefresh, isHotReloadDisabled } from './handlers/client';\nimport { errorHandler } from './handlers/error';\nimport { healthHandler } from './handlers/health';\nimport { restartAllActiveWorkflowRunsHandler } from './handlers/restart-active-runs';\nimport { rootHandler } from './handlers/root';\nimport type { ServerBundleOptions } from './types';\nimport { welcomeHtml } from './welcome';\n\n// Get studio path from env or default to ./studio relative to cwd\nconst getStudioPath = () => {\n if (process.env.MASTRA_STUDIO_PATH) {\n return process.env.MASTRA_STUDIO_PATH;\n }\n\n let __dirname: string = '.';\n if (import.meta.url) {\n const __filename = fileURLToPath(import.meta.url);\n __dirname = dirname(__filename);\n }\n\n const studioPath = process.env.MASTRA_STUDIO_PATH || join(__dirname, 'studio');\n return studioPath;\n};\n\n// Use adapter type definitions\ntype Bindings = HonoBindings;\n\ntype Variables = HonoVariables & {\n clients: Set<{ controller: ReadableStreamDefaultController }>;\n};\n\ntype SchemaApiRoute = Extract<ApiRoute, { readonly _mastraSchemaRoute: true }>;\ntype HonoApiRoute = Exclude<ApiRoute, SchemaApiRoute>;\ntype ApiRouteMiddleware = Extract<Exclude<HonoApiRoute['middleware'], undefined>, Function>;\n\nfunction isSchemaApiRoute(route: ApiRoute): route is SchemaApiRoute {\n return '_mastraSchemaRoute' in route && route._mastraSchemaRoute === true;\n}\n\nconst DEFAULT_CORS_ALLOW_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];\nconst DEFAULT_CORS_ALLOW_HEADERS = [\n 'Content-Type',\n 'Authorization',\n 'A2A-Version',\n 'x-mastra-client-type',\n 'x-mastra-dev-playground',\n];\nconst DEFAULT_CORS_EXPOSE_HEADERS = ['Content-Length', 'X-Requested-With'];\n\nfunction getCorsConfig(serverCors: CorsOptions | false | undefined, credentialsDefault: boolean) {\n const userCors = serverCors && typeof serverCors === 'object' ? serverCors : undefined;\n const origin =\n userCors && 'origin' in userCors && userCors.origin\n ? userCors.origin\n : credentialsDefault\n ? (requestOrigin: string) => requestOrigin || undefined\n : '*';\n const credentials = userCors && 'credentials' in userCors ? userCors.credentials : credentialsDefault;\n\n return {\n origin,\n allowMethods: DEFAULT_CORS_ALLOW_METHODS,\n credentials,\n maxAge: 3600,\n ...userCors,\n allowHeaders: [...DEFAULT_CORS_ALLOW_HEADERS, ...(userCors?.allowHeaders ?? [])],\n exposeHeaders: [...DEFAULT_CORS_EXPOSE_HEADERS, ...(userCors?.exposeHeaders ?? [])],\n };\n}\n\nfunction getRouteCorsConfig(apiRoutes: ApiRoute[] | undefined, pathname: string, method: string) {\n const route = findMatchingCustomRoute(pathname, method, apiRoutes)?.route;\n return route && !isSchemaApiRoute(route) ? route.cors : undefined;\n}\n\nexport function getToolExports(tools: Record<string, Function>[]) {\n try {\n return tools.reduce((acc, toolModule) => {\n Object.entries(toolModule).forEach(([key, tool]) => {\n if (tool instanceof Tool) {\n acc[key] = tool;\n }\n });\n return acc;\n }, {});\n } catch (err: any) {\n console.error(\n `Failed to import tools\nreason: ${err.message}\n${err.stack.split('\\n').slice(1).join('\\n')}\n `,\n err,\n );\n }\n}\n\nexport async function createHonoServer(\n mastra: Mastra,\n options: ServerBundleOptions = {\n tools: {},\n },\n) {\n // Register bundled tools with Mastra so they can be used by stored agents\n // This bridges the gap between tools discovered by the CLI bundler and the Mastra instance\n if (options.tools) {\n for (const [key, tool] of Object.entries(options.tools)) {\n try {\n mastra.addTool(tool as any, key);\n } catch {\n // Tool may already be registered (e.g., if defined in Mastra config), ignore\n }\n }\n }\n\n // Create typed Hono app\n const app = new Hono<{ Bindings: Bindings; Variables: Variables }>();\n const server = mastra.getServer();\n const apiPrefix = server?.apiPrefix ?? '/api';\n const a2aTaskStore = new InMemoryTaskStore();\n const routes = server?.apiRoutes;\n\n // Pre-process routes: bake hono-openapi describeRoute into route middleware\n // so the adapter handles it as normal middleware without needing to know about hono-openapi\n const processedRoutes: ApiRoute[] | undefined = routes?.map(route => {\n if (isSchemaApiRoute(route)) {\n return route;\n }\n\n if (route.openapi) {\n const existingMiddleware = route.middleware\n ? Array.isArray(route.middleware)\n ? route.middleware\n : [route.middleware]\n : [];\n return {\n ...route,\n middleware: [\n describeRoute(route.openapi as unknown as DescribeRouteOptions) as unknown as ApiRouteMiddleware,\n ...existingMiddleware,\n ],\n };\n }\n return route;\n });\n\n // Store custom route auth configurations\n const customRouteAuthConfig = new Map<string, boolean>();\n\n if (processedRoutes) {\n for (const route of processedRoutes) {\n // By default, routes require authentication unless explicitly set to false\n const requiresAuth = route.requiresAuth !== false;\n const routeKey = `${route.method}:${route.path}`;\n customRouteAuthConfig.set(routeKey, requiresAuth);\n }\n }\n\n // Set up error handling - use custom onError handler if provided, otherwise use default\n const customOnError = server?.onError;\n app.onError((err, c) => {\n if (customOnError) {\n return customOnError(err, c as unknown as Parameters<typeof customOnError>[1]);\n }\n return errorHandler(err, c, options.isDev);\n });\n\n // Define body limit options\n const bodyLimitOptions = {\n maxSize: server?.bodySizeLimit ?? 4.5 * 1024 * 1024, // 4.5 MB,\n onError: () => ({ error: 'Request body too large' }),\n };\n\n // Create server adapter with all configuration\n const honoServerAdapter = new MastraServer({\n app,\n mastra,\n tools: options.tools,\n taskStore: a2aTaskStore,\n bodyLimitOptions,\n openapiPath: options?.isDev || server?.build?.openAPIDocs ? '/openapi.json' : undefined,\n customRouteAuthConfig,\n customApiRoutes: processedRoutes,\n prefix: apiPrefix,\n mcpOptions: server?.mcpOptions,\n });\n\n // Register context middleware FIRST - this sets mastra, requestContext, tools, taskStore in context\n // Cast needed due to Hono type variance - safe because registerContextMiddleware is generic\n honoServerAdapter.registerContextMiddleware();\n\n // Apply custom server middleware from Mastra instance\n const serverMiddleware = mastra.getServerMiddleware?.();\n\n if (serverMiddleware && serverMiddleware.length > 0) {\n for (const m of serverMiddleware) {\n // Wrap with skipIfFrameworkPublic so user middleware cannot 401 routes\n // the framework declared public via `requiresAuth: false`\n // (e.g. Studio sign-in endpoints like /api/auth/capabilities).\n app.use(m.path, skipIfFrameworkPublic(m.handler));\n }\n }\n\n // Browser stream WebSocket setup - MUST be before CORS middleware\n // to avoid \"can't modify immutable headers\" error on WebSocket upgrade\n // This is async because it dynamically imports @hono/node-ws to avoid\n // bundling ws into user code. Returns null if ws is not available.\n const browserStreamSetup =\n options.browserStream === false\n ? null\n : await setupBrowserStream(app, {\n getToolset: async (agentId: string) => {\n // Look up agent and return its browser if configured.\n // First try the runtime registry (code-defined + previously hydrated agents),\n // then fall back to the editor for stored agents (hydrates on first access).\n try {\n const runtimeAgent = mastra.getAgentById(agentId);\n if (runtimeAgent) {\n return runtimeAgent.browser;\n }\n } catch {\n // Agent not in runtime registry — try stored agents via editor\n }\n\n try {\n const storedAgent = await mastra.getEditor?.()?.agent.getById(agentId);\n return storedAgent?.browser;\n } catch {\n return undefined;\n }\n },\n apiPrefix,\n });\n\n // Fallback session probe when browser streaming isn't available\n // (ws / @hono/node-ws not installed, disabled by deployer, or serverless environment).\n // Lets the client decide not to open a WS instead of failing the upgrade.\n if (!browserStreamSetup) {\n app.get(`${apiPrefix}/agents/:agentId/browser/session`, c =>\n c.json({ hasSession: false, screencastAvailable: false }),\n );\n }\n\n // Global CORS config\n if (server?.cors === false) {\n app.use('*', timeout(server?.timeout ?? 3 * 60 * 1000));\n } else {\n const hasAuth = !!server?.auth;\n app.use('*', timeout(server?.timeout ?? 3 * 60 * 1000), async (c, next) => {\n const pathname = new URL(c.req.url).pathname;\n const method =\n c.req.method === 'OPTIONS' ? (c.req.header('Access-Control-Request-Method') ?? c.req.method) : c.req.method;\n const routeCors = getRouteCorsConfig(processedRoutes, pathname, method);\n\n const corsOptions = routeCors ? getCorsConfig(routeCors, false) : getCorsConfig(server?.cors, hasAuth);\n return cors(corsOptions as unknown as Parameters<typeof cors>[0])(c, next);\n });\n }\n\n // Health check endpoint (before auth middleware so it's publicly accessible)\n app.get(\n '/health',\n describeRoute({\n description: 'Health check endpoint',\n tags: ['system'],\n responses: {\n 200: {\n description: 'Service is healthy',\n },\n },\n }),\n healthHandler,\n );\n\n if (options?.isDev && options.studio) {\n app.get('/api/learning/*', agentLearningProxyHandler);\n }\n\n if (options?.isDev || server?.build?.swaggerUI) {\n app.get(\n apiPrefix,\n describeRoute({\n description: 'API Welcome Page',\n tags: ['system'],\n responses: {\n 200: {\n description: 'Success',\n },\n },\n }),\n rootHandler,\n );\n }\n\n // Validate EE license before starting (checks RBAC config vs license)\n await honoServerAdapter.validateEELicense();\n\n // Register auth middleware (authentication and authorization)\n // This is handled by the server adapter now\n honoServerAdapter.registerAuthMiddleware();\n\n if (server?.middleware) {\n const normalizedMiddlewares = Array.isArray(server.middleware) ? server.middleware : [server.middleware];\n const middlewares = normalizedMiddlewares.map(middleware => {\n if (typeof middleware === 'function') {\n return {\n path: '*',\n handler: middleware,\n };\n }\n\n return middleware;\n });\n\n for (const middleware of middlewares) {\n // Wrap with skipIfFrameworkPublic so user middleware cannot 401 routes\n // the framework declared public via `requiresAuth: false`\n // (e.g. Studio sign-in endpoints like /api/auth/capabilities).\n app.use(middleware.path, skipIfFrameworkPublic(middleware.handler as unknown as HonoMiddlewareHandler));\n }\n }\n\n // Register custom API routes via the adapter (auth + middleware handled uniformly)\n await honoServerAdapter.registerCustomApiRoutes();\n\n if (server?.build?.apiReqLogs) {\n app.use(logger());\n }\n\n // Register adapter routes (adapter was created earlier with configuration)\n // Cast needed due to Hono type variance - safe because registerRoutes is generic\n await honoServerAdapter.registerRoutes();\n\n if (options?.isDev || server?.build?.swaggerUI) {\n // Warn if Swagger UI is enabled but OpenAPI docs are not in production\n if (!options?.isDev && server?.build?.swaggerUI && !server?.build?.openAPIDocs) {\n const logger = mastra.getLogger();\n logger.warn(\n 'Swagger UI is enabled but OpenAPI documentation is disabled. ' +\n 'The Swagger UI will not function properly without the OpenAPI endpoint. ' +\n 'Please enable openAPIDocs in your server.build configuration:\\n' +\n ' server: { build: { swaggerUI: true, openAPIDocs: true } }',\n );\n }\n\n app.get(\n '/swagger-ui',\n describeRoute({\n hide: true,\n }),\n swaggerUI({ url: `${apiPrefix}/openapi.json` }),\n );\n }\n\n if (options?.isDev) {\n app.post(\n '/__restart-active-workflow-runs',\n describeRoute({\n hide: true,\n }),\n restartAllActiveWorkflowRunsHandler,\n );\n }\n\n const serverOptions = mastra.getServer();\n const studioBasePath = normalizeStudioBase(serverOptions?.studioBase ?? '/');\n\n if (options?.studio) {\n // SSE endpoint for refresh notifications\n app.get(\n `${studioBasePath}/refresh-events`,\n describeRoute({\n hide: true,\n }),\n handleClientsRefresh,\n );\n\n // Trigger refresh for all clients\n app.post(\n `${studioBasePath}/__refresh`,\n describeRoute({\n hide: true,\n }),\n handleTriggerClientsRefresh,\n );\n\n // Check hot reload status\n app.get(\n `${studioBasePath}/__hot-reload-status`,\n describeRoute({\n hide: true,\n }),\n (c: Context) => {\n return c.json({\n disabled: isHotReloadDisabled(),\n timestamp: new Date().toISOString(),\n });\n },\n );\n\n // Enable gzip/deflate compression for studio static assets only\n app.use(`${studioBasePath}/assets/*`, compress());\n\n // Studio routes - these should come after API routes\n // Serve static assets from studio directory\n // Note: Vite builds with base: './' so all asset URLs are relative\n // The <base href> tag in index.html handles path resolution for the SPA\n const studioPath = getStudioPath();\n app.use(\n `${studioBasePath}/assets/*`,\n serveStatic({\n root: join(studioPath, 'assets'),\n rewriteRequestPath: path => {\n // Remove the basePath AND /assets prefix to get the actual file path\n // Example: /custom-path/assets/style.css -> /style.css -> ./studio/assets/style.css\n let rewritten = path;\n if (studioBasePath && rewritten.startsWith(studioBasePath)) {\n rewritten = rewritten.slice(studioBasePath.length);\n }\n // Remove the /assets prefix since root is already './studio/assets'\n if (rewritten.startsWith('/assets')) {\n rewritten = rewritten.slice('/assets'.length);\n }\n return rewritten;\n },\n }),\n );\n }\n\n // Dynamic HTML handler - this must come before static file serving\n app.get('*', async (c, next) => {\n const requestPath = c.req.path;\n\n // Skip if it's an API route\n if (\n requestPath === apiPrefix ||\n requestPath.startsWith(`${apiPrefix}/`) ||\n requestPath.startsWith('/swagger-ui') ||\n requestPath.startsWith('/openapi.json')\n ) {\n return await next();\n }\n\n // Skip if it's an asset file (has extension other than .html)\n if (requestPath.includes('.') && !requestPath.endsWith('.html')) {\n return await next();\n }\n\n // Only serve studio for routes matching the configured base path\n const isStudioRoute =\n studioBasePath === '' || requestPath === studioBasePath || requestPath.startsWith(`${studioBasePath}/`);\n if (options?.studio && isStudioRoute) {\n // For HTML routes, serve index.html with dynamic replacements\n const studioPath = getStudioPath();\n let indexHtml = await readFile(join(studioPath, 'index.html'), 'utf-8');\n\n // Inject the server configuration into index.html placeholders\n const port = serverOptions?.port ?? (Number(process.env.PORT) || 4111);\n const hideCloudCta = process.env.MASTRA_HIDE_CLOUD_CTA === 'true';\n const bindHost = serverOptions?.host ?? process.env.MASTRA_HOST;\n const host = bindHost ?? 'localhost';\n const key =\n serverOptions?.https?.key ??\n (process.env.MASTRA_HTTPS_KEY ? Buffer.from(process.env.MASTRA_HTTPS_KEY, 'base64') : undefined);\n const cert =\n serverOptions?.https?.cert ??\n (process.env.MASTRA_HTTPS_CERT ? Buffer.from(process.env.MASTRA_HTTPS_CERT, 'base64') : undefined);\n const protocol = key && cert ? 'https' : 'http';\n // Studio host/protocol/port for Studio URL injection — allows bind address\n // (e.g. 0.0.0.0) to differ from the domain browsers should connect to\n const studioHost = serverOptions?.studioHost ?? host;\n const studioProtocol = serverOptions?.studioProtocol ?? protocol;\n const studioPort = serverOptions?.studioPort ?? port;\n\n const cloudApiEndpoint = process.env.MASTRA_CLOUD_API_ENDPOINT || '';\n const experimentalFeatures = process.env.EXPERIMENTAL_FEATURES === 'true' ? 'true' : 'false';\n const experimentalUI = process.env.MASTRA_EXPERIMENTAL_UI === 'true' ? 'true' : 'false';\n const templatesEnabled = process.env.MASTRA_TEMPLATES === 'true' ? 'true' : 'false';\n const agentSignals = process.env.MASTRA_AGENT_SIGNALS === 'false' ? 'false' : 'true';\n const signalsUI = process.env.MASTRA_SIGNALS_UI === 'true' ? 'true' : 'false';\n const organizationId = process.env.MASTRA_ORGANIZATION_ID || '';\n const platformProjectId = process.env.MASTRA_PLATFORM_PROJECT_ID || '';\n const platformObservabilityEndpoint = process.env.MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT || '';\n const requestContextPresets = process.env.MASTRA_REQUEST_CONTEXT_PRESETS || '';\n\n const autoDetectUrl = process.env.MASTRA_AUTO_DETECT_URL === 'true';\n\n indexHtml = injectStudioHtmlConfig(indexHtml, {\n host: `'${studioHost}'`,\n port: `'${studioPort}'`,\n protocol: `'${studioProtocol}'`,\n apiPrefix: `'${serverOptions?.apiPrefix ?? '/api'}'`,\n basePath: studioBasePath,\n hideCloudCta: `'${hideCloudCta}'`,\n cloudApiEndpoint: `'${escapeStudioHtmlValue(cloudApiEndpoint)}'`,\n experimentalFeatures: `'${experimentalFeatures}'`,\n templates: `'${templatesEnabled}'`,\n telemetryDisabled: `'${escapeStudioHtmlValue(process.env.MASTRA_TELEMETRY_DISABLED ?? '')}'`,\n requestContextPresets: `'${escapeStudioHtmlValue(requestContextPresets)}'`,\n experimentalUI: `'${experimentalUI}'`,\n agentSignals: `'${agentSignals}'`,\n signalsUI: `'${signalsUI}'`,\n organizationId: `'${escapeStudioHtmlValue(organizationId)}'`,\n platformProjectId: `'${escapeStudioHtmlValue(platformProjectId)}'`,\n platformObservabilityEndpoint: `'${escapeStudioHtmlValue(platformObservabilityEndpoint)}'`,\n autoDetectUrl: `'${autoDetectUrl}'`,\n });\n\n return c.newResponse(indexHtml, 200, { 'Content-Type': 'text/html' });\n }\n\n return c.newResponse(welcomeHtml(apiPrefix), 200, { 'Content-Type': 'text/html' });\n });\n\n if (options?.studio) {\n // Serve extra static files from studio directory (this comes after HTML handler)\n const studioRootPath = getStudioPath();\n const studioPath = studioBasePath ? `${studioBasePath}/*` : '*';\n app.use(\n studioPath,\n serveStatic({\n root: studioRootPath,\n rewriteRequestPath: path => {\n // Remove the basePath prefix if present\n if (studioBasePath && path.startsWith(studioBasePath)) {\n return path.slice(studioBasePath.length);\n }\n return path;\n },\n }),\n );\n }\n\n // Attach injectWebSocket to app for backwards compatibility\n // Consumers can use app directly, and optionally call app.injectWebSocket(server) for browser streaming\n (app as any).injectWebSocket = browserStreamSetup?.injectWebSocket;\n\n return app;\n}\n\nexport async function createNodeServer(mastra: Mastra, options: ServerBundleOptions = { tools: {} }) {\n const app = await createHonoServer(mastra, options);\n const injectWebSocket = (app as any).injectWebSocket;\n const serverOptions = mastra.getServer();\n const apiPrefix = serverOptions?.apiPrefix ?? '/api';\n\n const key =\n serverOptions?.https?.key ??\n (process.env.MASTRA_HTTPS_KEY ? Buffer.from(process.env.MASTRA_HTTPS_KEY, 'base64') : undefined);\n const cert =\n serverOptions?.https?.cert ??\n (process.env.MASTRA_HTTPS_CERT ? Buffer.from(process.env.MASTRA_HTTPS_CERT, 'base64') : undefined);\n const isHttpsEnabled = Boolean(key && cert);\n\n const bindHost = serverOptions?.host ?? process.env.MASTRA_HOST;\n const host = bindHost ?? 'localhost';\n const port = serverOptions?.port ?? (Number(process.env.PORT) || 4111);\n const protocol = isHttpsEnabled ? 'https' : 'http';\n const studioHost = serverOptions?.studioHost ?? host;\n const studioProtocol = serverOptions?.studioProtocol ?? protocol;\n const studioPort = serverOptions?.studioPort ?? port;\n\n const server = serve(\n {\n fetch: app.fetch,\n port,\n hostname: bindHost,\n ...(isHttpsEnabled\n ? {\n createServer: https.createServer,\n serverOptions: {\n key,\n cert,\n },\n }\n : {}),\n },\n () => {\n const logger = mastra.getLogger();\n logger.info('Mastra API running', { url: `${protocol}://${host}:${port}${apiPrefix}` });\n if (options?.studio) {\n const studioBasePath = normalizeStudioBase(serverOptions?.studioBase ?? '/');\n const studioUrl = `${studioProtocol}://${studioHost}:${studioPort}${studioBasePath}`;\n logger.info('Studio available', { url: studioUrl });\n }\n\n if (process.send) {\n process.send({\n type: 'server-ready',\n port,\n host,\n });\n }\n },\n );\n\n // Enable WebSocket support for browser streaming (if available)\n // MUST be called after serve() returns per @hono/node-ws requirements\n injectWebSocket?.(server);\n\n // Backwards compatibility for projects running a newer deployer/CLI with an older @mastra/core.\n // TODO(v2): call `mastra.startWorkers()` unconditionally once old core versions are unsupported.\n const workerLifecycle = mastra as unknown as {\n startWorkers?: () => Promise<void>;\n startEventEngine: () => Promise<void>;\n };\n if (typeof workerLifecycle.startWorkers === 'function') {\n await workerLifecycle.startWorkers();\n } else {\n await workerLifecycle.startEventEngine();\n }\n\n // Fire-and-forget anonymous token usage telemetry (respects MASTRA_TELEMETRY_DISABLED).\n // Dynamic import keeps compatibility with older @mastra/core versions without the\n // `@mastra/core/telemetry` entry point.\n void import('@mastra/core/telemetry').then(({ syncUsageTelemetry }) => syncUsageTelemetry(mastra)).catch(() => {});\n void import('@mastra/core/telemetry')\n .then(({ syncFeatureUsageTelemetry }) => syncFeatureUsageTelemetry(mastra))\n .catch(() => {});\n\n // Graceful shutdown so storage backends release resources (e.g. DuckDB's\n // native file lock) before the process exits. On `mastra dev` hot reloads\n // the old process is sent SIGINT; without this the lock can linger and the\n // restarted process fails with \"Conflicting lock is held\".\n const SHUTDOWN_TIMEOUT_MS = 5000;\n let shuttingDown = false;\n const shutdown = async (signal: NodeJS.Signals) => {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n const logger = mastra.getLogger();\n logger.info('Shutting down Mastra server', { signal });\n server.close();\n // Feature-detect for older @mastra/core versions without shutdown().\n const lifecycle = mastra as unknown as { shutdown?: () => Promise<void> };\n if (typeof lifecycle.shutdown === 'function') {\n // Bound the wait so a hanging shutdown can't block process exit.\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timedOut = Symbol('shutdown-timeout');\n const timeoutPromise = new Promise<typeof timedOut>(resolve => {\n timeout = setTimeout(() => resolve(timedOut), SHUTDOWN_TIMEOUT_MS);\n });\n try {\n const result = await Promise.race([lifecycle.shutdown(), timeoutPromise]);\n if (result === timedOut) {\n logger.warn('Mastra shutdown timed out; forcing exit', { timeoutMs: SHUTDOWN_TIMEOUT_MS });\n }\n } catch (error) {\n logger.error('Error during Mastra shutdown', { error });\n } finally {\n clearTimeout(timeout);\n }\n }\n process.exit(0);\n };\n process.once('SIGINT', () => void shutd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