File size: 47,813 Bytes
edaa6b9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 | Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_constants = require('./constants-BXAKTxRC.cjs');
let node_http = require("node:http");
let node_http2 = require("node:http2");
let node_stream = require("node:stream");
let hono_ws = require("hono/ws");
//#region src/error.ts
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
//#endregion
//#region src/headers.ts
const nonJoinedHeaders = new Set([
"age",
"authorization",
"content-length",
"content-type",
"etag",
"expires",
"from",
"host",
"if-modified-since",
"if-unmodified-since",
"last-modified",
"location",
"max-forwards",
"proxy-authorization",
"referer",
"retry-after",
"server",
"user-agent"
]);
const validHeaderName = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;
const isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;
const normalizeHeaderValue = (value) => {
if (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value;
let start = 0;
let end = value.length;
while (start < end && isHttpWhitespace(value.charCodeAt(start))) start++;
while (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--;
return value.slice(start, end);
};
const forbiddenHeaderValue = /[\0\r\n]/;
const GlobalHeaders = globalThis.Headers;
const materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => {
const headers = new HeadersCtor();
for (let i = 0; i < rawHeaders.length; i += 2) {
const name = rawHeaders[i];
if (!name.startsWith(":")) headers.append(name, rawHeaders[i + 1]);
}
return headers;
};
var RequestHeaders = class {
#incoming;
#rawHeaders;
#headers;
#invalidValue;
constructor(incoming) {
this.#incoming = incoming;
if (incoming instanceof node_http2.Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice();
}
get #lazyRawHeaders() {
return this.#rawHeaders ??= this.#incoming.rawHeaders.slice();
}
get #native() {
if (!this.#headers) {
this.#headers = materializeHeaders(this.#lazyRawHeaders);
this.#rawHeaders = void 0;
}
return this.#headers;
}
#normalizedName(name) {
if (typeof name !== "string") return;
if (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`);
return name.toLowerCase();
}
#lookupHttp1(lowerName) {
const headers = this.#incoming instanceof node_http2.Http2ServerRequest ? void 0 : this.#incoming.headers;
if (!headers || nonJoinedHeaders.has(lowerName) || lowerName === "set-cookie" || lowerName === "__proto__") return;
if (!Object.hasOwn(headers, lowerName)) return null;
const rawValue = headers[lowerName];
if (typeof rawValue === "string") {
const value = normalizeHeaderValue(rawValue);
return forbiddenHeaderValue.test(value) ? void 0 : value;
}
}
#lookup(rawHeaders, lowerName) {
const separator = lowerName === "cookie" ? "; " : ", ";
let value = null;
for (let i = 0; i < rawHeaders.length; i += 2) {
const rawName = rawHeaders[i];
if (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) {
const rawValue = normalizeHeaderValue(rawHeaders[i + 1]);
if (forbiddenHeaderValue.test(rawValue)) {
this.#invalidValue = true;
return;
}
value = value === null ? rawValue : value + separator + rawValue;
}
}
return value;
}
append(name, value) {
this.#native.append(name, value);
}
delete(name) {
this.#native.delete(name);
}
get(name) {
const lowerName = this.#normalizedName(name);
if (lowerName && !this.#headers && !this.#invalidValue) {
const http1Value = this.#lookupHttp1(lowerName);
if (http1Value !== void 0) return http1Value;
const value = this.#lookup(this.#lazyRawHeaders, lowerName);
if (value !== void 0) return value;
}
return this.#native.get(name);
}
has(name) {
const lowerName = this.#normalizedName(name);
if (lowerName && !this.#headers && !this.#invalidValue) {
const http1Value = this.#lookupHttp1(lowerName);
if (http1Value !== void 0) return http1Value !== null;
const value = this.#lookup(this.#lazyRawHeaders, lowerName);
if (value !== void 0) return value !== null;
}
return this.#native.has(name);
}
set(name, value) {
this.#native.set(name, value);
}
getSetCookie() {
return this.#native.getSetCookie();
}
keys() {
return this.#native.keys();
}
values() {
return this.#native.values();
}
entries() {
return this.#native.entries();
}
forEach(callback, thisArg) {
this.#native.forEach((value, key) => {
callback.call(thisArg, value, key, this);
});
}
[Symbol.iterator]() {
return this.entries();
}
};
Object.defineProperty(RequestHeaders.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
return `Headers (lightweight) ${inspectFn(Object.fromEntries(this), {
...options,
depth: depth == null ? null : depth - 1
})}`;
} });
Object.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);
const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);
//#endregion
//#region src/url.ts
const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
const validateRequestTarget = (target) => {
const backslash = target.indexOf("\\");
if (backslash !== -1) {
const query = target.indexOf("?");
if (query === -1 || backslash < query) throw new RequestError("Backslash in request path");
}
};
const buildUrl = (scheme, host, incomingUrl) => {
const url = `${scheme}://${host}${incomingUrl}`;
if (!reValidHost.test(host)) {
validateRequestTarget(incomingUrl);
const urlObj = new URL(url);
if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
return urlObj.href;
} else if (incomingUrl.length === 0) return url + "/";
else {
if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) {
validateRequestTarget(incomingUrl);
return new URL(url).href;
}
return url;
}
};
//#endregion
//#region src/request.ts
const toRequestError = (e) => {
if (e instanceof RequestError) return e;
return new RequestError(e.message, { cause: e });
};
const GlobalRequest = global.Request;
var Request$1 = class Request$1 extends GlobalRequest {
static [Symbol.hasInstance](instance) {
if (this === Request$1) return instance instanceof GlobalRequest || Function.prototype[Symbol.hasInstance].call(this, instance);
return Function.prototype[Symbol.hasInstance].call(this, instance);
}
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
input = input[getRequestCache]();
}
if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
super(input, options);
}
};
const wrapBodyStream = Symbol("wrapBodyStream");
const byteExactEncodings = new Set([
"latin1",
"binary",
"hex",
"base64",
"base64url"
]);
const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof node_http2.Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
const recordBodyBufferedBeforeDisconnect = (incoming) => {
if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
const incomingWithRecovery = incoming;
incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
};
const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
const incomingWithRecovery = incoming;
if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
let result;
const errored = incoming.errored;
if (errored && errored.code !== "ECONNRESET") result = errored;
else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
else {
const bodyChunks = chunks ?? [];
let chunk;
while ((chunk = incoming.read()) !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
result = buffer;
const contentLength = incoming.headers["content-length"];
if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
const expectedLength = Number(contentLength);
if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
}
}
incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
return result;
};
const enqueueBufferedBody = (controller, buffered) => {
if (buffered instanceof Error) {
controller.error(buffered);
return;
}
if (buffered.length > 0) controller.enqueue(buffered);
controller.close();
};
const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request$1(url, init);
Object.defineProperty(req, "method", { get() {
return "TRACE";
} });
return req;
}
if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
} });
else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({ async pull(controller) {
try {
if (!reader) {
const buffered = readBodyBufferedBeforeDisconnect(incoming);
if (buffered !== void 0) {
enqueueBufferedBody(controller, buffered);
return;
}
}
reader ||= node_stream.Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) controller.close();
else controller.enqueue(value);
} catch (error) {
controller.error(error);
}
} });
} else {
const buffered = readBodyBufferedBeforeDisconnect(incoming);
if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
enqueueBufferedBody(controller, buffered);
} });
else init.body = node_stream.Readable.toWeb(incoming);
}
return new Request$1(url, init);
};
const getRequestCache = Symbol("getRequestCache");
const requestCache = Symbol("requestCache");
const incomingKey = Symbol("incomingKey");
const urlKey = Symbol("urlKey");
const methodKey = Symbol("methodKey");
const headersKey = Symbol("headersKey");
const abortControllerKey = Symbol("abortControllerKey");
const getAbortController = Symbol("getAbortController");
const abortRequest = Symbol("abortRequest");
const bodyBufferKey = Symbol("bodyBuffer");
const bodyReadPromiseKey = Symbol("bodyReadPromise");
const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
const bodyLockReaderKey = Symbol("bodyLockReader");
const abortReasonKey = Symbol("abortReason");
const newBodyUnusableError = () => {
return /* @__PURE__ */ new TypeError("Body is unusable");
};
const rejectBodyUnusable = () => {
return Promise.reject(newBodyUnusableError());
};
const textDecoder = new TextDecoder();
const consumeBodyDirectOnce = (request) => {
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
request[bodyConsumedDirectlyKey] = true;
};
const toArrayBuffer = (buf) => {
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
};
const contentType = (request) => {
return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
};
const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
const normalizeIncomingMethod = (method) => {
if (typeof method !== "string" || method.length === 0) return "GET";
switch (method) {
case "DELETE":
case "GET":
case "HEAD":
case "OPTIONS":
case "PATCH":
case "POST":
case "PUT":
case "QUERY": return method;
}
const upper = method.toUpperCase();
switch (upper) {
case "DELETE":
case "GET":
case "HEAD":
case "OPTIONS":
case "POST":
case "PUT": return upper;
default: return method;
}
};
const validateDirectReadMethod = (method) => {
if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
const normalized = method.toUpperCase();
if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
};
const readBodyWithFastPath = (request, method, fromBuffer) => {
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
const methodName = request.method;
if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
const methodValidationError = validateDirectReadMethod(methodName);
if (methodValidationError) return Promise.reject(methodValidationError);
if (request[requestCache]) {
if (methodName !== "TRACE") return request[requestCache][method]();
}
const alreadyUsedError = consumeBodyDirectOnce(request);
if (alreadyUsedError) return alreadyUsedError;
const raw = readRawBodyIfAvailable(request);
if (raw) {
const result = Promise.resolve(fromBuffer(raw, request));
request[bodyBufferKey] = void 0;
return result;
}
return readBodyDirect(request).then((buf) => {
const result = fromBuffer(buf, request);
request[bodyBufferKey] = void 0;
return result;
});
};
const readRawBodyIfAvailable = (request) => {
const incoming = request[incomingKey];
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
};
const normalizeAbortError = (request, incoming) => {
if (incoming.errored) return incoming.errored;
const reason = request[abortReasonKey];
if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
return /* @__PURE__ */ new Error("Client connection prematurely closed.");
};
const readBodyDirect = (request) => {
if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
const incoming = request[incomingKey];
if (incoming.readableDidRead) return rejectBodyUnusable();
const buffered = readBodyBufferedBeforeDisconnect(incoming);
if (buffered !== void 0) {
if (buffered instanceof Error) return Promise.reject(buffered);
request[bodyBufferKey] = buffered;
return Promise.resolve(buffered);
}
const promise = new Promise((resolve, reject) => {
const chunks = [];
let settled = false;
const finish = (callback) => {
if (settled) return;
settled = true;
cleanup();
callback();
};
const recoverCompleteBodyAfterDisconnect = (error) => {
const streamError = incoming.errored ?? error;
if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
finish(() => {
const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
if (recovered instanceof Error) reject(recovered);
else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
else {
request[bodyBufferKey] = recovered;
resolve(recovered);
}
});
return true;
};
const onData = (chunk) => {
chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
};
const onEnd = () => {
finish(() => {
const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
request[bodyBufferKey] = buffer;
resolve(buffer);
});
};
const onError = (error) => {
if (recoverCompleteBodyAfterDisconnect(error)) return;
finish(() => {
reject(error);
});
};
const onClose = () => {
if (incoming.readableEnded) {
onEnd();
return;
}
if (recoverCompleteBodyAfterDisconnect()) return;
finish(() => {
reject(normalizeAbortError(request, incoming));
});
};
const cleanup = () => {
incoming.off("data", onData);
incoming.off("end", onEnd);
incoming.off("error", onError);
incoming.off("close", onClose);
request[bodyReadPromiseKey] = void 0;
};
incoming.on("data", onData);
incoming.on("end", onEnd);
incoming.on("error", onError);
incoming.on("close", onClose);
queueMicrotask(() => {
if (settled) return;
if (incoming.readableEnded) onEnd();
else if (incoming.errored) onError(incoming.errored);
else if (incoming.destroyed) onClose();
});
});
request[bodyReadPromiseKey] = promise;
return promise;
};
const requestPrototype = {
get method() {
return this[methodKey];
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[abortRequest](reason) {
if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
const abortController = this[abortControllerKey];
if (abortController && !abortController.signal.aborted) abortController.abort(reason);
},
[getAbortController]() {
this[abortControllerKey] ||= new AbortController();
if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
return this[abortControllerKey];
},
[getRequestCache]() {
const abortController = this[getAbortController]();
if (this[requestCache]) return this[requestCache];
const method = this.method;
if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
this[bodyBufferKey] = void 0;
const init = {
method: method === "TRACE" ? "GET" : method,
headers: this.headers,
signal: abortController.signal
};
if (method !== "TRACE") {
init.body = new ReadableStream({ start(c) {
c.close();
} });
init.duplex = "half";
}
const req = new Request$1(this[urlKey], init);
if (method === "TRACE") Object.defineProperty(req, "method", { get() {
return "TRACE";
} });
return this[requestCache] = req;
}
return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
},
get body() {
if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
const request = this[getRequestCache]();
if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
return request.body;
},
get bodyUsed() {
if (this[bodyConsumedDirectlyKey]) return true;
if (this[requestCache]) return this[requestCache].bodyUsed;
return false;
}
};
Object.defineProperty(requestPrototype, "signal", { get() {
return this[getAbortController]().signal;
} });
[
"cache",
"credentials",
"destination",
"duplex",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, { get() {
return this[getRequestCache]()[k];
} });
});
["clone", "formData"].forEach((k) => {
Object.defineProperty(requestPrototype, k, { value: function() {
if (this[bodyConsumedDirectlyKey]) {
if (k === "clone") throw newBodyUnusableError();
return rejectBodyUnusable();
}
return this[getRequestCache]()[k]();
} });
});
Object.defineProperty(requestPrototype, "text", { value: function() {
return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
} });
Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
} });
Object.defineProperty(requestPrototype, "blob", { value: function() {
return readBodyWithFastPath(this, "blob", (buf, request) => {
const type = contentType(request);
const init = type ? { headers: { "content-type": type } } : void 0;
return new Response(buf, init).blob();
});
} });
Object.defineProperty(requestPrototype, "bytes", { value: function() {
return this.arrayBuffer().then((buf) => new Uint8Array(buf));
} });
Object.defineProperty(requestPrototype, "json", { value: function() {
if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
return this.text().then(JSON.parse);
} });
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
return `Request (lightweight) ${inspectFn({
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
}, {
...options,
depth: depth == null ? null : depth - 1
})}`;
} });
Object.setPrototypeOf(requestPrototype, Request$1.prototype);
const newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
req[methodKey] = normalizeIncomingMethod(incoming.method);
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof node_http2.Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
try {
validateRequestTarget(incomingUrl);
req[urlKey] = new URL(incomingUrl).href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) throw new RequestError("Missing host header");
let scheme;
if (incoming instanceof node_http2.Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
} else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
try {
req[urlKey] = buildUrl(scheme, host, incomingUrl);
} catch (e) {
if (e instanceof RequestError) throw e;
else throw new RequestError("Invalid URL", { cause: e });
}
return req;
};
//#endregion
//#region src/response.ts
const defaultContentType = "text/plain; charset=UTF-8";
const responseCache = Symbol("responseCache");
const getResponseCache = Symbol("getResponseCache");
const cacheKey = Symbol("cache");
const GlobalResponse = global.Response;
var Response$1 = class Response$1 {
#body;
#init;
static [Symbol.hasInstance](instance) {
if (this === Response$1) return instance instanceof GlobalResponse || Function.prototype[Symbol.hasInstance].call(this, instance);
return Function.prototype[Symbol.hasInstance].call(this, instance);
}
[getResponseCache]() {
const cache = this[cacheKey];
const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
status: this.#init?.status,
statusText: this.#init?.statusText,
headers: liveHeaders
} : this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof GlobalResponse) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
}
this.#init = #init in init ? init.#init : init;
headers = new Headers(init.headers);
} else this.#init = init;
if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
init?.status || 200,
body ?? null,
headers || init?.headers
];
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
[
"body",
"bodyUsed",
"redirected",
"statusText",
"trailers",
"type",
"url"
].forEach((k) => {
Object.defineProperty(Response$1.prototype, k, { get() {
return this[getResponseCache]()[k];
} });
});
[
"arrayBuffer",
"blob",
"bytes",
"clone",
"formData",
"json",
"text"
].forEach((k) => {
Object.defineProperty(Response$1.prototype, k, { value: function() {
return this[getResponseCache]()[k]();
} });
});
Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
return `Response (lightweight) ${inspectFn({
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
}, {
...options,
depth: depth == null ? null : depth - 1
})}`;
} });
Object.setPrototypeOf(Response$1, GlobalResponse);
Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
const parseRedirectUrl = (url) => {
if (url instanceof URL) return url.href;
if (validRedirectUrl.test(url)) return url;
return new URL(url).href;
};
const validRedirectStatuses = new Set([
301,
302,
303,
307,
308
]);
Object.defineProperty(Response$1, "redirect", {
value: function redirect(url, status = 302) {
if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
return new Response$1(null, {
status,
headers: { location: parseRedirectUrl(url) }
});
},
writable: true,
configurable: true
});
Object.defineProperty(Response$1, "json", {
value: function json(data, init) {
const body = JSON.stringify(data);
if (body === void 0) throw new TypeError("The data is not JSON serializable");
const initHeaders = init?.headers;
let headers;
if (initHeaders) {
headers = new Headers(initHeaders);
if (!headers.has("content-type")) headers.set("content-type", "application/json");
} else headers = { "content-type": "application/json" };
return new Response$1(body, {
status: init?.status ?? 200,
statusText: init?.statusText,
headers
});
},
writable: true,
configurable: true
});
//#endregion
//#region src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {});
};
const stream = writable.stream;
if (writable.destroyed || stream?.closed || stream?.destroyed) {
cancel();
return reader.closed;
}
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) writable.destroy(error);
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) writable.end();
else if (!writable.write(value)) writable.once("drain", onDrain);
else reader.read().then(flow, handleStreamError);
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) throw new TypeError("ReadableStream is locked.");
else if (writable.destroyed) {
stream.cancel().catch(() => {});
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
const res = {};
if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
if (headers.has("set-cookie")) {
const cookies = [];
for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
else res[k] = v;
if (cookies.length > 0) res["set-cookie"] = cookies;
} else for (const [k, v] of headers) res[k] = v;
if (defaultContentType) res["content-type"] ??= defaultContentType;
return res;
};
//#endregion
//#region src/listener.ts
const outgoingEnded = Symbol("outgoingEnded");
const incomingDraining = Symbol("incomingDraining");
const DRAIN_TIMEOUT_MS = 500;
const MAX_DRAIN_BYTES = 64 * 1024 * 1024;
const drainIncoming = (incoming) => {
const incomingWithDrainState = incoming;
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
incomingWithDrainState[incomingDraining] = true;
if (incoming instanceof node_http2.Http2ServerRequest) {
try {
incoming.stream?.close?.(node_http2.constants.NGHTTP2_NO_ERROR);
} catch {}
return;
}
let bytesRead = 0;
const cleanup = () => {
clearTimeout(timer);
incoming.off("data", onData);
incoming.off("end", cleanup);
incoming.off("error", cleanup);
};
const forceClose = () => {
cleanup();
const socket = incoming.socket;
if (socket && !socket.destroyed) {
if (typeof socket.destroySoon === "function") socket.destroySoon();
else if (typeof socket.destroy === "function") socket.destroy();
}
};
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
timer.unref?.();
const onData = (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_DRAIN_BYTES) forceClose();
};
incoming.on("data", onData);
incoming.on("end", cleanup);
incoming.on("error", cleanup);
incoming.resume();
};
const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
if (incoming.errored) {
recordBodyBufferedBeforeDisconnect(incoming);
req[abortRequest](incoming.errored.toString());
} else if (!outgoing.writableFinished || incoming instanceof node_http2.Http2ServerRequest && incoming.aborted) {
recordBodyBufferedBeforeDisconnect(incoming);
req[abortRequest]("Client connection prematurely closed.");
}
if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
if (!incoming.readableEnded) setTimeout(() => {
drainIncoming(incoming);
});
});
};
const isImmediateCacheableResponse = (res) => {
if (!(cacheKey in res)) return false;
const body = res[cacheKey][1];
return body === null || typeof body === "string" || body instanceof Uint8Array;
};
const handleRequestError = () => new Response(null, { status: 400 });
const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
const handleResponseError = (e, outgoing) => {
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
else {
console.error(e);
if (!outgoing.headersSent) {
if (outgoing instanceof node_http.ServerResponse) outgoing._contentLength = null;
outgoing.writeHead(500, { "Content-Type": "text/plain" });
}
outgoing.end(`Error: ${err.message}`);
outgoing.destroy(err);
}
};
const flushHeaders = (outgoing) => {
if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
};
const trySetContentLength = (outgoing, status, length) => {
const http1 = outgoing;
if (http1._contentLength === null && http1._hasBody && http1.useChunkedEncodingByDefault && !http1._removedContLen && status >= 200 && status !== 204 && status !== 304 && !outgoing.hasHeader("content-length") && !outgoing.hasHeader("transfer-encoding") && !outgoing.hasHeader("trailer")) {
http1._contentLength = length;
return true;
}
return false;
};
const writeDefaultHeaders = (outgoing, status, length) => {
if (trySetContentLength(outgoing, status, length)) outgoing.writeHead(status, { "Content-Type": defaultContentType });
else outgoing.writeHead(status, {
"Content-Type": defaultContentType,
"Content-Length": length
});
};
const responseViaCache = async (res, outgoing) => {
let [status, body, header] = res[cacheKey];
if (!header) {
if (body === null) {
outgoing.writeHead(status);
outgoing.end();
} else if (typeof body === "string") {
writeDefaultHeaders(outgoing, status, Buffer.byteLength(body));
outgoing.end(body);
} else if (body instanceof Uint8Array) {
writeDefaultHeaders(outgoing, status, body.byteLength);
outgoing.end(body);
} else if (body instanceof Blob) {
writeDefaultHeaders(outgoing, status, body.size);
outgoing.end(new Uint8Array(await body.arrayBuffer()));
} else {
outgoing.writeHead(status, { "Content-Type": defaultContentType });
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
}
outgoing[outgoingEnded]?.();
return;
}
let hasContentLength = false;
let plainHeaders = false;
let canAutoLength = true;
if (header instanceof Headers) {
hasContentLength = header.has("content-length");
header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
} else if (Array.isArray(header)) {
const headerObj = new Headers(header);
hasContentLength = headerObj.has("content-length");
header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
} else {
plainHeaders = true;
for (const key in header) {
if (key.length === 14 && key.toLowerCase() === "content-length") {
hasContentLength = true;
break;
}
if (key.length === 17 && key.toLowerCase() === "transfer-encoding" || key.length === 7 && key.toLowerCase() === "trailer") canAutoLength = false;
}
}
if (!hasContentLength) {
let length;
if (typeof body === "string") length = Buffer.byteLength(body);
else if (body instanceof Uint8Array) length = body.byteLength;
else if (body instanceof Blob) length = body.size;
if (length !== void 0 && (!plainHeaders || !canAutoLength || !trySetContentLength(outgoing, status, length))) {
if (plainHeaders) header = { ...header };
header["Content-Length"] = length;
}
}
outgoing.writeHead(status, header);
if (body == null) outgoing.end();
else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
else {
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
}
outgoing[outgoingEnded]?.();
};
const isPromise = (res) => typeof res.then === "function";
const responseViaResponseObject = async (res, outgoing, options = {}) => {
if (isPromise(res)) if (options.errorHandler) try {
res = await res;
} catch (err) {
const errRes = await options.errorHandler(err);
if (!errRes) return;
res = errRes;
}
else res = await res.catch(handleFetchError);
if (cacheKey in res) return responseViaCache(res, outgoing);
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
if (res.body) {
const reader = res.body.getReader();
const values = [];
let done = false;
let currentReadPromise = void 0;
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
let maxReadCount = 2;
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read();
const chunk = await readWithoutBlocking(currentReadPromise);
if (!chunk) {
if (i === 1) {
await new Promise((resolve) => setTimeout(resolve));
maxReadCount = 3;
continue;
}
break;
}
currentReadPromise = void 0;
if (chunk.value) values.push(chunk.value);
if (chunk.done) {
done = true;
break;
}
}
if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
}
outgoing.writeHead(res.status, resHeaderRecord);
values.forEach((value) => {
outgoing.write(value);
});
if (done) outgoing.end();
else {
if (values.length === 0) flushHeaders(outgoing);
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
}
} else if (resHeaderRecord[require_constants.X_ALREADY_SENT]) {} else {
outgoing.writeHead(res.status, resHeaderRecord);
outgoing.end();
}
outgoing[outgoingEnded]?.();
};
const getRequestListener = (fetchCallback, options = {}) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
Object.defineProperty(global, "Request", { value: Request$1 });
Object.defineProperty(global, "Response", { value: Response$1 });
}
return async (incoming, outgoing) => {
let res, req;
let needsBodyCleanup = false;
let closeHandlerAttached = false;
const ensureCloseHandler = () => {
if (!req || closeHandlerAttached) return;
closeHandlerAttached = true;
outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
};
try {
req = newRequest(incoming, options.hostname);
needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
if (needsBodyCleanup) {
incoming[wrapBodyStream] = true;
if (incoming instanceof node_http2.Http2ServerRequest) outgoing[outgoingEnded] = () => {
if (!incoming.readableEnded) setTimeout(() => {
if (!incoming.readableEnded) setTimeout(() => {
incoming.destroy();
outgoing.destroy();
});
});
};
}
res = fetchCallback(req, {
incoming,
outgoing
});
if (!isPromise(res) && isImmediateCacheableResponse(res)) {
if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
if (!incoming.readableEnded) drainIncoming(incoming);
});
return responseViaCache(res, outgoing);
}
ensureCloseHandler();
} catch (e) {
if (!res) if (options.errorHandler) {
ensureCloseHandler();
res = await options.errorHandler(req ? e : toRequestError(e));
if (!res) return;
} else if (!req) res = handleRequestError();
else res = handleFetchError(e);
else return handleResponseError(e, outgoing);
}
try {
return await responseViaResponseObject(res, outgoing, options);
} catch (e) {
return handleResponseError(e, outgoing);
}
};
};
//#endregion
//#region src/websocket.ts
/**
* @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
*/
const CloseEvent = globalThis.CloseEvent ?? class extends Event {
#eventInitDict;
constructor(type, eventInitDict = {}) {
super(type, eventInitDict);
this.#eventInitDict = eventInitDict;
}
get wasClean() {
return this.#eventInitDict.wasClean ?? false;
}
get code() {
return this.#eventInitDict.code ?? 0;
}
get reason() {
return this.#eventInitDict.reason ?? "";
}
};
/**
* Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.
* @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
*/
const ErrorEvent = globalThis.ErrorEvent ?? class extends Event {
#eventInitDict;
constructor(type, eventInitDict = {}) {
super(type, eventInitDict);
this.#eventInitDict = eventInitDict;
}
get message() {
return this.#eventInitDict.message ?? "";
}
get filename() {
return this.#eventInitDict.filename ?? "";
}
get lineno() {
return this.#eventInitDict.lineno ?? 0;
}
get colno() {
return this.#eventInitDict.colno ?? 0;
}
get error() {
return this.#eventInitDict.error ?? null;
}
};
const generateConnectionSymbol = () => Symbol("connection");
const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
const responseHeadersToSkip = new Set([
"connection",
"content-length",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"sec-websocket-accept",
"sec-websocket-extensions",
"sec-websocket-protocol"
]);
const appendResponseHeaders = (headers, responseHeaders) => {
if (!responseHeaders) return;
responseHeaders.forEach((value, key) => {
if (responseHeadersToSkip.has(key.toLowerCase())) return;
headers.push(`${key}: ${value}`);
});
};
const rejectUpgradeRequest = (socket, status, responseHeaders) => {
if (socket.destroyed) return;
const responseLines = ["Connection: close", "Content-Length: 0"];
appendResponseHeaders(responseLines, responseHeaders);
socket.end(`HTTP/1.1 ${status.toString()} ${node_http.STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
`);
};
const createUpgradeRequest = (request) => {
const protocol = request.socket.encrypted ? "https" : "http";
const incomingUrl = request.url ?? "/";
let url;
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
validateRequestTarget(incomingUrl);
url = new URL(incomingUrl).href;
} else url = buildUrl(protocol, request.headers.host ?? "localhost", incomingUrl);
const headers = new Headers();
for (const key in request.headers) {
const value = request.headers[key];
if (!value) continue;
headers.append(key, Array.isArray(value) ? value[0] : value);
}
return new Request(url, { headers });
};
const setupWebSocket = (options) => {
const { server, fetchCallback, wss } = options;
const waiterMap = /* @__PURE__ */ new Map();
wss.on("connection", (ws, request) => {
const waiter = waiterMap.get(request);
if (waiter) {
waiter.resolve(ws);
waiterMap.delete(request);
}
});
const rejectWaiter = (request) => {
const waiter = waiterMap.get(request);
if (waiter) {
waiterMap.delete(request);
waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted"));
}
};
const waitForWebSocket = (request, connectionSymbol) => {
return new Promise((resolve, reject) => {
waiterMap.set(request, {
resolve,
reject,
connectionSymbol
});
});
};
server.on("upgrade", async (request, socket, head) => {
const ignoreSocketError = () => {};
socket.on("error", ignoreSocketError);
if (request.headers.upgrade?.toLowerCase() !== "websocket") {
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 400);
return;
}
const reclaimWaiterOnClose = () => rejectWaiter(request);
socket.once("close", reclaimWaiterOnClose);
const env = {
incoming: request,
outgoing: void 0,
wss,
[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
};
let status = 400;
let responseHeaders;
try {
const response = await fetchCallback(createUpgradeRequest(request), env);
if (response instanceof Response) {
status = response.status;
responseHeaders = response.headers;
}
} catch (error) {
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, error instanceof RequestError ? 400 : 500);
return;
}
if (socket.destroyed) {
rejectWaiter(request);
return;
}
const waiter = waiterMap.get(request);
if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
rejectWaiter(request);
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
return;
}
const addResponseHeaders = (headers) => {
appendResponseHeaders(headers, responseHeaders);
};
wss.on("headers", addResponseHeaders);
try {
wss.handleUpgrade(request, socket, head, (ws) => {
socket.off("close", reclaimWaiterOnClose);
socket.off("error", ignoreSocketError);
wss.emit("connection", ws, request);
});
} finally {
wss.off("headers", addResponseHeaders);
}
});
server.on("close", () => {
wss.close();
});
};
const upgradeWebSocket = (0, hono_ws.defineWebSocketHelper)(async (c, events, options) => {
if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return;
const env = c.env;
const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });
const connectionSymbol = generateConnectionSymbol();
env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
(async () => {
let ws;
try {
ws = await waitForWebSocket(env.incoming, connectionSymbol);
} catch {
return;
}
const messagesReceivedInStarting = [];
const bufferMessage = (data, isBinary) => {
messagesReceivedInStarting.push([data, isBinary]);
};
ws.on("message", bufferMessage);
const ctx = {
binaryType: "arraybuffer",
close(code, reason) {
ws.close(code, reason);
},
protocol: ws.protocol,
raw: ws,
get readyState() {
return ws.readyState;
},
send(source, opts) {
ws.send(source, { compress: opts?.compress });
},
url: new URL(c.req.url)
};
try {
events?.onOpen?.(new Event("open"), ctx);
} catch (e) {
(options?.onError ?? console.error)(e);
}
const handleMessage = (data, isBinary) => {
const datas = Array.isArray(data) ? data : [data];
for (const data of datas) try {
events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === "string" ? data : Buffer.from(data).toString("utf-8") }), ctx);
} catch (e) {
(options?.onError ?? console.error)(e);
}
};
ws.off("message", bufferMessage);
for (const message of messagesReceivedInStarting) handleMessage(...message);
ws.on("message", (data, isBinary) => {
handleMessage(data, isBinary);
});
ws.on("close", (code, reason) => {
try {
events?.onClose?.(new CloseEvent("close", {
code,
reason: reason.toString()
}), ctx);
} catch (e) {
(options?.onError ?? console.error)(e);
}
});
ws.on("error", (error) => {
try {
events?.onError?.(new ErrorEvent("error", { error }), ctx);
} catch (e) {
(options?.onError ?? console.error)(e);
}
});
})();
return new Response();
});
//#endregion
//#region src/server.ts
const createAdaptorServer = (options) => {
const fetchCallback = options.fetch;
const requestListener = getRequestListener(fetchCallback, {
hostname: options.hostname,
overrideGlobalObjects: options.overrideGlobalObjects,
autoCleanupIncoming: options.autoCleanupIncoming
});
const server = (options.createServer || node_http.createServer)(options.serverOptions || {}, requestListener);
if (options.websocket && options.websocket.server) {
if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
setupWebSocket({
server,
fetchCallback,
wss: options.websocket.server
});
}
return server;
};
const serve = (options, listeningListener) => {
const server = createAdaptorServer(options);
server.listen(options?.port ?? 3e3, options.hostname, () => {
const serverInfo = server.address();
listeningListener && listeningListener(serverInfo);
});
return server;
};
//#endregion
exports.RequestError = RequestError;
exports.createAdaptorServer = createAdaptorServer;
exports.getRequestListener = getRequestListener;
exports.serve = serve;
exports.upgradeWebSocket = upgradeWebSocket; |