@znight/http 0.1.2 → 0.1.3

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.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { n as RouteTable, t as nodeAdapter } from "./node-Clm1Ia7T.mjs";
2
- import { $ as UnprocessableEntityException, A as serializeCookie, B as ConflictException, C as decodeCookieValue, D as parseCookieHeader, E as isCookieName, F as isStreamSource, G as InternalServerErrorException, H as GatewayTimeoutException, I as toByteStream, J as NotImplementedException, K as MethodNotAllowedException, L as trackStream, M as captureContext, N as discardStream, O as parseSetCookie, P as isByteStream, Q as UnauthorizedException, R as BadGatewayException, S as checkCookie, T as givenCookieKey, U as GoneException, V as ForbiddenException, W as HttpException, X as ServiceUnavailableException, Y as PayloadTooLargeException, Z as TooManyRequestsException, at as isBodylessStatus, et as UnsupportedMediaTypeException, h as isEventStreamType, it as toIssueDetail, j as serializeResponseCookie, k as serializeClearCookie, nt as isHttpException, ot as isValidStatus, q as NotFoundException, rt as issue, st as statusText, tt as ValidationException, w as encodeCookieValue, x as DEFAULT_COOKIE_OPTIONS, z as BadRequestException } from "./node-io-CVnqpVNS.mjs";
1
+ import { n as RouteTable, t as nodeAdapter } from "./node-DnYv_AMI.mjs";
2
+ import { $ as TooManyRequestsException, A as parseSetCookie, B as BadGatewayException, C as DEFAULT_COOKIE_OPTIONS, D as givenCookieKey, E as encodeCookieValue, F as discardStream, G as GoneException, H as ConflictException, I as isByteStream, J as MethodNotAllowedException, K as HttpException, L as isStreamSource, M as serializeCookie, N as serializeResponseCookie, O as isCookieName, P as captureContext, Q as ServiceUnavailableException, R as toByteStream, T as decodeCookieValue, U as ForbiddenException, V as BadRequestException, W as GatewayTimeoutException, X as NotImplementedException, Y as NotFoundException, Z as PayloadTooLargeException, at as issue, ct as isValidStatus, et as UnauthorizedException, g as isEventStreamType, it as isHttpException, j as serializeClearCookie, k as parseCookieHeader, lt as statusText, nt as UnsupportedMediaTypeException, ot as toIssueDetail, q as InternalServerErrorException, rt as ValidationException, st as isBodylessStatus, tt as UnprocessableEntityException, w as checkCookie, z as trackStream } from "./node-io-BkdRSQeg.mjs";
3
3
  import { a as isMediaTypePattern, i as contentTypeFor, n as parseByteSize, o as matchesMediaType, r as OCTET_STREAM, s as mediaTypeEssence, t as formatByteSize } from "./size-D8rsQcV0.mjs";
4
- import { i as isThenable, n as errorMessage, r as isBun, t as emptyRecord } from "./utils-DCbu3a4w.mjs";
4
+ import { a as isThenable, i as isBun, n as errorMessage, r as fastRecord, t as emptyRecord } from "./utils-DIWdzVht.mjs";
5
5
  import { RoutePathError, compareRoutePaths, compareStrings, decodePathValue, joinPaths, matchRoutePath, normalizePath, parseRoutePath } from "./path.mjs";
6
6
  import { Readable } from "node:stream";
7
7
  import { Buffer as Buffer$1 } from "node:buffer";
@@ -483,9 +483,35 @@ function splitUrl(url) {
483
483
  }
484
484
  // src/body.ts
485
485
  const UTF8 = new TextDecoder("utf-8", { fatal: true });
486
+ /**
487
+ * Parsed `content-type` values: an application receives a handful of them, parsed twice per request
488
+ * with a body (request context, then {@link parseBody}). Bounded, since clients choose the values:
489
+ * cleared when full.
490
+ */
491
+ const MEDIA_TYPES = /* @__PURE__ */ new Map();
492
+ const MEDIA_TYPES_MAX = 64;
486
493
  /** Parses a `content-type` header value (`application/json; charset=utf-8`). */
487
494
  function parseMediaType(header) {
488
495
  if (header === void 0) return void 0;
496
+ if (header === "application/json") return {
497
+ type: "application/json",
498
+ charset: void 0
499
+ };
500
+ const cached = MEDIA_TYPES.get(header);
501
+ if (cached !== void 0) return {
502
+ type: cached.type,
503
+ charset: cached.charset
504
+ };
505
+ const media = parseUncached(header);
506
+ if (media === void 0) return void 0;
507
+ if (MEDIA_TYPES.size === MEDIA_TYPES_MAX) MEDIA_TYPES.clear();
508
+ MEDIA_TYPES.set(header, media);
509
+ return {
510
+ type: media.type,
511
+ charset: media.charset
512
+ };
513
+ }
514
+ function parseUncached(header) {
489
515
  const separator = header.indexOf(";");
490
516
  const type = (separator === -1 ? header : header.slice(0, separator)).trim().toLowerCase();
491
517
  if (type === "") return void 0;
@@ -537,12 +563,16 @@ function hasBody(headers) {
537
563
  */
538
564
  function parseBody(bytes, contentType, contentEncoding) {
539
565
  try {
540
- return Promise.resolve(parseBytes(bytes, contentType, contentEncoding));
566
+ return Promise.resolve(parseBodyBytes(bytes, contentType, contentEncoding));
541
567
  } catch (error) {
542
568
  return Promise.reject(error);
543
569
  }
544
570
  }
545
- function parseBytes(bytes, contentType, contentEncoding) {
571
+ /**
572
+ * {@link parseBody} without the promise: returns the parsed body or throws its `HttpException`
573
+ * (internal: the request context parses the buffered body with it, without an extra microtask).
574
+ */
575
+ function parseBodyBytes(bytes, contentType, contentEncoding) {
546
576
  if (bytes.byteLength === 0) return void 0;
547
577
  checkContentEncoding(contentEncoding);
548
578
  const media = parseMediaType(contentType);
@@ -601,7 +631,29 @@ function single(value, label) {
601
631
  if (Array.isArray(value)) throw new BadRequestException(`Invalid ${label}: expected a single value, received ${value.length}`);
602
632
  throw invalid$1(label, "a string", value);
603
633
  }
634
+ /** Longest run of decimal digits whose value is exact without parsing (`999999999999999` < 2^53). */
635
+ const MAX_FAST_DIGITS = 15;
636
+ /**
637
+ * The value of `text` when it is 1 to 15 ASCII decimal digits (the common `/users/42`), `-1`
638
+ * otherwise. The same number as `Number(text)` for such a string, without the regular expression,
639
+ * the trim and the parse of the general path.
640
+ */
641
+ function digitsValue(text) {
642
+ const length = text.length;
643
+ if (length === 0 || length > MAX_FAST_DIGITS) return -1;
644
+ let result = 0;
645
+ for (let index = 0; index < length; index++) {
646
+ const digit = text.charCodeAt(index) - 48;
647
+ if (digit < 0 || digit > 9) return -1;
648
+ result = result * 10 + digit;
649
+ }
650
+ return result;
651
+ }
604
652
  function toNumber(value, label) {
653
+ if (typeof value === "string") {
654
+ const digits = digitsValue(value);
655
+ if (digits !== -1) return digits;
656
+ }
605
657
  const raw = single(value, label);
606
658
  const text = raw.trim();
607
659
  if (NUMBER.test(text)) {
@@ -611,6 +663,10 @@ function toNumber(value, label) {
611
663
  throw invalid$1(label, "a number", raw);
612
664
  }
613
665
  function toInteger(value, label) {
666
+ if (typeof value === "string") {
667
+ const digits = digitsValue(value);
668
+ if (digits !== -1) return digits;
669
+ }
614
670
  const raw = single(value, label);
615
671
  const text = raw.trim();
616
672
  if (INTEGER.test(text)) {
@@ -620,6 +676,8 @@ function toInteger(value, label) {
620
676
  throw invalid$1(label, "an integer", raw);
621
677
  }
622
678
  function toBoolean(value, label) {
679
+ if (value === "true" || value === "1") return true;
680
+ if (value === "false" || value === "0") return false;
623
681
  const raw = single(value, label);
624
682
  switch (raw.trim().toLowerCase()) {
625
683
  case "true":
@@ -781,8 +839,27 @@ const ABORT_MESSAGES = {
781
839
  shutdown: "The server is shutting down",
782
840
  expired: "The event stream reached its maxDuration"
783
841
  };
842
+ /**
843
+ * The state of a request context that most requests never need (parsed query, `ctx.state`, body,
844
+ * request cookies, abort signal), created on first use: a context is created for every request.
845
+ */
846
+ var ContextState = class {
847
+ query = void 0;
848
+ state = void 0;
849
+ body = void 0;
850
+ files = void 0;
851
+ raw = void 0;
852
+ streamed = false;
853
+ /** Stops the body stream opened for the request, unless it was read to its end or cancelled. */
854
+ stopBody = void 0;
855
+ parsed = void 0;
856
+ cookies = void 0;
857
+ signed = void 0;
858
+ abortReason = void 0;
859
+ abortController = void 0;
860
+ };
784
861
  /** Implementation of {@link HttpContext} used by the pipeline (internal). */
785
- var RequestContext = class {
862
+ var RequestContext = class RequestContext {
786
863
  requestId;
787
864
  method;
788
865
  url;
@@ -798,60 +875,64 @@ var RequestContext = class {
798
875
  #source;
799
876
  #plan;
800
877
  #rawQuery;
801
- #query;
802
- #state;
803
- #responseHeaders;
804
- #body;
805
- #files;
806
- #raw;
807
- #streamed = false;
808
- /** Stops the body stream opened for the request, unless it was read to its end or cancelled. */
809
- #stopBody;
810
- #parsed;
811
878
  #cookieSettings;
812
- #cookies;
813
- #signed;
879
+ #responseHeaders = void 0;
814
880
  /** Cookies set on the response, by key (name, domain, path), with their `Set-Cookie` line. */
815
- #jar;
881
+ #jar = void 0;
816
882
  /** The response headers were handed to the adapter (cookies can no longer be set). */
817
883
  #committed = false;
818
884
  /** The request is over: later aborts are ignored. */
819
885
  #completed = false;
820
- #abortReason;
821
- #abortController;
822
- constructor(source, init) {
886
+ #more = void 0;
887
+ /** `path` and `query`: `source.url` split; `client`: see {@link RequestContextInit.client}. */
888
+ constructor(source, requestId, adapter, path, query, route, params, body, cookies, client) {
823
889
  this.#source = source;
824
- this.#plan = init.body;
825
- this.#cookieSettings = init.cookies ?? DEFAULT_COOKIE_SETTINGS;
826
- const { path, query } = init.url ?? splitUrl(source.url);
890
+ this.#plan = body;
891
+ this.#cookieSettings = cookies;
827
892
  this.#rawQuery = query;
828
- this.requestId = init.requestId;
893
+ this.requestId = requestId;
829
894
  this.method = source.method;
830
895
  this.url = source.url;
831
896
  this.path = path;
832
- this.params = init.params;
897
+ this.params = params;
833
898
  this.headers = source.headers;
834
- this.route = init.route;
899
+ this.route = route;
835
900
  this.request = source.raw;
836
901
  this.response = source.rawResponse;
837
- this.adapter = init.adapter;
838
- const connection = source.encrypted === true ? "https" : "http";
839
- this.ip = init.client === void 0 ? source.ip : init.client.ip;
840
- this.protocol = init.client === void 0 ? connection : init.client.protocol;
902
+ this.adapter = adapter;
903
+ if (client === void 0) {
904
+ this.ip = source.ip;
905
+ this.protocol = source.encrypted === true ? "https" : "http";
906
+ } else {
907
+ this.ip = client.ip;
908
+ this.protocol = client.protocol;
909
+ }
910
+ }
911
+ /** A context from named settings (defaults: `source.url` split, secure cookie defaults, the adapter's client). */
912
+ static of(source, init) {
913
+ const { path, query } = init.url ?? splitUrl(source.url);
914
+ return new RequestContext(source, init.requestId, init.adapter, path, query, init.route, init.params, init.body, init.cookies ?? DEFAULT_COOKIE_SETTINGS, init.client);
915
+ }
916
+ /** The state created on first use. */
917
+ get #extra() {
918
+ this.#more ??= new ContextState();
919
+ return this.#more;
841
920
  }
842
921
  get query() {
843
- this.#query ??= parseQuery(this.#rawQuery);
844
- return this.#query;
922
+ const state = this.#extra;
923
+ state.query ??= parseQuery(this.#rawQuery);
924
+ return state.query;
845
925
  }
846
926
  get state() {
847
- this.#state ??= /* @__PURE__ */ new Map();
848
- return this.#state;
927
+ const state = this.#extra;
928
+ state.state ??= /* @__PURE__ */ new Map();
929
+ return state.state;
849
930
  }
850
931
  get body() {
851
- return this.#body;
932
+ return this.#more?.body;
852
933
  }
853
934
  get files() {
854
- return this.#files ?? NO_FILES$1;
935
+ return this.#more?.files ?? NO_FILES$1;
855
936
  }
856
937
  /** Maximum body size of the route, in bytes. */
857
938
  get bodyLimit() {
@@ -879,16 +960,18 @@ var RequestContext = class {
879
960
  else this.#responseHeaders[key] = typeof existing === "string" ? [existing, value] : [...existing, value];
880
961
  }
881
962
  get cookies() {
882
- this.#cookies ??= parseCookieHeader(this.headers["cookie"]);
883
- return this.#cookies;
963
+ const state = this.#extra;
964
+ state.cookies ??= parseCookieHeader(this.headers["cookie"]);
965
+ return state.cookies;
884
966
  }
885
967
  signedCookie(name) {
886
968
  const signer = this.#cookieSettings.signer;
887
969
  if (signer === void 0) throw missingSecrets(`Cannot read the signed cookie ${JSON.stringify(String(name))}`);
888
- this.#signed ??= /* @__PURE__ */ new Map();
889
- if (this.#signed.has(name)) return this.#signed.get(name);
970
+ const state = this.#extra;
971
+ state.signed ??= /* @__PURE__ */ new Map();
972
+ if (state.signed.has(name)) return state.signed.get(name);
890
973
  const value = verifySigned(signer, name, this.cookies[name]);
891
- this.#signed.set(name, value);
974
+ state.signed.set(name, value);
892
975
  return value;
893
976
  }
894
977
  setCookie(name, value, options = {}) {
@@ -908,6 +991,10 @@ var RequestContext = class {
908
991
  get responseCookies() {
909
992
  return this.#jar === void 0 ? NO_COOKIES$1 : [...this.#jar.values()].map((entry) => entry.cookie);
910
993
  }
994
+ /** Whether {@link setCookie} / {@link clearCookie} were called (internal). */
995
+ get hasCookies() {
996
+ return this.#jar !== void 0;
997
+ }
911
998
  /** The `Set-Cookie` lines of {@link setCookie} / {@link clearCookie}, with their keys, in order (internal). */
912
999
  get cookieLines() {
913
1000
  return this.#jar === void 0 ? NO_LINES : [...this.#jar].map(([key, entry]) => ({
@@ -932,27 +1019,29 @@ var RequestContext = class {
932
1019
  });
933
1020
  }
934
1021
  get signal() {
935
- if (this.#abortController === void 0) {
1022
+ const state = this.#extra;
1023
+ if (state.abortController === void 0) {
936
1024
  const controller = new AbortController();
937
- this.#abortController = controller;
938
- if (this.#abortReason !== void 0) controller.abort(this.#abortReason);
1025
+ state.abortController = controller;
1026
+ if (state.abortReason !== void 0) controller.abort(state.abortReason);
939
1027
  else if (!this.#completed) this.#source.onAbort?.(() => this.abort("client"));
940
1028
  }
941
- return this.#abortController.signal;
1029
+ return state.abortController.signal;
942
1030
  }
943
1031
  /** Whether {@link signal} aborted (or will be created aborted). */
944
1032
  get aborted() {
945
- return this.#abortReason !== void 0;
1033
+ return this.#more?.abortReason !== void 0;
946
1034
  }
947
1035
  /**
948
1036
  * Aborts {@link signal} with a {@link RequestAbortedError} of `kind` (internal): at most once, and
949
1037
  * never once the request is over ({@link complete}).
950
1038
  */
951
1039
  abort(kind) {
952
- if (this.#abortReason !== void 0 || this.#completed) return;
1040
+ if (this.#more?.abortReason !== void 0 || this.#completed) return;
953
1041
  const reason = new RequestAbortedError(kind);
954
- this.#abortReason = reason;
955
- this.#abortController?.abort(reason);
1042
+ const state = this.#extra;
1043
+ state.abortReason = reason;
1044
+ state.abortController?.abort(reason);
956
1045
  }
957
1046
  /** The response headers are handed to the adapter: cookies can no longer be set (internal). */
958
1047
  commit() {
@@ -963,15 +1052,17 @@ var RequestContext = class {
963
1052
  this.#completed = true;
964
1053
  }
965
1054
  rawBody() {
966
- if (this.#raw === void 0) {
967
- if (this.#streamed) return Promise.reject(alreadyStreamed());
968
- this.#raw = this.#source.readBody(this.#plan.limit);
1055
+ const state = this.#extra;
1056
+ if (state.raw === void 0) {
1057
+ if (state.streamed) return Promise.reject(alreadyStreamed());
1058
+ state.raw = this.#source.readBody(this.#plan.limit);
969
1059
  }
970
- return this.#raw;
1060
+ return state.raw;
971
1061
  }
972
1062
  bodyStream() {
973
- if (this.#raw !== void 0 || this.#streamed) throw alreadyStreamed();
974
- this.#streamed = true;
1063
+ const state = this.#extra;
1064
+ if (state.raw !== void 0 || state.streamed) throw alreadyStreamed();
1065
+ state.streamed = true;
975
1066
  return this.#openBodyStream();
976
1067
  }
977
1068
  /**
@@ -980,18 +1071,21 @@ var RequestContext = class {
980
1071
  * adapter discard the rest of the body, so that the connection can serve the next request.
981
1072
  */
982
1073
  releaseBody() {
983
- const stop = this.#stopBody;
984
- this.#stopBody = void 0;
1074
+ const state = this.#more;
1075
+ if (state === void 0) return;
1076
+ const stop = state.stopBody;
1077
+ state.stopBody = void 0;
985
1078
  stop?.();
986
1079
  }
987
1080
  /** The body as a stream (see {@link releaseBody}). */
988
1081
  #openBodyStream() {
989
1082
  const reader = openBodyStream(this.#source, this.#plan.limit).getReader();
1083
+ const state = this.#extra;
990
1084
  let controller;
991
1085
  const settle = () => {
992
- this.#stopBody = void 0;
1086
+ state.stopBody = void 0;
993
1087
  };
994
- this.#stopBody = () => {
1088
+ state.stopBody = () => {
995
1089
  reader.cancel().catch(() => void 0);
996
1090
  try {
997
1091
  controller?.error(/* @__PURE__ */ new Error("The request is over: its body can no longer be read"));
@@ -1023,32 +1117,34 @@ var RequestContext = class {
1023
1117
  }, { highWaterMark: 0 });
1024
1118
  }
1025
1119
  parseBody() {
1026
- this.#parsed ??= this.#parse();
1027
- return this.#parsed;
1120
+ const state = this.#extra;
1121
+ state.parsed ??= this.#parse();
1122
+ return state.parsed;
1028
1123
  }
1029
1124
  async #parse() {
1030
1125
  const headers = this.headers;
1031
1126
  const contentType = headers["content-type"];
1032
1127
  const media = parseMediaType(contentType);
1128
+ const state = this.#extra;
1033
1129
  if (media?.type === "multipart/form-data") {
1034
1130
  checkContentEncoding(headers["content-encoding"]);
1035
1131
  const policy = this.#plan.multipart;
1036
1132
  let result;
1037
- if (this.#raw === void 0) {
1038
- if (this.#streamed) throw alreadyStreamed();
1039
- this.#streamed = true;
1133
+ if (state.raw === void 0) {
1134
+ if (state.streamed) throw alreadyStreamed();
1135
+ state.streamed = true;
1040
1136
  result = await readMultipart(this.#openBodyStream(), contentType, policy);
1041
- } else result = parseMultipart(await this.#raw, contentType, policy);
1042
- this.#files = result.files;
1043
- this.#body = result.fields;
1137
+ } else result = parseMultipart(await state.raw, contentType, policy);
1138
+ state.files = result.files;
1139
+ state.body = result.fields;
1044
1140
  return result.fields;
1045
1141
  }
1046
1142
  if (this.#plan.upload) {
1047
1143
  if (!(headers["content-length"] !== void 0 || headers["transfer-encoding"] !== void 0 ? hasBody(headers) : this.#source.hasBody?.() === true)) return void 0;
1048
1144
  throw new UnsupportedMediaTypeException(`Expected a multipart/form-data body${media === void 0 ? "" : ` (received ${JSON.stringify(media.type)})`}`);
1049
1145
  }
1050
- const body = await parseBody(await this.rawBody(), contentType, headers["content-encoding"]);
1051
- this.#body = body;
1146
+ const body = parseBodyBytes(await this.rawBody(), contentType, headers["content-encoding"]);
1147
+ state.body = body;
1052
1148
  return body;
1053
1149
  }
1054
1150
  };
@@ -1788,7 +1884,7 @@ function encodeExtValue(value) {
1788
1884
  */
1789
1885
  /** Length of a signature: base64url of 32 bytes, without padding. */
1790
1886
  const SIGNATURE_LENGTH = 43;
1791
- const ENCODER$2 = new TextEncoder();
1887
+ const ENCODER$3 = new TextEncoder();
1792
1888
  /**
1793
1889
  * Signs and verifies cookie values. The wire form of a signed cookie is
1794
1890
  * `<encoded value>.<signature>` with `signature = base64url(HMAC-SHA256(secret, "<name>=<encoded value>"))`:
@@ -1835,7 +1931,7 @@ function isSignature(text) {
1835
1931
  return true;
1836
1932
  }
1837
1933
  function toBytes(secret) {
1838
- return typeof secret === "string" ? ENCODER$2.encode(secret) : secret;
1934
+ return typeof secret === "string" ? ENCODER$3.encode(secret) : secret;
1839
1935
  }
1840
1936
  /**
1841
1937
  * Normalises the option `cookies.secrets` to a list, or explains what is wrong with it (a secret
@@ -2851,8 +2947,8 @@ function describe$1(value) {
2851
2947
  function errorText(error) {
2852
2948
  return error instanceof Error ? error.message : String(error);
2853
2949
  }
2854
- const ENCODER$1 = new TextEncoder();
2855
- const HEARTBEAT = ENCODER$1.encode(":\n\n");
2950
+ const ENCODER$2 = new TextEncoder();
2951
+ const HEARTBEAT = ENCODER$2.encode(":\n\n");
2856
2952
  /**
2857
2953
  * One event stream: the byte stream sent to the client and the controls of the pipeline
2858
2954
  * ({@link close} on shutdown or `maxDuration`). The source is read only when the client pulls
@@ -2902,7 +2998,7 @@ var SseSession = class {
2902
2998
  start: (controller) => {
2903
2999
  this.#controller = controller;
2904
3000
  const retry = settings.retry;
2905
- controller.enqueue(retry === void 0 ? HEARTBEAT : ENCODER$1.encode(`retry: ${retry}\n\n`));
3001
+ controller.enqueue(retry === void 0 ? HEARTBEAT : ENCODER$2.encode(`retry: ${retry}\n\n`));
2906
3002
  if (settings.maxDuration !== void 0) this.#maxTimer = unref(setTimeout(() => this.close("expired"), timerDelay(settings.maxDuration)));
2907
3003
  },
2908
3004
  pull: (controller) => this.#pull(controller),
@@ -2965,7 +3061,7 @@ var SseSession = class {
2965
3061
  await this.#finish(true);
2966
3062
  return;
2967
3063
  }
2968
- controller.enqueue(ENCODER$1.encode(encoded));
3064
+ controller.enqueue(ENCODER$2.encode(encoded));
2969
3065
  this.#atBoundary = true;
2970
3066
  this.#lineHasContent = false;
2971
3067
  this.#afterCr = false;
@@ -3093,7 +3189,7 @@ var SseSession = class {
3093
3189
  #finalRetry() {
3094
3190
  const base = this.#settings.retry ?? 3e3;
3095
3191
  const random = this.#settings.random ?? Math.random;
3096
- return ENCODER$1.encode(`retry: ${Math.round(base + random() * base)}\n\n`);
3192
+ return ENCODER$2.encode(`retry: ${Math.round(base + random() * base)}\n\n`);
3097
3193
  }
3098
3194
  /**
3099
3195
  * Stops the source (`return()` / `cancel()`) and waits for it at most `stopTimeoutMs`: an async
@@ -3344,15 +3440,19 @@ function withCookie(cookies, cookie) {
3344
3440
  }
3345
3441
  /** Whether `value` is an {@link HttpResponse} (also across duplicated package copies). */
3346
3442
  function isHttpResponse(value) {
3347
- return value instanceof HttpResponse || value !== null && typeof value === "object" && value.constructor?.name === "HttpResponse" && "body" in value && "headers" in value;
3443
+ if (value instanceof HttpResponse) return true;
3444
+ if (value === null || typeof value !== "object") return false;
3445
+ const type = value.constructor;
3446
+ if (type === Object || type === Array) return false;
3447
+ return type?.name === "HttpResponse" && "body" in value && "headers" in value;
3348
3448
  }
3349
3449
  // src/serialize.ts
3350
- const ENCODER = new TextEncoder();
3450
+ const ENCODER$1 = new TextEncoder();
3351
3451
  /**
3352
3452
  * UTF-8 encoding of a text body: a pooled `Buffer` (a `Uint8Array`) is several times cheaper than
3353
3453
  * `TextEncoder` on Node.js, `TextEncoder` is the fastest on Bun.
3354
3454
  */
3355
- const utf8 = isBun() ? (text) => ENCODER.encode(text) : (text) => Buffer$1.from(text, "utf8");
3455
+ const utf8$1 = isBun() ? (text) => ENCODER$1.encode(text) : (text) => Buffer$1.from(text, "utf8");
3356
3456
  /** Content types set by the serialiser. */
3357
3457
  const ContentType = Object.freeze({
3358
3458
  json: "application/json; charset=utf-8",
@@ -3391,8 +3491,14 @@ function serializeResult(result, options) {
3391
3491
  cookies = cookiesOf(result);
3392
3492
  }
3393
3493
  const finalStatus = options.status ?? status ?? defaultStatus(options.routeMethod, payload);
3394
- const headers = emptyRecord();
3395
- const body = encode(payload, headers);
3494
+ const headers = fastRecord();
3495
+ const encoded = encode(payload, headers);
3496
+ let body;
3497
+ let text;
3498
+ if (typeof encoded === "string") {
3499
+ text = encoded;
3500
+ body = encodeText(encoded, headers, sendsBody(finalStatus, options.method));
3501
+ } else body = encoded;
3396
3502
  let own = true;
3397
3503
  if (options.headers !== void 0) {
3398
3504
  assignHeaders(headers, options.headers);
@@ -3406,7 +3512,7 @@ function serializeResult(result, options) {
3406
3512
  assignHeaders(headers, extra);
3407
3513
  own = false;
3408
3514
  }
3409
- return withCookies(finish(finalStatus, headers, body, options.method, own), cookies);
3515
+ return withCookies(finish(finalStatus, headers, body, options.method, text, own), cookies);
3410
3516
  }
3411
3517
  /**
3412
3518
  * Serialises an event stream (`@Sse` result, `HttpResponse.sse()`): status 200 unless `@HttpCode`
@@ -3417,7 +3523,7 @@ function serializeResult(result, options) {
3417
3523
  */
3418
3524
  function serializeSseReply(session, response, options) {
3419
3525
  const status = options.status ?? response?.status ?? 200;
3420
- const headers = emptyRecord();
3526
+ const headers = fastRecord();
3421
3527
  headers["cache-control"] = "no-cache, no-transform";
3422
3528
  headers["x-accel-buffering"] = "no";
3423
3529
  if (options.headers !== void 0) assignHeaders(headers, options.headers);
@@ -3450,7 +3556,7 @@ function withCookies(reply, cookies) {
3450
3556
  */
3451
3557
  function serializeFileReply(file, response, options) {
3452
3558
  const status = file.status === 200 ? options.status ?? response.status ?? 200 : file.status;
3453
- const headers = emptyRecord();
3559
+ const headers = fastRecord();
3454
3560
  assignHeaders(headers, file.headers);
3455
3561
  if (options.headers !== void 0) assignHeaders(headers, options.headers);
3456
3562
  if (options.context !== void 0) assignHeaders(headers, options.context);
@@ -3464,8 +3570,10 @@ function defaultStatus(routeMethod, payload) {
3464
3570
  }
3465
3571
  /** Serialises an error body as JSON. */
3466
3572
  function serializeError(status, body, method) {
3467
- const headers = emptyRecord();
3468
- return finish(status, headers, encode(body, headers), method);
3573
+ const headers = fastRecord();
3574
+ const encoded = encode(body, headers);
3575
+ if (typeof encoded !== "string") return finish(status, headers, encoded, method);
3576
+ return finish(status, headers, encodeText(encoded, headers, sendsBody(status, method)), method, encoded);
3469
3577
  }
3470
3578
  /** Copies headers with lower-case names (later values win). */
3471
3579
  function assignHeaders(target, source) {
@@ -3483,10 +3591,10 @@ function addMissingHeaders(target, source) {
3483
3591
  }
3484
3592
  }
3485
3593
  /**
3486
- * The reply of a body: a string (see {@link encode}) is sent as its UTF-8 bytes, with its text.
3487
- * `own`: only {@link encode} set `headers`, which are then valid for a text body.
3594
+ * The reply of a body: `text` is the string `body` encodes (see {@link encodeText}). `own`: only
3595
+ * {@link encode} set `headers`, which are then valid for a text body.
3488
3596
  */
3489
- function finish(status, headers, body, method, own = false) {
3597
+ function finish(status, headers, body, method, text, own = false) {
3490
3598
  if (isBodylessStatus(status)) {
3491
3599
  discard(body);
3492
3600
  delete headers["content-type"];
@@ -3505,7 +3613,7 @@ function finish(status, headers, body, method, own = false) {
3505
3613
  body: null
3506
3614
  };
3507
3615
  }
3508
- if (typeof body !== "string") return {
3616
+ if (text === void 0) return {
3509
3617
  status,
3510
3618
  headers,
3511
3619
  body
@@ -3513,22 +3621,41 @@ function finish(status, headers, body, method, own = false) {
3513
3621
  return own ? {
3514
3622
  status,
3515
3623
  headers,
3516
- body: utf8(body),
3517
- text: body,
3624
+ body,
3625
+ text,
3518
3626
  ownHeaders: true
3519
3627
  } : {
3520
3628
  status,
3521
3629
  headers,
3522
- body: utf8(body),
3523
- text: body
3630
+ body,
3631
+ text
3524
3632
  };
3525
3633
  }
3526
3634
  function discard(body) {
3527
3635
  if (body instanceof ReadableStream) discardStream(body);
3528
3636
  }
3637
+ /** Whether a reply with this status, to this method, carries its body (see {@link finish}). */
3638
+ function sendsBody(status, method) {
3639
+ return method !== "HEAD" && !isBodylessStatus(status);
3640
+ }
3641
+ /**
3642
+ * Sets the `content-length` of a text body (right after its `content-type`, before the route
3643
+ * headers) and returns its UTF-8 bytes: their length is the header, a lone surrogate counting as
3644
+ * U+FFFD. `null` when the reply sends no body (`HEAD`, bodyless status): nothing is encoded then,
3645
+ * `Buffer.byteLength` counts the same bytes.
3646
+ */
3647
+ function encodeText(text, headers, sent) {
3648
+ if (!sent) {
3649
+ headers["content-length"] = String(Buffer$1.byteLength(text, "utf8"));
3650
+ return null;
3651
+ }
3652
+ const bytes = utf8$1(text);
3653
+ headers["content-length"] = String(bytes.byteLength);
3654
+ return bytes;
3655
+ }
3529
3656
  /**
3530
- * The body of a payload, its `content-type` and, for bytes and text, its `content-length` set in
3531
- * `headers`. Text (a string, JSON) is returned as a string, encoded as UTF-8 by {@link finish}.
3657
+ * The body of a payload, its `content-type` and, for bytes, its `content-length` set in `headers`.
3658
+ * Text (a string, JSON) is returned as a string: {@link encodeText} sets its length and encodes it.
3532
3659
  */
3533
3660
  function encode(payload, headers) {
3534
3661
  if (payload === void 0) return null;
@@ -3562,14 +3689,13 @@ function bytes(data, headers, type) {
3562
3689
  }
3563
3690
  function text$1(data, headers, type) {
3564
3691
  headers["content-type"] = type;
3565
- headers["content-length"] = String(Buffer$1.byteLength(data, "utf8"));
3566
3692
  return data;
3567
3693
  }
3568
3694
  function isNodeReadable(value) {
3569
3695
  return value instanceof Readable || value !== null && typeof value === "object" && typeof value.pipe === "function" && typeof value.on === "function" && typeof value.read === "function";
3570
3696
  }
3571
3697
  function fromWebResponse(response, method) {
3572
- const headers = emptyRecord();
3698
+ const headers = fastRecord();
3573
3699
  for (const [name, value] of response.headers) if (name !== "set-cookie") headers[name] = value;
3574
3700
  const cookies = response.headers.getSetCookie();
3575
3701
  if (cookies.length > 0) headers["set-cookie"] = cookies;
@@ -3596,11 +3722,64 @@ const DEFAULT_SSE_SETTINGS = Object.freeze({
3596
3722
  const RAW = Symbol("raw response");
3597
3723
  const REQUEST_ID = /^[\w\-.:@/+=]{1,128}$/;
3598
3724
  const MAX_PATH_IN_MESSAGE = 200;
3599
- /** The default request id generator: a random UUID. */
3725
+ /** The default request id generator: a random UUID (version 4, like `crypto.randomUUID()`). */
3600
3726
  function randomRequestId() {
3601
- return crypto.randomUUID();
3727
+ return uuid();
3728
+ }
3729
+ const uuidPool = /* @__PURE__ */ new Uint8Array(2048);
3730
+ let uuidOffset = uuidPool.length;
3731
+ /** The text of the last UUID, its dashes in place. */
3732
+ const uuidText = Buffer$1.alloc(36, 45);
3733
+ /** The two lower-case hexadecimal digits of each byte, as character codes. */
3734
+ const HEX_CODES = /* @__PURE__ */ new Uint8Array(512);
3735
+ for (let byte = 0; byte < 256; byte++) {
3736
+ const digits = byte.toString(16).padStart(2, "0");
3737
+ HEX_CODES[byte * 2] = digits.charCodeAt(0);
3738
+ HEX_CODES[byte * 2 + 1] = digits.charCodeAt(1);
3739
+ }
3740
+ function putHex(position, byte) {
3741
+ uuidText[position] = HEX_CODES[byte * 2];
3742
+ uuidText[position + 1] = HEX_CODES[byte * 2 + 1];
3743
+ }
3744
+ /**
3745
+ * A random version 4 UUID written from a pool of random bytes (`crypto.getRandomValues`), as Node.js
3746
+ * does, but read as one flat string: `crypto.randomUUID()` returns a concatenation of 20 pieces that
3747
+ * is flattened again when the header is written, which makes it about twice as slow.
3748
+ */
3749
+ function pooledUuid() {
3750
+ if (uuidOffset === uuidPool.length) {
3751
+ crypto.getRandomValues(uuidPool);
3752
+ uuidOffset = 0;
3753
+ }
3754
+ const pool = uuidPool;
3755
+ const at = uuidOffset;
3756
+ uuidOffset = at + 16;
3757
+ putHex(0, pool[at]);
3758
+ putHex(2, pool[at + 1]);
3759
+ putHex(4, pool[at + 2]);
3760
+ putHex(6, pool[at + 3]);
3761
+ putHex(9, pool[at + 4]);
3762
+ putHex(11, pool[at + 5]);
3763
+ putHex(14, pool[at + 6] & 15 | 64);
3764
+ putHex(16, pool[at + 7]);
3765
+ putHex(19, pool[at + 8] & 63 | 128);
3766
+ putHex(21, pool[at + 9]);
3767
+ putHex(24, pool[at + 10]);
3768
+ putHex(26, pool[at + 11]);
3769
+ putHex(28, pool[at + 12]);
3770
+ putHex(30, pool[at + 13]);
3771
+ putHex(32, pool[at + 14]);
3772
+ putHex(34, pool[at + 15]);
3773
+ return readUuidText();
3602
3774
  }
3603
3775
  /**
3776
+ * The text of {@link uuidText}: Node.js `Buffer#latin1Slice` (what `toString('latin1')` calls after
3777
+ * checking its arguments) when present.
3778
+ */
3779
+ const readUuidText = typeof uuidText.latin1Slice === "function" ? () => uuidText.latin1Slice(0, 36) : () => uuidText.toString("latin1", 0, 36);
3780
+ /** UUID generator: Bun's native `crypto.randomUUID()` is the fastest there. */
3781
+ const uuid = isBun() ? () => crypto.randomUUID() : pooledUuid;
3782
+ /**
3604
3783
  * The request pipeline (architecture §9.1):
3605
3784
  * `runInScope({ HttpContext, RequestId }) → hooks.run('http:request') → guards → body → interceptors
3606
3785
  * → invoke → serialise`, errors being mapped to responses inside `hooks.run`.
@@ -3615,6 +3794,22 @@ var Pipeline = class {
3615
3794
  #securityHeaders;
3616
3795
  /** Every request id can be sent: an incoming one matched `REQUEST_ID`, the generated ones are UUIDs. */
3617
3796
  #validIds;
3797
+ /**
3798
+ * The headers of a JSON reply of the fast lane, in their final order (content type and length,
3799
+ * then the framework headers, see {@link #frameworkHeaders}): copied, then completed with the
3800
+ * length and the request id.
3801
+ */
3802
+ #jsonHeaders;
3803
+ /** The request id header of {@link #jsonHeaders}, `undefined` when the reply has none. */
3804
+ #jsonIdHeader;
3805
+ /** The headers of a reply without body of the fast lane (the framework headers, see {@link #jsonHeaders}). */
3806
+ #emptyHeaders;
3807
+ /** The request id header of {@link #emptyHeaders}, `undefined` when the reply has none. */
3808
+ #emptyIdHeader;
3809
+ /** Whether {@link #jsonHeaders} and {@link #emptyHeaders} hold every framework header (see {@link #fastRoute}). */
3810
+ #fastHeaders;
3811
+ /** The `cookies` option (secure defaults, no signing, when not set). */
3812
+ #cookies;
3618
3813
  #inflight = 0;
3619
3814
  #idle = [];
3620
3815
  /** Open event streams. */
@@ -3628,7 +3823,22 @@ var Pipeline = class {
3628
3823
  this.#options = options;
3629
3824
  this.#table = table;
3630
3825
  this.#validIds = options.generateRequestId === randomRequestId;
3826
+ this.#cookies = options.cookies ?? DEFAULT_COOKIE_SETTINGS;
3631
3827
  this.#securityHeaders = Object.entries(options.securityHeaders ?? {}).map(([name, value]) => [name.toLowerCase(), value]);
3828
+ const placeholder = "-";
3829
+ const idHeader = options.requestIdHeader;
3830
+ const json = {
3831
+ "content-type": ContentType.json,
3832
+ "content-length": "0"
3833
+ };
3834
+ this.#frameworkHeaders(json, placeholder, void 0, false);
3835
+ this.#jsonHeaders = json;
3836
+ this.#jsonIdHeader = idHeader !== void 0 && json[idHeader] === placeholder ? idHeader : void 0;
3837
+ const empty = {};
3838
+ this.#frameworkHeaders(empty, placeholder, void 0, false);
3839
+ this.#emptyHeaders = empty;
3840
+ this.#emptyIdHeader = idHeader !== void 0 && empty[idHeader] === placeholder ? idHeader : void 0;
3841
+ this.#fastHeaders = (idHeader === void 0 || !(idHeader in Object.prototype)) && this.#securityHeaders.every(([name]) => !(name in Object.prototype));
3632
3842
  }
3633
3843
  /** Number of requests being processed. */
3634
3844
  get inflight() {
@@ -3651,6 +3861,207 @@ var Pipeline = class {
3651
3861
  return new Promise((resolve) => this.#idle.push(resolve));
3652
3862
  }
3653
3863
  /**
3864
+ * The adapter handler of a route: {@link handle}, or a fast lane for the routes that need no
3865
+ * guard, interceptor, event stream, raw response nor `@Header` when CORS is off (see
3866
+ * {@link #fast}).
3867
+ */
3868
+ handler(plan) {
3869
+ const route = this.#fastRoute(plan);
3870
+ if (route === void 0) return (request) => this.handle(plan, request);
3871
+ return (request) => this.#fast(route, request);
3872
+ }
3873
+ /** The fast lane of a route, `undefined` when the route needs the general pipeline. */
3874
+ #fastRoute(plan) {
3875
+ const definition = plan.definition;
3876
+ if (!this.#fastHeaders || this.#options.cors !== void 0 || plan.redirect === true || plan.guards.length > 0 || plan.interceptors.length > 0 || definition.sse !== void 0 || definition.rawResponse === true || definition.headers !== void 0 || definition.method === "ALL") return;
3877
+ const post = definition.method === "POST";
3878
+ const json = definition.status ?? (post ? 201 : 200);
3879
+ return {
3880
+ plan,
3881
+ target: {
3882
+ kind: "route",
3883
+ plan
3884
+ },
3885
+ method: definition.method,
3886
+ jsonStatus: definition.method === "HEAD" || isBodylessStatus(json) ? void 0 : json,
3887
+ emptyStatus: definition.status ?? (post ? 201 : 204)
3888
+ };
3889
+ }
3890
+ /**
3891
+ * The fast lane: what {@link handle} does for a route of {@link #fastRoute}, decided once instead
3892
+ * of per request, without promises while the route stays synchronous. A request takes it when no
3893
+ * `http:request` wrapper nor listener is registered, the server is not draining and its method
3894
+ * is the route's (not a `HEAD` served by a `GET` route); a plain object or array returned by the
3895
+ * handler is serialised as JSON, and `undefined` answered without body, with the headers in their
3896
+ * final order (a template precomputed at boot).
3897
+ * A thenable result is awaited in the lane (see {@link #fastAsync}). Anything else — a malformed
3898
+ * path (before the request starts), a thrown error or a rejection, an `HttpResponse`, a `Response`
3899
+ * or any other result, headers or cookies set through the context — continues in the general
3900
+ * pipeline, in the same request scope, with the same outcome.
3901
+ */
3902
+ #fast(route, request) {
3903
+ const plan = route.plan;
3904
+ const hooks = this.#hooks;
3905
+ if (this.draining || request.method !== route.method || hooks.hasWrappers("http:request") || hooks.hasListeners("http:request")) return this.handle(plan, request);
3906
+ const url = request.url;
3907
+ const mark = url.indexOf("?");
3908
+ const path = mark === -1 ? url : url.slice(0, mark);
3909
+ const params = routeParams(plan.path, path);
3910
+ if (params === void 0) return this.handle(plan, request);
3911
+ this.#enter();
3912
+ let ctx;
3913
+ try {
3914
+ const query = mark === -1 ? "" : url.slice(mark + 1);
3915
+ ctx = this.#context(request, this.#requestId(request), path, query, plan.info, params, plan.body);
3916
+ } catch (error) {
3917
+ this.#leave();
3918
+ return Promise.reject(error);
3919
+ }
3920
+ const scope = this.#container.openScope([[HttpTokens.Context, ctx], [HttpTokens.RequestId, ctx.requestId]]);
3921
+ const done = scope.run(this.#fastRun, route, request, ctx);
3922
+ if (done instanceof Exchange) {
3923
+ done.done.then(() => this.#end(done, scope, void 0), (error) => this.#end(done, scope, error));
3924
+ if (!hooks.hasListeners("http:request")) return done.replied;
3925
+ done.tracked = true;
3926
+ return this.#emitted(done);
3927
+ }
3928
+ const closing = scope.close();
3929
+ if (closing === void 0) {
3930
+ ctx.complete();
3931
+ this.#leave();
3932
+ } else {
3933
+ const x = new Exchange(request, ctx, ctx.requestId, route.target);
3934
+ x.answer(done);
3935
+ closing.then(() => this.#over(x), (error) => this.#disposalFailed(x, error));
3936
+ }
3937
+ if (!hooks.hasListeners("http:request")) return Promise.resolve(done);
3938
+ const event = requestEvent(request, ctx, performance.now());
3939
+ event.status = done.status;
3940
+ return Promise.resolve(done).then((reply) => {
3941
+ hooks.emit("http:request", event);
3942
+ return reply;
3943
+ });
3944
+ }
3945
+ /**
3946
+ * The fast lane in the request scope: the reply when the handler answered synchronously with a
3947
+ * plain JSON value or `undefined`, otherwise the exchange finishing the request (see {@link #fast}).
3948
+ */
3949
+ #fastRun = (route, request, ctx) => {
3950
+ const plan = route.plan;
3951
+ if (plan.parseBody) return this.#fastLater(route, request, ctx, NO_RESULT);
3952
+ let result;
3953
+ let reply;
3954
+ try {
3955
+ result = plan.definition.invoke(this.#resolve(plan.controller), ctx);
3956
+ if (isThenable(result)) return this.#fastLater(route, request, ctx, result);
3957
+ reply = this.#fastReply(route, ctx, result);
3958
+ } catch (error) {
3959
+ const x = new Exchange(request, ctx, ctx.requestId, route.target);
3960
+ x.done = this.#respond(x, () => this.#failed(error, ctx, x.event));
3961
+ return x;
3962
+ }
3963
+ if (reply !== void 0) {
3964
+ ctx.commit();
3965
+ ctx.releaseBody();
3966
+ return reply;
3967
+ }
3968
+ const x = new Exchange(request, ctx, ctx.requestId, route.target);
3969
+ x.done = this.#respond(x, () => this.#settle(ctx, plan, x.event, result));
3970
+ return x;
3971
+ };
3972
+ /** The fast lane of a route with a body to read or a handler that returned a thenable. */
3973
+ #fastLater(route, request, ctx, result) {
3974
+ const x = new Exchange(request, ctx, ctx.requestId, route.target);
3975
+ x.done = this.#fastAsync(x, route, result);
3976
+ return x;
3977
+ }
3978
+ /**
3979
+ * The asynchronous part of the fast lane, in the request scope: the body read (`result` is
3980
+ * {@link NO_RESULT}) and the handler run, or the thenable it returned awaited. Never rejects.
3981
+ */
3982
+ async #fastAsync(x, route, pending) {
3983
+ const ctx = x.ctx;
3984
+ const plan = route.plan;
3985
+ let result = pending;
3986
+ let reply;
3987
+ try {
3988
+ if (result === NO_RESULT) {
3989
+ const controller = this.#resolve(plan.controller);
3990
+ await ctx.parseBody();
3991
+ result = plan.definition.invoke(controller, ctx);
3992
+ }
3993
+ if (isThenable(result)) result = await result;
3994
+ reply = this.#fastReply(route, ctx, result);
3995
+ } catch (error) {
3996
+ await this.#respond(x, () => this.#failed(error, ctx, x.event));
3997
+ return;
3998
+ }
3999
+ if (reply === void 0) {
4000
+ const value = result;
4001
+ await this.#respond(x, () => this.#settle(ctx, plan, x.event, value));
4002
+ return;
4003
+ }
4004
+ ctx.commit();
4005
+ ctx.releaseBody();
4006
+ if (x.tracked) x.event.status = reply.status;
4007
+ x.answer(reply);
4008
+ }
4009
+ /**
4010
+ * The reply of a plain JSON value (see {@link isPlainJson}) or of `undefined`: what
4011
+ * `serializeResult` and {@link #complete} produce for it, the headers in their final order.
4012
+ * `undefined` when the result or the context needs the general pipeline. Throws like
4013
+ * `JSON.stringify`.
4014
+ */
4015
+ #fastReply(route, ctx, result) {
4016
+ const status = result === void 0 ? route.emptyStatus : route.jsonStatus;
4017
+ if (status === void 0 || ctx.hasResponseHeaders || ctx.hasCookies || this.draining) return void 0;
4018
+ const requestId = ctx.requestId;
4019
+ if (!this.#validIds && !isHeaderValue(requestId)) return void 0;
4020
+ if (result === void 0) {
4021
+ const headers = { ...this.#emptyHeaders };
4022
+ const idHeader = this.#emptyIdHeader;
4023
+ if (idHeader !== void 0) headers[idHeader] = requestId;
4024
+ return {
4025
+ status,
4026
+ headers,
4027
+ body: null
4028
+ };
4029
+ }
4030
+ if (!isPlainJson(result)) return void 0;
4031
+ const json = JSON.stringify(result);
4032
+ if (json === void 0) throw new TypeError(`Cannot serialise a ${typeof result} as a response body`);
4033
+ const headers = { ...this.#jsonHeaders };
4034
+ const body = utf8(json);
4035
+ headers["content-length"] = String(body.byteLength);
4036
+ const idHeader = this.#jsonIdHeader;
4037
+ if (idHeader !== void 0) headers[idHeader] = requestId;
4038
+ return {
4039
+ status,
4040
+ headers,
4041
+ body,
4042
+ text: json
4043
+ };
4044
+ }
4045
+ /** Ends a fast-lane request once its asynchronous part settled: its scope is closed, then it is over. */
4046
+ #end(x, scope, error) {
4047
+ const closing = scope.close();
4048
+ if (error !== void 0) {
4049
+ const report = () => this.#disposalFailed(x, error);
4050
+ if (closing === void 0) report();
4051
+ else closing.then(report, report);
4052
+ return;
4053
+ }
4054
+ if (closing === void 0) this.#over(x);
4055
+ else closing.then(() => this.#over(x), (failure) => this.#disposalFailed(x, failure));
4056
+ }
4057
+ #disposalFailed(x, error) {
4058
+ this.#over(x);
4059
+ this.#logger.error("Failed to dispose request-scoped providers", {
4060
+ err: error,
4061
+ requestId: x.requestId
4062
+ });
4063
+ }
4064
+ /**
3654
4065
  * Handles a request routed to `plan` by the adapter. The request stays in flight (and its scope
3655
4066
  * open) until a streamed or file response body has been fully read or cancelled by the adapter.
3656
4067
  */
@@ -3746,146 +4157,140 @@ var Pipeline = class {
3746
4157
  }
3747
4158
  #serve(request, url, route, params, target, startTime, body) {
3748
4159
  this.#enter();
3749
- let requestId;
3750
- let ctx;
3751
- let event;
4160
+ let x;
3752
4161
  try {
3753
- requestId = this.#requestId(request);
3754
- const proxy = this.#options.trustProxy;
3755
- ctx = new RequestContext(request, {
3756
- requestId,
3757
- adapter: this.#options.adapter,
3758
- url,
3759
- route,
3760
- params,
3761
- body,
3762
- cookies: this.#options.cookies ?? DEFAULT_COOKIE_SETTINGS,
3763
- client: proxy === void 0 ? void 0 : proxy.resolve(request.remoteAddress ?? request.ip, request.headers, request.encrypted === true)
3764
- });
4162
+ const requestId = this.#requestId(request);
4163
+ const ctx = this.#context(request, requestId, url.path, url.query, route, params, body);
3765
4164
  if (this.draining && target.kind === "route" && target.plan.definition.sse !== void 0) ctx.abort("shutdown");
3766
- event = {
3767
- method: request.method,
3768
- path: ctx.path,
3769
- route: route?.path,
3770
- requestId,
3771
- headers: request.headers,
3772
- context: ctx,
3773
- startTime,
3774
- responseHeaders: {}
3775
- };
4165
+ x = new Exchange(request, ctx, requestId, target, startTime);
3776
4166
  } catch (error) {
3777
4167
  this.#leave();
3778
4168
  return Promise.reject(error);
3779
4169
  }
3780
- let outcome;
3781
- let cors;
3782
- const preflight = target.kind === "preflight";
3783
- let resolve = () => void 0;
3784
- let reject = () => void 0;
3785
- const replied = new Promise((onReply, onError) => {
3786
- resolve = onReply;
3787
- reject = onError;
4170
+ this.#container.runInScope(() => this.#respond(x, void 0), [[HttpTokens.Context, x.ctx], [HttpTokens.RequestId, x.requestId]]).then(() => this.#over(x), (error) => {
4171
+ this.#over(x);
4172
+ this.#logger.error("Failed to dispose request-scoped providers", {
4173
+ err: error,
4174
+ requestId: x.requestId
4175
+ });
3788
4176
  });
3789
- let answered = false;
3790
- const answer = (reply) => {
3791
- answered = true;
3792
- resolve(reply);
3793
- };
3794
- /** The request is over (response body sent or abandoned, scope closed). */
3795
- const over = () => {
3796
- ctx.complete();
3797
- try {
3798
- if (!answered) {
3799
- const failure = /* @__PURE__ */ new Error("Request not handled");
3800
- const reply = serializeError(500, this.#internalBody(failure), ctx.method);
3801
- const completed = this.#complete(reply, ctx, event, requestId, cors, preflight, true);
3802
- event.status = 500;
3803
- answer(completed);
3804
- }
3805
- } catch (error) {
3806
- reject(error);
3807
- } finally {
3808
- this.#leave();
3809
- }
3810
- };
3811
- this.#container.runInScope(async () => {
3812
- let hookError;
3813
- let failed = false;
3814
- let run;
3815
- if (this.#options.cors !== void 0) cors = await this.#corsDecision(request, requestId);
3816
- let recheck = this.#hooks.hasWrappers("http:request");
3817
- try {
3818
- if (recheck) await this.#hooks.run("http:request", event, async () => {
3819
- outcome = this.#checked(await this.#process(ctx, target, event, cors), ctx, event);
4177
+ return this.#hooks.hasListeners("http:request") ? this.#emitted(x) : x.replied;
4178
+ }
4179
+ /** The reply of a request once the `http:request` listeners saw its event. */
4180
+ #emitted(x) {
4181
+ return x.replied.then((reply) => {
4182
+ this.#hooks.emit("http:request", x.event);
4183
+ return reply;
4184
+ });
4185
+ }
4186
+ /** The request context of a request (internal). */
4187
+ #context(request, requestId, path, query, route, params, body) {
4188
+ const proxy = this.#options.trustProxy;
4189
+ return new RequestContext(request, requestId, this.#options.adapter, path, query, route, params, body, this.#cookies, proxy === void 0 ? void 0 : proxy.resolve(request.remoteAddress ?? request.ip, request.headers, request.encrypted === true));
4190
+ }
4191
+ /**
4192
+ * Answers a request in its scope: its outcome (`process`, or the target of the exchange after the
4193
+ * CORS decision and through the `http:request` wrappers), checked, completed and handed to the
4194
+ * adapter; a streamed body is then tracked until it was sent or abandoned. Never rejects.
4195
+ * `process` is given by the fast lane, which decided at the start of the request that no wrapper
4196
+ * applies and that CORS is off.
4197
+ */
4198
+ async #respond(x, process) {
4199
+ const ctx = x.ctx;
4200
+ const requestId = x.requestId;
4201
+ const event = x.event;
4202
+ let outcome;
4203
+ let hookError;
4204
+ let failed = false;
4205
+ let run;
4206
+ let recheck = false;
4207
+ let work = process;
4208
+ if (work === void 0) {
4209
+ if (this.#options.cors !== void 0) x.cors = await this.#corsDecision(x.request, requestId);
4210
+ recheck = this.#hooks.hasWrappers("http:request");
4211
+ const target = x.target;
4212
+ work = () => this.#process(ctx, target, event, x.cors);
4213
+ }
4214
+ try {
4215
+ if (recheck) {
4216
+ const inner = work;
4217
+ await this.#hooks.run("http:request", event, async () => {
4218
+ outcome = this.#checked(await inner(), ctx, event);
3820
4219
  if (outcome !== RAW && isStreamed(outcome.body)) run = captureContext();
3821
4220
  return outcome;
3822
4221
  });
3823
- else outcome = this.#checked(await this.#process(ctx, target, event, cors), ctx, event);
3824
- } catch (error) {
3825
- failed = true;
3826
- hookError = error;
3827
- }
3828
- if (outcome === void 0) {
3829
- const error = failed ? hookError : /* @__PURE__ */ new Error("An \"http:request\" hook wrapper did not call next()");
3830
- event.error ??= error;
3831
- const fallback = await this.#errorReply(error, ctx);
3832
- outcome = this.#checkCookies(this.#checkHeaders(fallback, ctx, event), ctx, event);
3833
- event.status = outcome.status;
3834
- recheck = true;
3835
- } else if (failed) this.#logger.error("An \"http:request\" hook wrapper failed after the request was handled", {
3836
- err: hookError,
3837
- requestId
3838
- });
3839
- if (outcome === RAW) {
3840
- ctx.commit();
3841
- const status = request.rawStatus?.() ?? 200;
3842
- event.status ??= status;
3843
- answer({
3844
- status,
3845
- headers: {},
3846
- body: null,
3847
- raw: true
3848
- });
3849
- return;
3850
- }
3851
- const serialized = this.#complete(outcome, ctx, event, requestId, cors, preflight, recheck);
3852
- const body = serialized.body;
3853
- if (!isStreamed(body)) {
3854
- const reply = adapterReply(serialized, body);
3855
- ctx.commit();
3856
- ctx.releaseBody();
3857
- answer(reply);
3858
- return;
3859
- }
3860
- const tracked = trackStream(body, run ?? captureContext(), () => ctx.abort("client"));
3861
- const session = serialized.sse;
3862
- const reply = adapterReply(serialized, tracked.stream, body instanceof Blob ? body : void 0);
3863
- if (session !== void 0) {
3864
- this.#streams.add(session);
3865
- if (this.draining) session.close("shutdown");
3866
- }
4222
+ } else outcome = this.#checked(await work(), ctx, event);
4223
+ } catch (error) {
4224
+ failed = true;
4225
+ hookError = error;
4226
+ }
4227
+ if (outcome === void 0) {
4228
+ const error = failed ? hookError : /* @__PURE__ */ new Error("An \"http:request\" hook wrapper did not call next()");
4229
+ event.error ??= error;
4230
+ const fallback = await this.#errorReply(error, ctx);
4231
+ outcome = this.#checkCookies(this.#checkHeaders(fallback, ctx, event), ctx, event);
4232
+ event.status = outcome.status;
4233
+ recheck = true;
4234
+ } else if (failed) this.#logger.error("An \"http:request\" hook wrapper failed after the request was handled", {
4235
+ err: hookError,
4236
+ requestId
4237
+ });
4238
+ if (outcome === RAW) {
3867
4239
  ctx.commit();
3868
- answer(reply);
3869
- const failure = await tracked.done;
3870
- if (session !== void 0) this.#streams.delete(session);
3871
- if (failure !== void 0) this.#logger.error("The response stream failed", {
3872
- err: failure,
3873
- requestId,
3874
- path: ctx.path
4240
+ const status = x.request.rawStatus?.() ?? 200;
4241
+ event.status ??= status;
4242
+ x.answer({
4243
+ status,
4244
+ headers: {},
4245
+ body: null,
4246
+ raw: true
3875
4247
  });
4248
+ return;
4249
+ }
4250
+ const serialized = this.#complete(outcome, ctx, event, requestId, x.cors, x.preflight, recheck);
4251
+ const body = serialized.body;
4252
+ if (!isStreamed(body)) {
4253
+ const reply = adapterReply(serialized, body);
4254
+ ctx.commit();
3876
4255
  ctx.releaseBody();
3877
- }, [[HttpTokens.Context, ctx], [HttpTokens.RequestId, requestId]]).then(over, (error) => {
3878
- over();
3879
- this.#logger.error("Failed to dispose request-scoped providers", {
3880
- err: error,
3881
- requestId
3882
- });
3883
- });
3884
- if (!this.#hooks.hasListeners("http:request")) return replied;
3885
- return replied.then((reply) => {
3886
- this.#hooks.emit("http:request", event);
3887
- return reply;
4256
+ x.answer(reply);
4257
+ return;
4258
+ }
4259
+ const tracked = trackStream(body, run ?? captureContext(), () => ctx.abort("client"));
4260
+ const session = serialized.sse;
4261
+ const reply = adapterReply(serialized, tracked.stream, body instanceof Blob ? body : void 0);
4262
+ if (session !== void 0) {
4263
+ this.#streams.add(session);
4264
+ if (this.draining) session.close("shutdown");
4265
+ }
4266
+ ctx.commit();
4267
+ x.answer(reply);
4268
+ const failure = await tracked.done;
4269
+ if (session !== void 0) this.#streams.delete(session);
4270
+ if (failure !== void 0) this.#logger.error("The response stream failed", {
4271
+ err: failure,
4272
+ requestId,
4273
+ path: ctx.path
3888
4274
  });
4275
+ ctx.releaseBody();
4276
+ }
4277
+ /** The request is over (response body sent or abandoned, scope closed). */
4278
+ #over(x) {
4279
+ const ctx = x.ctx;
4280
+ ctx.complete();
4281
+ try {
4282
+ if (!x.answered) {
4283
+ const failure = /* @__PURE__ */ new Error("Request not handled");
4284
+ const reply = serializeError(500, this.#internalBody(failure), ctx.method);
4285
+ const completed = this.#complete(reply, ctx, x.event, x.requestId, x.cors, x.preflight, true);
4286
+ x.event.status = 500;
4287
+ x.answer(completed);
4288
+ }
4289
+ } catch (error) {
4290
+ x.fail(error);
4291
+ } finally {
4292
+ this.#leave();
4293
+ }
3889
4294
  }
3890
4295
  /**
3891
4296
  * Adds the headers of the `http:request` wrappers, then the framework headers (see
@@ -3920,7 +4325,7 @@ var Pipeline = class {
3920
4325
  #checkCookies(reply, ctx, event) {
3921
4326
  const cookies = reply.cookies;
3922
4327
  if (cookies === void 0 || cookies.length === 0) return reply;
3923
- const settings = this.#options.cookies ?? DEFAULT_COOKIE_SETTINGS;
4328
+ const settings = this.#cookies;
3924
4329
  const lines = [];
3925
4330
  try {
3926
4331
  for (const cookie of cookies) lines.push(serializeWith(cookie, settings));
@@ -4038,41 +4443,72 @@ var Pipeline = class {
4038
4443
  }
4039
4444
  /** Runs a route: guards, body, interceptors, handler, serialisation. Never rejects (errors are mapped). */
4040
4445
  async #invoke(ctx, plan, event) {
4446
+ let result;
4041
4447
  try {
4042
4448
  const controller = this.#resolve(plan.controller);
4043
4449
  for (const guard of plan.guards) if (await this.#resolve(guard).canActivate(ctx) !== true) throw new ForbiddenException("Forbidden resource");
4044
4450
  if (plan.parseBody) await ctx.parseBody();
4045
4451
  const definition = plan.definition;
4046
4452
  const interceptors = plan.interceptors;
4047
- let result;
4048
- if (interceptors.length === 0) {
4049
- result = definition.invoke(controller, ctx);
4050
- if (isThenable(result)) result = await result;
4051
- } else {
4453
+ if (interceptors.length === 0) result = definition.invoke(controller, ctx);
4454
+ else {
4052
4455
  const chain = async (index) => {
4053
4456
  if (index === interceptors.length) return await definition.invoke(controller, ctx);
4054
4457
  return await this.#resolve(interceptors[index]).intercept(ctx, () => chain(index + 1));
4055
4458
  };
4056
- result = await chain(0);
4459
+ result = chain(0);
4057
4460
  }
4058
- if (definition.rawResponse === true && !(result instanceof Response)) return RAW;
4059
- const options = {
4060
- method: ctx.method,
4061
- routeMethod: definition.method,
4062
- status: definition.status,
4063
- headers: definition.headers,
4064
- context: ctx.hasResponseHeaders ? ctx.responseHeaders : void 0
4065
- };
4066
- const sse = definition.sse;
4067
- let reply;
4068
- if (sse !== void 0 && !(result instanceof Response) && !isHttpResponse(result)) {
4069
- if (!isSseSource(result)) throw new TypeError(`@Sse handler ${displayName(plan.info.controller)}.${definition.handler} must return an AsyncIterable, an Iterable or a ReadableStream of SseEvent (received ${describeResult(result)})`);
4070
- reply = serializeSseReply(this.#openStream(result, sseOptions(sse), ctx), void 0, options);
4071
- } else reply = isHttpResponse(result) ? await this.#serialize(result, ctx, options, sse) : serializeResult(result, options);
4072
- return this.#finish(event, reply);
4073
4461
  } catch (error) {
4074
4462
  return await this.#failed(error, ctx, event);
4075
4463
  }
4464
+ const settled = this.#settle(ctx, plan, event, result);
4465
+ return settled instanceof Promise ? await settled : settled;
4466
+ }
4467
+ /**
4468
+ * The rest of {@link #invoke} once the handler (and its interceptors) returned `result`: awaited
4469
+ * when it is a thenable, then serialised. Never throws nor rejects (errors are mapped).
4470
+ */
4471
+ #settle(ctx, plan, event, result) {
4472
+ if (isThenable(result)) return this.#settleLater(ctx, plan, event, result);
4473
+ try {
4474
+ const outcome = this.#outcome(ctx, plan, event, result);
4475
+ return outcome instanceof Promise ? outcome.catch((error) => this.#failed(error, ctx, event)) : outcome;
4476
+ } catch (error) {
4477
+ return this.#failed(error, ctx, event);
4478
+ }
4479
+ }
4480
+ async #settleLater(ctx, plan, event, pending) {
4481
+ let result;
4482
+ try {
4483
+ result = await pending;
4484
+ } catch (error) {
4485
+ return await this.#failed(error, ctx, event);
4486
+ }
4487
+ const settled = this.#settle(ctx, plan, event, result);
4488
+ return settled instanceof Promise ? await settled : settled;
4489
+ }
4490
+ /**
4491
+ * The outcome of a handler result: `RAW` for a `@Res()` route, otherwise its reply (files resolved,
4492
+ * event streams opened: only an `HttpResponse` may need an asynchronous step). Throws (or rejects)
4493
+ * when the result cannot be served.
4494
+ */
4495
+ #outcome(ctx, plan, event, result) {
4496
+ const definition = plan.definition;
4497
+ if (definition.rawResponse === true && !(result instanceof Response)) return RAW;
4498
+ const options = {
4499
+ method: ctx.method,
4500
+ routeMethod: definition.method,
4501
+ status: definition.status,
4502
+ headers: definition.headers,
4503
+ context: ctx.hasResponseHeaders ? ctx.responseHeaders : void 0
4504
+ };
4505
+ const sse = definition.sse;
4506
+ if (sse !== void 0 && !(result instanceof Response) && !isHttpResponse(result)) {
4507
+ if (!isSseSource(result)) throw new TypeError(`@Sse handler ${displayName(plan.info.controller)}.${definition.handler} must return an AsyncIterable, an Iterable or a ReadableStream of SseEvent (received ${describeResult(result)})`);
4508
+ return this.#finish(event, serializeSseReply(this.#openStream(result, sseOptions(sse), ctx), void 0, options));
4509
+ }
4510
+ if (!isHttpResponse(result)) return this.#finish(event, serializeResult(result, options));
4511
+ return this.#serialize(result, ctx, options, sse).then((reply) => this.#finish(event, reply));
4076
4512
  }
4077
4513
  /** Serialises a handler (or exception mapper) result; file bodies are resolved, event streams opened. */
4078
4514
  async #serialize(result, ctx, options, route) {
@@ -4234,6 +4670,126 @@ var Pipeline = class {
4234
4670
  }
4235
4671
  }
4236
4672
  };
4673
+ /** `#fastAsync` reads the body and runs the handler. */
4674
+ const NO_RESULT = Symbol("no result");
4675
+ /** A request being answered (internal): its context, its target and the promise of its reply. */
4676
+ var Exchange = class {
4677
+ request;
4678
+ ctx;
4679
+ requestId;
4680
+ target;
4681
+ preflight;
4682
+ replied;
4683
+ cors = void 0;
4684
+ answered = false;
4685
+ /** The `http:request` listeners will see the event (fast lane: keep its status). */
4686
+ tracked = false;
4687
+ /** The asynchronous part of a fast-lane request (never rejects). */
4688
+ done = void 0;
4689
+ #resolve;
4690
+ #reject;
4691
+ #event;
4692
+ /** `startTime`: the event is created now (general pipeline); otherwise when first needed (fast lane). */
4693
+ constructor(request, ctx, requestId, target, startTime) {
4694
+ this.request = request;
4695
+ this.ctx = ctx;
4696
+ this.requestId = requestId;
4697
+ this.target = target;
4698
+ this.preflight = target.kind === "preflight";
4699
+ let resolve;
4700
+ let reject;
4701
+ this.replied = new Promise((onReply, onError) => {
4702
+ resolve = onReply;
4703
+ reject = onError;
4704
+ });
4705
+ this.#resolve = resolve;
4706
+ this.#reject = reject;
4707
+ if (startTime !== void 0) this.#event = requestEvent(request, ctx, startTime);
4708
+ }
4709
+ /**
4710
+ * The `http:request` event. The fast lane creates it when the general pipeline takes over: no
4711
+ * hook saw the request start, so its `startTime` is not observed.
4712
+ */
4713
+ get event() {
4714
+ this.#event ??= requestEvent(this.request, this.ctx, performance.now());
4715
+ return this.#event;
4716
+ }
4717
+ answer(reply) {
4718
+ this.answered = true;
4719
+ this.#resolve(reply);
4720
+ }
4721
+ fail(error) {
4722
+ this.#reject(error);
4723
+ }
4724
+ };
4725
+ /** The `http:request` event of a request. */
4726
+ function requestEvent(request, ctx, startTime) {
4727
+ return {
4728
+ method: request.method,
4729
+ path: ctx.path,
4730
+ route: ctx.route?.path,
4731
+ requestId: ctx.requestId,
4732
+ headers: request.headers,
4733
+ context: ctx,
4734
+ startTime,
4735
+ responseHeaders: {}
4736
+ };
4737
+ }
4738
+ /**
4739
+ * The decoded parameters of a raw request path matched against a route, in one pass: what
4740
+ * `matchRoutePath` then `decodePathValue` (see `Pipeline.#route`) give for a path they accept.
4741
+ * `undefined` when the path does not match or a value is not valid percent-encoding: the general
4742
+ * pipeline then answers it (a reroute, a 400).
4743
+ */
4744
+ function routeParams(route, path) {
4745
+ if (path.charCodeAt(0) !== 47) return void 0;
4746
+ const params = emptyRecord();
4747
+ const segments = route.segments;
4748
+ const last = segments.length - 1;
4749
+ if (last === -1) return path === "/" ? params : void 0;
4750
+ let position = 1;
4751
+ for (let index = 0; index <= last; index++) {
4752
+ const segment = segments[index];
4753
+ if (segment.kind === "wildcard") {
4754
+ const rest = decodePathValue(path.slice(position));
4755
+ if (rest === void 0) return void 0;
4756
+ params["*"] = rest;
4757
+ return params;
4758
+ }
4759
+ const slash = path.indexOf("/", position);
4760
+ const end = slash === -1 ? path.length : slash;
4761
+ if (segment.kind === "static") {
4762
+ const value = segment.value;
4763
+ if (end - position !== value.length || !path.startsWith(value, position)) return void 0;
4764
+ } else {
4765
+ if (end === position) return void 0;
4766
+ const decoded = decodePathValue(path.slice(position, end));
4767
+ if (decoded === void 0) return void 0;
4768
+ params[segment.name] = decoded;
4769
+ }
4770
+ if (index === last) return end === path.length ? params : void 0;
4771
+ if (slash === -1) return void 0;
4772
+ position = slash + 1;
4773
+ }
4774
+ return params;
4775
+ }
4776
+ /**
4777
+ * A value the fast lane serialises as JSON: a plain object or array (its own prototype and
4778
+ * constructor), not duck-typed as a Node.js stream. Anything `serializeResult` could treat otherwise
4779
+ * (`HttpResponse`, `Response`, bytes, streams, `Blob`, strings, `undefined`...) is not.
4780
+ */
4781
+ function isPlainJson(value) {
4782
+ if (value === null || typeof value !== "object") return false;
4783
+ const prototype = Object.getPrototypeOf(value);
4784
+ const ctor = value.constructor;
4785
+ if (prototype === Object.prototype) {
4786
+ if (ctor !== Object) return false;
4787
+ } else if (prototype !== Array.prototype || ctor !== Array) return false;
4788
+ return typeof value.pipe !== "function";
4789
+ }
4790
+ const ENCODER = new TextEncoder();
4791
+ /** UTF-8 encoding of a text body, like the serialiser (a pooled `Buffer` on Node.js, `TextEncoder` on Bun). */
4792
+ const utf8 = isBun() ? (text) => ENCODER.encode(text) : (text) => Buffer$1.from(text, "utf8");
4237
4793
  /**
4238
4794
  * The reply handed to the adapter (internal fields of the serialised reply left out). A streamed
4239
4795
  * `text/event-stream` body is an event stream whatever produced it (`@Sse`, `HttpResponse.sse()`, a
@@ -5019,7 +5575,7 @@ var HttpPlugin = class HttpPlugin {
5019
5575
  adapter.registerRoute({
5020
5576
  method: registration.method,
5021
5577
  path: registration.path,
5022
- handler: (request) => pipeline.handle(plan, request)
5578
+ handler: pipeline.handler(plan)
5023
5579
  });
5024
5580
  routes.push(Object.freeze({
5025
5581
  method: registration.method,
@@ -5671,7 +6227,8 @@ function isStandardSchema(value) {
5671
6227
  * the schema strips them).
5672
6228
  *
5673
6229
  * Returns synchronously when the schema validates synchronously, a promise otherwise (async
5674
- * refinements): generated code always `await`s it.
6230
+ * refinements): generated code calls the handler directly with the value, and `await`s the value
6231
+ * when it is a thenable (`isThenable`).
5675
6232
  *
5676
6233
  * @param location what is validated, used in the error message: `body`, `query`, `query "page"`,
5677
6234
  * `param "id"`, `headers`, `cookie "sid"`, `cookies`...
@@ -5681,8 +6238,9 @@ function isStandardSchema(value) {
5681
6238
  * @throws TypeError when `schema` is not a Standard Schema v1 (a programming error → 500).
5682
6239
  */
5683
6240
  function validate(schema, value, location) {
5684
- if (!isStandardSchema(schema)) throw new TypeError(`The schema of ${location} is not a Standard Schema v1 (missing "~standard.validate")`);
5685
- const result = schema["~standard"].validate(value);
6241
+ const props = schema !== null && (typeof schema === "object" || typeof schema === "function") ? schema["~standard"] : void 0;
6242
+ if (props === null || typeof props !== "object" || props.version !== 1 || typeof props.validate !== "function") throw new TypeError(`The schema of ${location} is not a Standard Schema v1 (missing "~standard.validate")`);
6243
+ const result = props.validate(value);
5686
6244
  if (isThenable(result)) return Promise.resolve(result).then((settled) => unwrap(settled, location));
5687
6245
  return unwrap(result, location);
5688
6246
  }
@@ -5707,6 +6265,6 @@ function redact(issue) {
5707
6265
  path
5708
6266
  };
5709
6267
  }
5710
- export { All, BadGatewayException, BadRequestException, Body, BodyLimit, ConflictException, Controller, Cookie, Ctx, Delete, EventChannel, ForbiddenException, GatewayTimeoutException, Get, GoneException, Head, Header, Headers, HttpCode, HttpException, HttpPlugin, HttpResponse, HttpTokens, InternalServerErrorException, MethodNotAllowedException, NotFoundException, NotImplementedException, Options, Param, Patch, PayloadTooLargeException, Post, Put, Query, Req, RequestAbortedError, Res, ServiceUnavailableException, SignedCookie, Sse, TooManyRequestsException, UnauthorizedException, UnprocessableEntityException, UnsupportedMediaTypeException, UploadedFile, UploadedFiles, UseGuard, UseInterceptor, Validate, ValidationException, coerce, contentDisposition, contentTypeFor, createRouteDecorator, encodeSseEvent, formatByteSize, isHttpException, isHttpResponse, isJsonType, isStandardSchema, isValidStatus, matchesMediaType, nodeAdapter, parseBody, parseByteSize, parseCookieHeader, parseMediaType, parseQuery, parseRange, parseSetCookie, parseSseStream, serializeClearCookie, serializeCookie, statusText, toIssueDetail, uploads, validate };
6268
+ export { All, BadGatewayException, BadRequestException, Body, BodyLimit, ConflictException, Controller, Cookie, Ctx, Delete, EventChannel, ForbiddenException, GatewayTimeoutException, Get, GoneException, Head, Header, Headers, HttpCode, HttpException, HttpPlugin, HttpResponse, HttpTokens, InternalServerErrorException, MethodNotAllowedException, NotFoundException, NotImplementedException, Options, Param, Patch, PayloadTooLargeException, Post, Put, Query, Req, RequestAbortedError, Res, ServiceUnavailableException, SignedCookie, Sse, TooManyRequestsException, UnauthorizedException, UnprocessableEntityException, UnsupportedMediaTypeException, UploadedFile, UploadedFiles, UseGuard, UseInterceptor, Validate, ValidationException, coerce, contentDisposition, contentTypeFor, createRouteDecorator, encodeSseEvent, formatByteSize, isHttpException, isHttpResponse, isJsonType, isStandardSchema, isThenable, isValidStatus, matchesMediaType, nodeAdapter, parseBody, parseByteSize, parseCookieHeader, parseMediaType, parseQuery, parseRange, parseSetCookie, parseSseStream, serializeClearCookie, serializeCookie, statusText, toIssueDetail, uploads, validate };
5711
6269
 
5712
6270
  //# sourceMappingURL=index.mjs.map