@oxide/skepsis 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/README.md +15 -1
  2. package/dist/cli.js +1280 -433
  3. package/dist/web/assets/actionscript-3-Cs6JJXT5.js +1 -0
  4. package/dist/web/assets/ahk-CA9gdOdF.js +1 -0
  5. package/dist/web/assets/ahk2-_6rzW9BS.js +1 -0
  6. package/dist/web/assets/{angular-html-pG5dAD0_.js → angular-html-C5aEDwTp.js} +1 -1
  7. package/dist/web/assets/{angular-ts-DIcf2VTw.js → angular-ts-rB5llKv-.js} +1 -1
  8. package/dist/web/assets/apex-KFGFyKwG.js +1 -0
  9. package/dist/web/assets/{apl-BTdhpGn9.js → apl-CqbPKRAc.js} +1 -1
  10. package/dist/web/assets/asciidoc-SCjQUq34.js +1 -0
  11. package/dist/web/assets/{astro-DakfVy_Y.js → astro-CM0Pxilc.js} +1 -1
  12. package/dist/web/assets/{bat-Bo4NYOV-.js → bat-qdxAdBWQ.js} +1 -1
  13. package/dist/web/assets/bird2-CYIUgYqB.js +1 -0
  14. package/dist/web/assets/{blade-C6DTZ92F.js → blade-ogn21bYe.js} +1 -1
  15. package/dist/web/assets/bsl-_VjlB9mv.js +1 -0
  16. package/dist/web/assets/{c-BknOWMt9.js → c-CGor3kLj.js} +1 -1
  17. package/dist/web/assets/c3-D0apG41V.js +1 -0
  18. package/dist/web/assets/catppuccin-frappe-C9Q5zVZY.js +1 -0
  19. package/dist/web/assets/catppuccin-latte-CtsyrtPq.js +1 -0
  20. package/dist/web/assets/catppuccin-macchiato-R8nAf1vR.js +1 -0
  21. package/dist/web/assets/catppuccin-mocha-DjuaAJKi.js +1 -0
  22. package/dist/web/assets/chapel-DhXHcJ4N.js +1 -0
  23. package/dist/web/assets/clarity-CtfBBspg.js +1 -0
  24. package/dist/web/assets/cobol-6N_aCEjh.js +1 -0
  25. package/dist/web/assets/{coffee-BPXprhpm.js → coffee-CE_P7pNd.js} +1 -1
  26. package/dist/web/assets/coq-DuBRPxYg.js +1 -0
  27. package/dist/web/assets/cpp-B88fnU0Z.js +1 -0
  28. package/dist/web/assets/{crystal-UlL7t4Zq.js → crystal-BT-YK4sB.js} +1 -1
  29. package/dist/web/assets/{csharp-Ct8U2NOr.js → csharp-oqKa8noW.js} +1 -1
  30. package/dist/web/assets/{css-CmUKBEHK.js → css-DCGRDgpo.js} +1 -1
  31. package/dist/web/assets/dart-CnvKMtbv.js +1 -0
  32. package/dist/web/assets/{edge-Bva-bvwE.js → edge-arvQfpwJ.js} +1 -1
  33. package/dist/web/assets/{elixir-LgMpmQwl.js → elixir-C7GGiF0W.js} +1 -1
  34. package/dist/web/assets/{elm-ChIA19GX.js → elm-D9PPgTIK.js} +1 -1
  35. package/dist/web/assets/emacs-lisp-c_oH4hRZ.js +1 -0
  36. package/dist/web/assets/{erb-BUe-kf6W.js → erb-DtcOMAax.js} +1 -1
  37. package/dist/web/assets/{gdresource-C0sCabJj.js → gdresource-xMC7jr7x.js} +1 -1
  38. package/dist/web/assets/gdscript-DYvRD3hg.js +1 -0
  39. package/dist/web/assets/{git-rebase-Bkg7Rriu.js → git-rebase-B_XRqoYY.js} +1 -1
  40. package/dist/web/assets/{glimmer-js-xiPCviF3.js → glimmer-js-ClxSee9S.js} +1 -1
  41. package/dist/web/assets/{glimmer-ts-CDtPNXki.js → glimmer-ts-Dhuf-Y5F.js} +1 -1
  42. package/dist/web/assets/{glsl-bk_LJBBf.js → glsl-ynj6iQSj.js} +1 -1
  43. package/dist/web/assets/{go-BJwz_mda.js → go-rLFTqkRN.js} +1 -1
  44. package/dist/web/assets/{graphql-vA1XHlCX.js → graphql-BpoONP-Q.js} +1 -1
  45. package/dist/web/assets/hack-BzaytsIT.js +1 -0
  46. package/dist/web/assets/{haml-BGCPnhpH.js → haml-DPP1vu4S.js} +1 -1
  47. package/dist/web/assets/{handlebars-gtAMNNdU.js → handlebars-BaJLp3cS.js} +1 -1
  48. package/dist/web/assets/haxe-C8oCnwJJ.js +1 -0
  49. package/dist/web/assets/{horizon-bright-Br1oVSNq.js → horizon-bright-DSNQnXHK.js} +1 -1
  50. package/dist/web/assets/{html-derivative-BPuTRG5t.js → html-derivative-Beps_752.js} +1 -1
  51. package/dist/web/assets/{html-CgIt1AET.js → html-v5mS3OkU.js} +1 -1
  52. package/dist/web/assets/{http-DdtwxenI.js → http-BST5nRdv.js} +1 -1
  53. package/dist/web/assets/{hurl-DSrXqpg7.js → hurl-CN6vmMBm.js} +1 -1
  54. package/dist/web/assets/hxml-Dcm88srW.js +1 -0
  55. package/dist/web/assets/index-B3HpMNO5.js +1597 -0
  56. package/dist/web/assets/index-BSWivZhr.css +1 -0
  57. package/dist/web/assets/{java-b4q4A2MJ.js → java-DUwoI7LA.js} +1 -1
  58. package/dist/web/assets/{javascript-DvrXh2-w.js → javascript-CcMqq0Uh.js} +1 -1
  59. package/dist/web/assets/{jinja-bz3Ea8Og.js → jinja-BrGVdWXp.js} +1 -1
  60. package/dist/web/assets/{jison-ChuG6csj.js → jison-Dx7sppLf.js} +1 -1
  61. package/dist/web/assets/{json-CHS9jaD3.js → json-0dY4XPp1.js} +1 -1
  62. package/dist/web/assets/{jsx-1EPpFZLR.js → jsx-BZwRrCyr.js} +1 -1
  63. package/dist/web/assets/julia-D-Z-tYL2.js +1 -0
  64. package/dist/web/assets/just-zgqsqrUB.js +1 -0
  65. package/dist/web/assets/kanagawa-dragon-Bozd7klA.js +1 -0
  66. package/dist/web/assets/kanagawa-lotus-BmuOG9ZW.js +1 -0
  67. package/dist/web/assets/kanagawa-wave-BML5mF2J.js +1 -0
  68. package/dist/web/assets/{kusto-BUv0MjJC.js → kusto-C7mF5XQf.js} +1 -1
  69. package/dist/web/assets/latex-C7HLdg74.js +1 -0
  70. package/dist/web/assets/{liquid-B-M2TsXg.js → liquid-BEZROxvV.js} +1 -1
  71. package/dist/web/assets/{llvm-Cm23YOpf.js → llvm-DqHOMS-s.js} +1 -1
  72. package/dist/web/assets/{lua-C6t1QxbP.js → lua-C2p9eHxb.js} +1 -1
  73. package/dist/web/assets/luau-C2pBCSgt.js +1 -0
  74. package/dist/web/assets/{marko-BXp6EEyC.js → marko-DXYA4QD1.js} +1 -1
  75. package/dist/web/assets/mdc-Dss9CZfr.js +1 -0
  76. package/dist/web/assets/mermaid-BxpfTIzt.js +1 -0
  77. package/dist/web/assets/mojo-fg40_ntQ.js +1 -0
  78. package/dist/web/assets/monokai-B_bV9PQ9.js +1 -0
  79. package/dist/web/assets/moonbit-DgjMoLWr.js +1 -0
  80. package/dist/web/assets/move-BYnGhZoM.js +1 -0
  81. package/dist/web/assets/{nextflow-Bbiyy34d.js → nextflow-BJtWHP5T.js} +1 -1
  82. package/dist/web/assets/nextflow-groovy-DJMQeKeT.js +1 -0
  83. package/dist/web/assets/{nginx-CYoJ8RiQ.js → nginx-DmShDBsa.js} +1 -1
  84. package/dist/web/assets/{nim-Lmg_RrgG.js → nim-BqYI3_iM.js} +1 -1
  85. package/dist/web/assets/nsis-CjNLYCLg.js +1 -0
  86. package/dist/web/assets/nushell-DHYfO66s.js +1 -0
  87. package/dist/web/assets/org-hHoeeaKm.js +1 -0
  88. package/dist/web/assets/{perl-BzG_43hA.js → perl-fn2L5MRS.js} +1 -1
  89. package/dist/web/assets/php-BwyO_7IL.js +1 -0
  90. package/dist/web/assets/pierre-dark-CpLgRqie.js +1 -0
  91. package/dist/web/assets/pierre-dark-protanopia-deuteranopia-B35FxJx-.js +1 -0
  92. package/dist/web/assets/pierre-dark-soft-kZQmAZld.js +1 -0
  93. package/dist/web/assets/pierre-dark-tritanopia-CpjhbsIL.js +1 -0
  94. package/dist/web/assets/pierre-dark-vibrant-CpQYzh95.js +1 -0
  95. package/dist/web/assets/pierre-light-CoaEpmwp.js +1 -0
  96. package/dist/web/assets/pierre-light-protanopia-deuteranopia-0fSaH845.js +1 -0
  97. package/dist/web/assets/pierre-light-soft-lWLdNTOI.js +1 -0
  98. package/dist/web/assets/pierre-light-tritanopia-CEbqgOJL.js +1 -0
  99. package/dist/web/assets/pierre-light-vibrant-D80Fkn33.js +1 -0
  100. package/dist/web/assets/{powershell-DshXNtvi.js → powershell-CCSX75yM.js} +1 -1
  101. package/dist/web/assets/prisma-DMgNhnYS.js +1 -0
  102. package/dist/web/assets/{pug-CRa_NVRK.js → pug-Dl7ZKYHx.js} +1 -1
  103. package/dist/web/assets/{qml-CyX6SUld.js → qml-pWdxV5ol.js} +1 -1
  104. package/dist/web/assets/r-DeBiNT1C.js +1 -0
  105. package/dist/web/assets/{razor-Um-R2urW.js → razor-zmMxDX0l.js} +1 -1
  106. package/dist/web/assets/rbs-C0MpOrj4.js +1 -0
  107. package/dist/web/assets/red-DX1BQOs8.js +1 -0
  108. package/dist/web/assets/{regexp-CNZtvSUc.js → regexp-xTlKvM-H.js} +1 -1
  109. package/dist/web/assets/rose-pine-aMsaMD1D.js +1 -0
  110. package/dist/web/assets/rose-pine-dawn-8PwUyIlP.js +1 -0
  111. package/dist/web/assets/rose-pine-moon-DO-qXg-I.js +1 -0
  112. package/dist/web/assets/{rst-CDHVc2Gd.js → rst-BuNrOwzF.js} +1 -1
  113. package/dist/web/assets/ruby-Cdu0fHrj.js +1 -0
  114. package/dist/web/assets/{sas-DncoNlJt.js → sas-CL8JWcZe.js} +1 -1
  115. package/dist/web/assets/{scala-DKOlJaKm.js → scala-BiFt_7mu.js} +1 -1
  116. package/dist/web/assets/{scss-C5jkio7Q.js → scss-D_SpSPm_.js} +1 -1
  117. package/dist/web/assets/{shellscript-CyzeyQay.js → shellscript-Bd28erXn.js} +1 -1
  118. package/dist/web/assets/{shellsession-ByVGKVNS.js → shellsession-KpWtzopz.js} +1 -1
  119. package/dist/web/assets/smalltalk-BHpQb5nM.js +1 -0
  120. package/dist/web/assets/smithy-Dgaz7aur.js +1 -0
  121. package/dist/web/assets/solarized-dark-UdsmMDCL.js +1 -0
  122. package/dist/web/assets/solarized-light-C1IUL_tW.js +1 -0
  123. package/dist/web/assets/solidity-Bj7E1mRn.js +1 -0
  124. package/dist/web/assets/{soy-zYFGKx5x.js → soy-Cm_tfFk2.js} +1 -1
  125. package/dist/web/assets/{sql-Dj917N_H.js → sql-BXTtmIcY.js} +1 -1
  126. package/dist/web/assets/{stata-thuN2N13.js → stata-3Pp0Vpoz.js} +1 -1
  127. package/dist/web/assets/surrealql-3C_44OtM.js +1 -0
  128. package/dist/web/assets/{svelte-CwDkJEno.js → svelte-Jk4EqHbZ.js} +1 -1
  129. package/dist/web/assets/swift-CyEgAFGc.js +1 -0
  130. package/dist/web/assets/system-verilog-Dh5ihWbf.js +1 -0
  131. package/dist/web/assets/{templ-BrPesEYk.js → templ-Bs_fAS0X.js} +1 -1
  132. package/dist/web/assets/tex-B8ZXCJNT.js +1 -0
  133. package/dist/web/assets/ts-tags-BaXDfNdt.js +1 -0
  134. package/dist/web/assets/{tsx-D5IskOUN.js → tsx-Q43CUQyb.js} +1 -1
  135. package/dist/web/assets/twig-qmn8-L4G.js +1 -0
  136. package/dist/web/assets/{typescript-r_zvhrlY.js → typescript-DfCNjb9H.js} +1 -1
  137. package/dist/web/assets/typespec-BRdr0IET.js +1 -0
  138. package/dist/web/assets/typst-DDL_Klw6.js +1 -0
  139. package/dist/web/assets/{v-DETTlOr0.js → v-DBj4K9d_.js} +1 -1
  140. package/dist/web/assets/{vb-Djn5o6TS.js → vb-DOwzaHZ0.js} +1 -1
  141. package/dist/web/assets/verilog-B2gwz-sJ.js +1 -0
  142. package/dist/web/assets/vesper-DdrHHSXu.js +1 -0
  143. package/dist/web/assets/{vue-BzuE9sEQ.js → vue-BoIjRuVV.js} +1 -1
  144. package/dist/web/assets/{vue-html-DwsEam__.js → vue-html-DpELogdz.js} +1 -1
  145. package/dist/web/assets/{vue-vine-9CKb8y5-.js → vue-vine-DrISOBMU.js} +1 -1
  146. package/dist/web/assets/worker-DTm3p0vg.js +161 -0
  147. package/dist/web/assets/{xml-cD-peQlu.js → xml-Bwdcxk7e.js} +1 -1
  148. package/dist/web/assets/{xsl-BCD-tggE.js → xsl-FwP02LKO.js} +1 -1
  149. package/dist/web/assets/{yaml-DRdq_7xy.js → yaml-Boxda9qL.js} +1 -1
  150. package/dist/web/index.html +7 -2
  151. package/package.json +8 -8
  152. package/dist/web/assets/actionscript-3--17pq3dv.js +0 -1
  153. package/dist/web/assets/apex-CGTLDQj6.js +0 -1
  154. package/dist/web/assets/asciidoc-DE70LPWp.js +0 -1
  155. package/dist/web/assets/bird2-C2hNVINV.js +0 -1
  156. package/dist/web/assets/bsl-BkkzgIyY.js +0 -1
  157. package/dist/web/assets/c3-CnJL0r0V.js +0 -1
  158. package/dist/web/assets/catppuccin-frappe-3VR1Za6u.js +0 -1
  159. package/dist/web/assets/catppuccin-latte-DwIHMF0Q.js +0 -1
  160. package/dist/web/assets/catppuccin-macchiato-DYnBP6_5.js +0 -1
  161. package/dist/web/assets/catppuccin-mocha-DYhrFGRu.js +0 -1
  162. package/dist/web/assets/clarity-SemFz856.js +0 -1
  163. package/dist/web/assets/cobol-DM9v9gYz.js +0 -1
  164. package/dist/web/assets/coq-BrsZFFmf.js +0 -1
  165. package/dist/web/assets/cpp-DLQwcdN2.js +0 -1
  166. package/dist/web/assets/dart-DkHntEIa.js +0 -1
  167. package/dist/web/assets/emacs-lisp-C9PiwqqW.js +0 -1
  168. package/dist/web/assets/gdscript-Cp2uCuqX.js +0 -1
  169. package/dist/web/assets/hack-B_CtamN1.js +0 -1
  170. package/dist/web/assets/haxe-OTjmBuCE.js +0 -1
  171. package/dist/web/assets/hxml-B0Qn7Nwc.js +0 -1
  172. package/dist/web/assets/index-CbKUFESc.css +0 -1
  173. package/dist/web/assets/index-CzdR8dhb.js +0 -286
  174. package/dist/web/assets/julia-Cbx7uJVy.js +0 -1
  175. package/dist/web/assets/just-Ls8h7RL1.js +0 -1
  176. package/dist/web/assets/kanagawa-dragon-CXtmUGW6.js +0 -1
  177. package/dist/web/assets/kanagawa-lotus-BN08jTvb.js +0 -1
  178. package/dist/web/assets/kanagawa-wave-CTweb8Dz.js +0 -1
  179. package/dist/web/assets/latex-VMqHKg1F.js +0 -1
  180. package/dist/web/assets/luau-CNKltnaQ.js +0 -1
  181. package/dist/web/assets/mdc-BXUMSRUO.js +0 -1
  182. package/dist/web/assets/mermaid-Bk4SNUv9.js +0 -1
  183. package/dist/web/assets/mojo-BgCJLMeH.js +0 -1
  184. package/dist/web/assets/monokai-CdkpiU2Y.js +0 -1
  185. package/dist/web/assets/moonbit-CaWjb8XO.js +0 -1
  186. package/dist/web/assets/move-B1IS1UjX.js +0 -1
  187. package/dist/web/assets/nextflow-groovy-Dc_ddanL.js +0 -1
  188. package/dist/web/assets/nushell-DcLAeLz5.js +0 -1
  189. package/dist/web/assets/php-DmlshsRI.js +0 -1
  190. package/dist/web/assets/pierre-dark-sU4Zdns8.js +0 -1
  191. package/dist/web/assets/pierre-dark-soft-HXgun5vs.js +0 -1
  192. package/dist/web/assets/pierre-dark-vibrant-D4RhcSIK.js +0 -1
  193. package/dist/web/assets/pierre-light-DWBk51d8.js +0 -1
  194. package/dist/web/assets/pierre-light-soft-CodEzPxf.js +0 -1
  195. package/dist/web/assets/pierre-light-vibrant-B76X7i5Y.js +0 -1
  196. package/dist/web/assets/prisma-BsRQq5mF.js +0 -1
  197. package/dist/web/assets/r-DtTGDaOA.js +0 -1
  198. package/dist/web/assets/red-CJ3rzSJv.js +0 -1
  199. package/dist/web/assets/rose-pine-BthvhNj6.js +0 -1
  200. package/dist/web/assets/rose-pine-dawn-Dg85fqjY.js +0 -1
  201. package/dist/web/assets/rose-pine-moon-hon4tzzS.js +0 -1
  202. package/dist/web/assets/ruby-MAT-rQcK.js +0 -1
  203. package/dist/web/assets/smalltalk-B16xEiuN.js +0 -1
  204. package/dist/web/assets/solarized-dark-DV17i1UV.js +0 -1
  205. package/dist/web/assets/solarized-light-DSh2HLQt.js +0 -1
  206. package/dist/web/assets/solidity-CKzVLygQ.js +0 -1
  207. package/dist/web/assets/surrealql-DuXCW9WN.js +0 -1
  208. package/dist/web/assets/swift-DonLKvLd.js +0 -1
  209. package/dist/web/assets/system-verilog-DJ5XKQeo.js +0 -1
  210. package/dist/web/assets/tex-CwAnoL2j.js +0 -1
  211. package/dist/web/assets/ts-tags-0yZMGjSv.js +0 -1
  212. package/dist/web/assets/twig-BgqTRaMb.js +0 -1
  213. package/dist/web/assets/typespec-B88KGewJ.js +0 -1
  214. package/dist/web/assets/typst-DI99ib-x.js +0 -1
  215. package/dist/web/assets/verilog-CiiDBU1e.js +0 -1
  216. package/dist/web/assets/vesper-D5bVUKB1.js +0 -1
package/dist/cli.js CHANGED
@@ -1,19 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFileSync, spawn } from "child_process";
3
- import fs, { existsSync } from "node:fs";
3
+ import fs, { createReadStream, existsSync, statSync } from "node:fs";
4
4
  import path, { basename, dirname, extname, join, relative } from "node:path";
5
5
  import { EventEmitter } from "node:events";
6
6
  import childProcess, { spawn as spawn$1 } from "node:child_process";
7
- import process$1 from "node:process";
7
+ import process$1, { versions } from "node:process";
8
8
  import { stripVTControlCharacters } from "node:util";
9
- import { createServer } from "http";
10
- import { Http2ServerRequest, constants } from "http2";
11
- import { Readable } from "stream";
12
- import crypto$1, { createHash } from "crypto";
13
- import { createReadStream, existsSync as existsSync$1, statSync } from "fs";
14
- import { join as join$1 } from "path";
15
- import { versions } from "process";
9
+ import { STATUS_CODES, createServer } from "node:http";
10
+ import { Http2ServerRequest, constants } from "node:http2";
11
+ import { Readable } from "node:stream";
16
12
  import { open, readFile, writeFile } from "node:fs/promises";
13
+ import { join as join$1 } from "path";
14
+ import { createHash } from "crypto";
17
15
  import { mkdir, readFile as readFile$1, writeFile as writeFile$1 } from "fs/promises";
18
16
  //#region \0rolldown/runtime.js
19
17
  var __defProp = Object.defineProperty;
@@ -91,7 +89,6 @@ var Argument = class {
91
89
  default:
92
90
  this.required = true;
93
91
  this._name = name;
94
- break;
95
92
  }
96
93
  if (this._name.endsWith("...")) {
97
94
  this.variadic = true;
@@ -1546,9 +1543,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
1546
1543
  const oldValue = this.getOptionValue(name);
1547
1544
  if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1548
1545
  else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1549
- if (val == null) if (option.negate) val = false;
1550
- else if (option.isBoolean() || option.optional) val = true;
1551
- else val = "";
1546
+ if (val == null) {
1547
+ if (option.negate) val = false;
1548
+ else if (option.isBoolean() || option.optional) val = true;
1549
+ else val = "";
1550
+ }
1552
1551
  this.setOptionValueWithSource(name, val, valueSource);
1553
1552
  };
1554
1553
  this.on("option:" + oname, (val) => {
@@ -1952,12 +1951,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
1952
1951
  }
1953
1952
  const launchWithNode = sourceExt.includes(path.extname(executableFile));
1954
1953
  let proc;
1955
- if (process$1.platform !== "win32") if (launchWithNode) {
1956
- args.unshift(executableFile);
1957
- args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
1958
- proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
1959
- } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1960
- else {
1954
+ if (process$1.platform !== "win32") {
1955
+ if (launchWithNode) {
1956
+ args.unshift(executableFile);
1957
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
1958
+ proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
1959
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1960
+ } else {
1961
1961
  this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1962
1962
  args.unshift(executableFile);
1963
1963
  args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
@@ -2401,8 +2401,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2401
2401
  "default",
2402
2402
  "config",
2403
2403
  "env"
2404
- ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2405
- else this.emit(`optionEnv:${option.name()}`);
2404
+ ].includes(this.getOptionValueSource(optionKey))) {
2405
+ if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2406
+ else this.emit(`optionEnv:${option.name()}`);
2407
+ }
2406
2408
  }
2407
2409
  });
2408
2410
  }
@@ -3040,18 +3042,28 @@ var HTTPException = class extends Error {
3040
3042
  //#region node_modules/hono/dist/request/constants.js
3041
3043
  var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
3042
3044
  //#endregion
3045
+ //#region node_modules/hono/dist/utils/buffer.js
3046
+ var bufferToFormData = (arrayBuffer, contentType) => {
3047
+ return new Response(arrayBuffer, { headers: { "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase()) } }).formData();
3048
+ };
3049
+ //#endregion
3043
3050
  //#region node_modules/hono/dist/utils/body.js
3051
+ var isRawRequest = (request) => "headers" in request;
3044
3052
  var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
3045
3053
  const { all = false, dot = false } = options;
3046
- const contentType = (request instanceof HonoRequest ? request.raw.headers : request.headers).get("Content-Type");
3047
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) return parseFormData(request, {
3054
+ const mediaType = (isRawRequest(request) ? request.headers : request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();
3055
+ if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded") return parseFormData(request, {
3048
3056
  all,
3049
3057
  dot
3050
3058
  });
3051
3059
  return {};
3052
3060
  };
3053
3061
  async function parseFormData(request, options) {
3054
- const formData = await request.formData();
3062
+ if (!isRawRequest(request) && request.bodyCache.formData) return convertFormDataToBodyData(await request.bodyCache.formData, options);
3063
+ const headers = isRawRequest(request) ? request.headers : request.raw.headers;
3064
+ const formDataPromise = bufferToFormData(await request.arrayBuffer(), headers.get("Content-Type") || "");
3065
+ if (!isRawRequest(request)) request.bodyCache.formData = formDataPromise;
3066
+ const formData = await formDataPromise;
3055
3067
  if (formData) return convertFormDataToBodyData(formData, options);
3056
3068
  return {};
3057
3069
  }
@@ -3070,9 +3082,10 @@ function convertFormDataToBodyData(formData, options) {
3070
3082
  return form;
3071
3083
  }
3072
3084
  var handleParsingAllValues = (form, key, value) => {
3073
- if (form[key] !== void 0) if (Array.isArray(form[key])) form[key].push(value);
3074
- else form[key] = [form[key], value];
3075
- else if (!key.endsWith("[]")) form[key] = value;
3085
+ if (form[key] !== void 0) {
3086
+ if (Array.isArray(form[key])) form[key].push(value);
3087
+ else form[key] = [form[key], value];
3088
+ } else if (!key.endsWith("[]")) form[key] = value;
3076
3089
  else form[key] = [value];
3077
3090
  };
3078
3091
  var handleParsingNestedValues = (form, key, value) => {
@@ -3126,20 +3139,22 @@ var getPattern = (label, next) => {
3126
3139
  const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
3127
3140
  if (match) {
3128
3141
  const cacheKey = `${label}#${next}`;
3129
- if (!patternCache[cacheKey]) if (match[2]) patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
3130
- cacheKey,
3131
- match[1],
3132
- new RegExp(`^${match[2]}(?=/${next})`)
3133
- ] : [
3134
- label,
3135
- match[1],
3136
- new RegExp(`^${match[2]}$`)
3137
- ];
3138
- else patternCache[cacheKey] = [
3139
- label,
3140
- match[1],
3141
- true
3142
- ];
3142
+ if (!patternCache[cacheKey]) {
3143
+ if (match[2]) patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
3144
+ cacheKey,
3145
+ match[1],
3146
+ new RegExp(`^${match[2]}(?=/${next})`)
3147
+ ] : [
3148
+ label,
3149
+ match[1],
3150
+ new RegExp(`^${match[2]}$`)
3151
+ ];
3152
+ else patternCache[cacheKey] = [
3153
+ label,
3154
+ match[1],
3155
+ true
3156
+ ];
3157
+ }
3143
3158
  return patternCache[cacheKey];
3144
3159
  }
3145
3160
  return null;
@@ -3189,24 +3204,26 @@ var checkOptionalParameter = (path) => {
3189
3204
  let basePath = "";
3190
3205
  segments.forEach((segment) => {
3191
3206
  if (segment !== "" && !/\:/.test(segment)) basePath += "/" + segment;
3192
- else if (/\:/.test(segment)) if (/\?/.test(segment)) {
3193
- if (results.length === 0 && basePath === "") results.push("/");
3194
- else results.push(basePath);
3195
- const optionalSegment = segment.replace("?", "");
3196
- basePath += "/" + optionalSegment;
3197
- results.push(basePath);
3198
- } else basePath += "/" + segment;
3207
+ else if (/\:/.test(segment)) {
3208
+ if (segment.charCodeAt(segment.length - 1) === 63) {
3209
+ if (results.length === 0 && basePath === "") results.push("/");
3210
+ else results.push(basePath);
3211
+ const optionalSegment = segment.slice(0, -1);
3212
+ basePath += "/" + optionalSegment;
3213
+ results.push(basePath);
3214
+ } else basePath += "/" + segment;
3215
+ }
3199
3216
  });
3200
3217
  return results.filter((v, i, a) => a.indexOf(v) === i);
3201
3218
  };
3219
+ var tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode$1(str, decodeURIComponent_) : str;
3202
3220
  var _decodeURI = (value) => {
3203
- if (!/[%+]/.test(value)) return value;
3204
3221
  if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
3205
- return value.indexOf("%") !== -1 ? tryDecode$1(value, decodeURIComponent_) : value;
3222
+ return tryDecodeURIComponent(value);
3206
3223
  };
3207
3224
  var _getQueryParam = (url, key, multiple) => {
3208
3225
  let encoded;
3209
- if (!multiple && key && !/[%+]/.test(key)) {
3226
+ if (!multiple && key && key.indexOf("%") === -1 && key.indexOf("+") === -1) {
3210
3227
  let keyIndex2 = url.indexOf("?", 8);
3211
3228
  if (keyIndex2 === -1) return;
3212
3229
  if (!url.startsWith(key, keyIndex2 + 1)) keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
@@ -3222,7 +3239,7 @@ var _getQueryParam = (url, key, multiple) => {
3222
3239
  encoded = /[%+]/.test(url);
3223
3240
  if (!encoded) return;
3224
3241
  }
3225
- const results = {};
3242
+ const results = /* @__PURE__ */ Object.create(null);
3226
3243
  encoded ??= /[%+]/.test(url);
3227
3244
  let keyIndex = url.indexOf("?", 8);
3228
3245
  while (keyIndex !== -1) {
@@ -3253,7 +3270,6 @@ var getQueryParams = (url, key) => {
3253
3270
  var decodeURIComponent_ = decodeURIComponent;
3254
3271
  //#endregion
3255
3272
  //#region node_modules/hono/dist/request.js
3256
- var tryDecodeURIComponent = (str) => tryDecode$1(str, decodeURIComponent_);
3257
3273
  var HonoRequest = class {
3258
3274
  /**
3259
3275
  * `.raw` can get the raw Request object.
@@ -3291,7 +3307,6 @@ var HonoRequest = class {
3291
3307
  this.raw = request;
3292
3308
  this.path = path;
3293
3309
  this.#matchResult = matchResult;
3294
- this.#validatedData = {};
3295
3310
  }
3296
3311
  param(key) {
3297
3312
  return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
@@ -3299,14 +3314,14 @@ var HonoRequest = class {
3299
3314
  #getDecodedParam(key) {
3300
3315
  const paramKey = this.#matchResult[0][this.routeIndex][1][key];
3301
3316
  const param = this.#getParamValue(paramKey);
3302
- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
3317
+ return param && tryDecodeURIComponent(param);
3303
3318
  }
3304
3319
  #getAllDecodedParams() {
3305
3320
  const decoded = {};
3306
3321
  const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
3307
3322
  for (const key of keys) {
3308
3323
  const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
3309
- if (value !== void 0) decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
3324
+ if (value !== void 0) decoded[key] = tryDecodeURIComponent(value);
3310
3325
  }
3311
3326
  return decoded;
3312
3327
  }
@@ -3321,7 +3336,7 @@ var HonoRequest = class {
3321
3336
  }
3322
3337
  header(name) {
3323
3338
  if (name) return this.raw.headers.get(name) ?? void 0;
3324
- const headerData = {};
3339
+ const headerData = /* @__PURE__ */ Object.create(null);
3325
3340
  this.raw.headers.forEach((value, key) => {
3326
3341
  headerData[key] = value;
3327
3342
  });
@@ -3334,8 +3349,7 @@ var HonoRequest = class {
3334
3349
  const { bodyCache, raw } = this;
3335
3350
  const cachedBody = bodyCache[key];
3336
3351
  if (cachedBody) return cachedBody;
3337
- const anyCachedKey = Object.keys(bodyCache)[0];
3338
- if (anyCachedKey) return bodyCache[anyCachedKey].then((body) => {
3352
+ for (const anyCachedKey in bodyCache) return bodyCache[anyCachedKey].then((body) => {
3339
3353
  if (anyCachedKey === "json") body = JSON.stringify(body);
3340
3354
  return new Response(body)[key]();
3341
3355
  });
@@ -3434,10 +3448,10 @@ var HonoRequest = class {
3434
3448
  * @param data - The validated data to add.
3435
3449
  */
3436
3450
  addValidatedData(target, data) {
3437
- this.#validatedData[target] = data;
3451
+ (this.#validatedData ??= {})[target] = data;
3438
3452
  }
3439
3453
  valid(target) {
3440
- return this.#validatedData[target];
3454
+ return this.#validatedData?.[target];
3441
3455
  }
3442
3456
  /**
3443
3457
  * `.url()` can get the request url strings.
@@ -3804,20 +3818,32 @@ var Context = class {
3804
3818
  return Object.fromEntries(this.#var);
3805
3819
  }
3806
3820
  #newResponse(data, arg, headers) {
3807
- const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
3808
- if (typeof arg === "object" && "headers" in arg) {
3809
- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
3810
- for (const [key, value] of argHeaders) if (key.toLowerCase() === "set-cookie") responseHeaders.append(key, value);
3821
+ let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;
3822
+ if (typeof arg === "object" && arg.headers) {
3823
+ responseHeaders ??= new Headers();
3824
+ for (const [key, value] of new Headers(arg.headers)) if (key === "set-cookie") responseHeaders.append(key, value);
3811
3825
  else responseHeaders.set(key, value);
3812
3826
  }
3813
- if (headers) for (const [k, v] of Object.entries(headers)) if (typeof v === "string") responseHeaders.set(k, v);
3814
- else {
3815
- responseHeaders.delete(k);
3816
- for (const v2 of v) responseHeaders.append(k, v2);
3827
+ if (headers) {
3828
+ if (!responseHeaders) {
3829
+ let count = 0;
3830
+ for (const k in headers) if (++count > 1 || typeof headers[k] !== "string") {
3831
+ responseHeaders = new Headers();
3832
+ break;
3833
+ }
3834
+ }
3835
+ if (responseHeaders) for (const k in headers) {
3836
+ const v = headers[k];
3837
+ if (typeof v === "string") responseHeaders.set(k, v);
3838
+ else {
3839
+ responseHeaders.delete(k);
3840
+ for (const v2 of v) responseHeaders.append(k, v2);
3841
+ }
3842
+ }
3817
3843
  }
3818
3844
  return createResponseInstance(data, {
3819
3845
  status: typeof arg === "number" ? arg : arg?.status ?? this.#status,
3820
- headers: responseHeaders
3846
+ headers: responseHeaders ?? headers
3821
3847
  });
3822
3848
  }
3823
3849
  newResponse = (...args) => this.#newResponse(...args);
@@ -3922,7 +3948,8 @@ var METHODS = [
3922
3948
  "put",
3923
3949
  "delete",
3924
3950
  "options",
3925
- "patch"
3951
+ "patch",
3952
+ "query"
3926
3953
  ];
3927
3954
  var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
3928
3955
  var UnsupportedPathError = class extends Error {};
@@ -3949,6 +3976,7 @@ var Hono$1 = class _Hono {
3949
3976
  delete;
3950
3977
  options;
3951
3978
  patch;
3979
+ query;
3952
3980
  all;
3953
3981
  on;
3954
3982
  use;
@@ -4127,11 +4155,13 @@ var Hono$1 = class _Hono {
4127
4155
  mount(path, applicationHandler, options) {
4128
4156
  let replaceRequest;
4129
4157
  let optionHandler;
4130
- if (options) if (typeof options === "function") optionHandler = options;
4131
- else {
4132
- optionHandler = options.optionHandler;
4133
- if (options.replaceRequest === false) replaceRequest = (request) => request;
4134
- else replaceRequest = options.replaceRequest;
4158
+ if (options) {
4159
+ if (typeof options === "function") optionHandler = options;
4160
+ else {
4161
+ optionHandler = options.optionHandler;
4162
+ if (options.replaceRequest === false) replaceRequest = (request) => request;
4163
+ else replaceRequest = options.replaceRequest;
4164
+ }
4135
4165
  }
4136
4166
  const getOptions = optionHandler ? (c) => {
4137
4167
  const options2 = optionHandler(c);
@@ -4215,8 +4245,8 @@ var Hono$1 = class _Hono {
4215
4245
  * @see {@link https://hono.dev/docs/api/hono#fetch}
4216
4246
  *
4217
4247
  * @param {Request} request - request Object of request
4218
- * @param {Env} Env - env Object
4219
- * @param {ExecutionContext} - context of execution
4248
+ * @param {Env} env - env Object
4249
+ * @param {ExecutionContext} executionCtx - context of execution
4220
4250
  * @returns {Response | Promise<Response>} response of request
4221
4251
  *
4222
4252
  */
@@ -4290,7 +4320,7 @@ var regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
4290
4320
  function compareKey(a, b) {
4291
4321
  if (a.length === 1) return b.length === 1 ? a < b ? -1 : 1 : -1;
4292
4322
  if (b.length === 1) return 1;
4293
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) return 1;
4323
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 1;
4294
4324
  else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) return -1;
4295
4325
  if (a === LABEL_REG_EXP_STR) return 1;
4296
4326
  else if (b === LABEL_REG_EXP_STR) return -1;
@@ -4300,60 +4330,63 @@ var Node$1 = class _Node {
4300
4330
  #index;
4301
4331
  #varIndex;
4302
4332
  #children = /* @__PURE__ */ Object.create(null);
4303
- insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
4304
- if (tokens.length === 0) {
4305
- if (this.#index !== void 0) throw PATH_ERROR;
4306
- if (pathErrorCheckOnly) return;
4307
- this.#index = index;
4308
- return;
4309
- }
4310
- const [token, ...restTokens] = tokens;
4311
- const pattern = token === "*" ? restTokens.length === 0 ? [
4312
- "",
4313
- "",
4314
- ONLY_WILDCARD_REG_EXP_STR
4315
- ] : [
4316
- "",
4317
- "",
4318
- LABEL_REG_EXP_STR
4319
- ] : token === "/*" ? [
4320
- "",
4321
- "",
4322
- TAIL_WILDCARD_REG_EXP_STR
4323
- ] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
4324
- let node;
4325
- if (pattern) {
4326
- const name = pattern[1];
4327
- let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
4328
- if (name && pattern[2]) {
4329
- if (regexpStr === ".*") throw PATH_ERROR;
4330
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
4331
- if (/\((?!\?:)/.test(regexpStr)) throw PATH_ERROR;
4332
- }
4333
- node = this.#children[regexpStr];
4334
- if (!node) {
4335
- if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) throw PATH_ERROR;
4336
- if (pathErrorCheckOnly) return;
4337
- node = this.#children[regexpStr] = new _Node();
4338
- if (name !== "") node.#varIndex = context.varIndex++;
4339
- }
4340
- if (!pathErrorCheckOnly && name !== "") paramMap.push([name, node.#varIndex]);
4341
- } else {
4342
- node = this.#children[token];
4343
- if (!node) {
4344
- if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) throw PATH_ERROR;
4345
- if (pathErrorCheckOnly) return;
4346
- node = this.#children[token] = new _Node();
4333
+ insert(tokens, index, paramMap, context, isStatic) {
4334
+ let node = this;
4335
+ for (let i = 0, len = tokens.length; i < len; i++) {
4336
+ const token = tokens[i];
4337
+ const pattern = token.length === 1 ? token === "*" ? i === len - 1 ? [
4338
+ "",
4339
+ "",
4340
+ ONLY_WILDCARD_REG_EXP_STR
4341
+ ] : [
4342
+ "",
4343
+ "",
4344
+ LABEL_REG_EXP_STR
4345
+ ] : null : token === "/*" ? [
4346
+ "",
4347
+ "",
4348
+ TAIL_WILDCARD_REG_EXP_STR
4349
+ ] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
4350
+ let nextNode;
4351
+ if (pattern) {
4352
+ const name = pattern[1];
4353
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
4354
+ if (name && pattern[2]) {
4355
+ if (regexpStr === ".*") throw PATH_ERROR;
4356
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
4357
+ if (/\((?!\?:)/.test(regexpStr)) throw PATH_ERROR;
4358
+ if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) throw PATH_ERROR;
4359
+ }
4360
+ nextNode = node.#children[regexpStr];
4361
+ if (!nextNode) {
4362
+ if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) {
4363
+ for (const k in node.#children) if ((regexpStr.length > 1 || k.length > 1) && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR) throw PATH_ERROR;
4364
+ }
4365
+ nextNode = node.#children[regexpStr] = new _Node();
4366
+ }
4367
+ if (name !== "") {
4368
+ nextNode.#varIndex ??= context.varIndex++;
4369
+ paramMap.push([name, nextNode.#varIndex]);
4370
+ }
4371
+ } else {
4372
+ nextNode = node.#children[token];
4373
+ if (!nextNode) {
4374
+ for (const k in node.#children) if (k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR) throw PATH_ERROR;
4375
+ nextNode = node.#children[token] = new _Node();
4376
+ }
4347
4377
  }
4378
+ node = nextNode;
4348
4379
  }
4349
- node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
4380
+ if (node.#index !== void 0) throw PATH_ERROR;
4381
+ node.#index = isStatic ? -1 : index;
4350
4382
  }
4351
4383
  buildRegExpStr() {
4352
4384
  const strList = Object.keys(this.#children).sort(compareKey).map((k) => {
4353
4385
  const c = this.#children[k];
4354
- return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
4355
- });
4356
- if (typeof this.#index === "number") strList.unshift(`#${this.#index}`);
4386
+ const childStr = c.buildRegExpStr();
4387
+ return childStr === "" ? "" : (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + childStr;
4388
+ }).filter(Boolean);
4389
+ if (typeof this.#index === "number" && this.#index !== -1) strList.unshift(`#${this.#index}`);
4357
4390
  if (strList.length === 0) return "";
4358
4391
  if (strList.length === 1) return strList[0];
4359
4392
  return "(?:" + strList.join("|") + ")";
@@ -4364,12 +4397,19 @@ var Node$1 = class _Node {
4364
4397
  var Trie = class {
4365
4398
  #context = { varIndex: 0 };
4366
4399
  #root = new Node$1();
4367
- insert(path, index, pathErrorCheckOnly) {
4400
+ #index = 0;
4401
+ paths = /* @__PURE__ */ Object.create(null);
4402
+ insert(path, isStatic) {
4403
+ if (isStatic) {
4404
+ this.#root.insert(path.split(""), 0, [], this.#context, true);
4405
+ return;
4406
+ }
4368
4407
  const paramAssoc = [];
4369
4408
  const groups = [];
4409
+ let markedPath = path;
4370
4410
  for (let i = 0;;) {
4371
4411
  let replaced = false;
4372
- path = path.replace(/\{[^}]+\}/g, (m) => {
4412
+ markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {
4373
4413
  const mark = `@\\${i}`;
4374
4414
  groups[i] = [mark, m];
4375
4415
  i++;
@@ -4378,7 +4418,7 @@ var Trie = class {
4378
4418
  });
4379
4419
  if (!replaced) break;
4380
4420
  }
4381
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
4421
+ const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
4382
4422
  for (let i = groups.length - 1; i >= 0; i--) {
4383
4423
  const [mark] = groups[i];
4384
4424
  for (let j = tokens.length - 1; j >= 0; j--) if (tokens[j].indexOf(mark) !== -1) {
@@ -4386,8 +4426,8 @@ var Trie = class {
4386
4426
  break;
4387
4427
  }
4388
4428
  }
4389
- this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
4390
- return paramAssoc;
4429
+ this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);
4430
+ this.paths[path] = [this.#index++, paramAssoc];
4391
4431
  }
4392
4432
  buildRegExp() {
4393
4433
  let regexp = this.#root.buildRegExpStr();
@@ -4419,11 +4459,6 @@ var Trie = class {
4419
4459
  };
4420
4460
  //#endregion
4421
4461
  //#region node_modules/hono/dist/router/reg-exp-router/router.js
4422
- var nullMatcher = [
4423
- /^$/,
4424
- [],
4425
- /* @__PURE__ */ Object.create(null)
4426
- ];
4427
4462
  var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
4428
4463
  function buildWildcardRegExp(path) {
4429
4464
  return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
@@ -4431,48 +4466,6 @@ function buildWildcardRegExp(path) {
4431
4466
  function clearWildcardRegExpCache() {
4432
4467
  wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
4433
4468
  }
4434
- function buildMatcherFromPreprocessedRoutes(routes) {
4435
- const trie = new Trie();
4436
- const handlerData = [];
4437
- if (routes.length === 0) return nullMatcher;
4438
- const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
4439
- const staticMap = /* @__PURE__ */ Object.create(null);
4440
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
4441
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
4442
- if (pathErrorCheckOnly) staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
4443
- else j++;
4444
- let paramAssoc;
4445
- try {
4446
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
4447
- } catch (e) {
4448
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
4449
- }
4450
- if (pathErrorCheckOnly) continue;
4451
- handlerData[j] = handlers.map(([h, paramCount]) => {
4452
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
4453
- paramCount -= 1;
4454
- for (; paramCount >= 0; paramCount--) {
4455
- const [key, value] = paramAssoc[paramCount];
4456
- paramIndexMap[key] = value;
4457
- }
4458
- return [h, paramIndexMap];
4459
- });
4460
- }
4461
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
4462
- for (let i = 0, len = handlerData.length; i < len; i++) for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
4463
- const map = handlerData[i][j]?.[1];
4464
- if (!map) continue;
4465
- const keys = Object.keys(map);
4466
- for (let k = 0, len3 = keys.length; k < len3; k++) map[keys[k]] = paramReplacementMap[map[keys[k]]];
4467
- }
4468
- const handlerMap = [];
4469
- for (const i in indexReplacementMap) handlerMap[i] = handlerData[indexReplacementMap[i]];
4470
- return [
4471
- regexp,
4472
- handlerMap,
4473
- staticMap
4474
- ];
4475
- }
4476
4469
  function findMiddleware(middleware, path) {
4477
4470
  if (!middleware) return;
4478
4471
  for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) if (buildWildcardRegExp(k).test(path)) return [...middleware[k]];
@@ -4481,28 +4474,43 @@ var RegExpRouter = class {
4481
4474
  name = "RegExpRouter";
4482
4475
  #middleware;
4483
4476
  #routes;
4477
+ #tries;
4484
4478
  constructor() {
4485
4479
  this.#middleware = { ["ALL"]: /* @__PURE__ */ Object.create(null) };
4486
4480
  this.#routes = { ["ALL"]: /* @__PURE__ */ Object.create(null) };
4481
+ this.#tries = { ["ALL"]: new Trie() };
4482
+ }
4483
+ #insertPath(method, path) {
4484
+ try {
4485
+ this.#tries[method].insert(path, !/\*|\/:/.test(path));
4486
+ } catch (e) {
4487
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
4488
+ }
4487
4489
  }
4488
4490
  add(method, path, handler) {
4489
4491
  const middleware = this.#middleware;
4490
4492
  const routes = this.#routes;
4491
4493
  if (!middleware || !routes) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
4492
- if (!middleware[method]) [middleware, routes].forEach((handlerMap) => {
4493
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
4494
- Object.keys(handlerMap["ALL"]).forEach((p) => {
4495
- handlerMap[method][p] = [...handlerMap["ALL"][p]];
4494
+ if (!middleware[method]) {
4495
+ this.#tries[method] = new Trie();
4496
+ [middleware, routes].forEach((handlerMap) => {
4497
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
4498
+ Object.keys(handlerMap["ALL"]).forEach((p) => {
4499
+ handlerMap[method][p] = [...handlerMap["ALL"][p]];
4500
+ this.#insertPath(method, p);
4501
+ });
4496
4502
  });
4497
- });
4503
+ }
4498
4504
  if (path === "/*") path = "*";
4499
4505
  const paramCount = (path.match(/\/:/g) || []).length;
4500
4506
  if (/\*$/.test(path)) {
4501
4507
  const re = buildWildcardRegExp(path);
4502
- if (method === "ALL") Object.keys(middleware).forEach((m) => {
4503
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware["ALL"], path) || [];
4508
+ Object.keys(middleware).forEach((m) => {
4509
+ if ((method === "ALL" || method === m) && !middleware[m][path]) {
4510
+ this.#insertPath(m, path);
4511
+ middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware["ALL"], path) || [];
4512
+ }
4504
4513
  });
4505
- else middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware["ALL"], path) || [];
4506
4514
  Object.keys(middleware).forEach((m) => {
4507
4515
  if (method === "ALL" || method === m) Object.keys(middleware[m]).forEach((p) => {
4508
4516
  re.test(p) && middleware[m][p].push([handler, paramCount]);
@@ -4518,7 +4526,10 @@ var RegExpRouter = class {
4518
4526
  const path2 = paths[i];
4519
4527
  Object.keys(routes).forEach((m) => {
4520
4528
  if (method === "ALL" || method === m) {
4521
- routes[m][path2] ||= [...findMiddleware(middleware[m], path2) || findMiddleware(middleware["ALL"], path2) || []];
4529
+ if (!routes[m][path2]) {
4530
+ this.#insertPath(m, path2);
4531
+ routes[m][path2] = [...findMiddleware(middleware[m], path2) || findMiddleware(middleware["ALL"], path2) || []];
4532
+ }
4522
4533
  routes[m][path2].push([handler, paramCount - len + i + 1]);
4523
4534
  }
4524
4535
  });
@@ -4530,22 +4541,50 @@ var RegExpRouter = class {
4530
4541
  Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
4531
4542
  matchers[method] ||= this.#buildMatcher(method);
4532
4543
  });
4533
- this.#middleware = this.#routes = void 0;
4544
+ this.#middleware = this.#routes = this.#tries = void 0;
4534
4545
  clearWildcardRegExpCache();
4535
4546
  return matchers;
4536
4547
  }
4537
4548
  #buildMatcher(method) {
4538
- const routes = [];
4539
- let hasOwnRoute = method === "ALL";
4540
- [this.#middleware, this.#routes].forEach((r) => {
4541
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
4542
- if (ownRoute.length !== 0) {
4543
- hasOwnRoute ||= true;
4544
- routes.push(...ownRoute);
4545
- } else if (method !== "ALL") routes.push(...Object.keys(r["ALL"]).map((path) => [path, r["ALL"][path]]));
4549
+ const middleware = this.#middleware[method];
4550
+ const routes = this.#routes[method];
4551
+ const trie = this.#tries[method];
4552
+ const staticMap = /* @__PURE__ */ Object.create(null);
4553
+ const handlerData = [];
4554
+ [middleware, routes].forEach((r) => {
4555
+ for (const path in r) {
4556
+ const handlers = r[path];
4557
+ const pathData = trie.paths[path];
4558
+ if (!pathData) {
4559
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
4560
+ continue;
4561
+ }
4562
+ const paramAssoc = pathData[1];
4563
+ handlerData[pathData[0]] = handlers.map(([h, paramCount]) => {
4564
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
4565
+ paramCount -= 1;
4566
+ for (; paramCount >= 0; paramCount--) {
4567
+ const [key, value] = paramAssoc[paramCount];
4568
+ paramIndexMap[key] = value;
4569
+ }
4570
+ return [h, paramIndexMap];
4571
+ });
4572
+ }
4546
4573
  });
4547
- if (!hasOwnRoute) return null;
4548
- else return buildMatcherFromPreprocessedRoutes(routes);
4574
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
4575
+ for (let i = 0, len = handlerData.length; i < len; i++) for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
4576
+ const map = handlerData[i][j]?.[1];
4577
+ if (!map) continue;
4578
+ const keys = Object.keys(map);
4579
+ for (let k = 0, len3 = keys.length; k < len3; k++) map[keys[k]] = paramReplacementMap[map[keys[k]]];
4580
+ }
4581
+ const handlerMap = [];
4582
+ for (const i in indexReplacementMap) handlerMap[i] = handlerData[indexReplacementMap[i]];
4583
+ return [
4584
+ regexp,
4585
+ handlerMap,
4586
+ staticMap
4587
+ ];
4549
4588
  }
4550
4589
  };
4551
4590
  //#endregion
@@ -4719,9 +4758,10 @@ var Node = class _Node {
4719
4758
  if (m) {
4720
4759
  params[name] = m[0];
4721
4760
  this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
4761
+ if (m[0].length === restPathString.length && child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, node.#params, params);
4722
4762
  if (hasChildren(child.#children)) {
4723
4763
  child.#params = params;
4724
- const componentCount = m[0].match(/\//)?.length ?? 0;
4764
+ const componentCount = m[0].match(/\//g)?.length ?? 0;
4725
4765
  (curNodesQueue[componentCount] ||= []).push(child);
4726
4766
  }
4727
4767
  continue;
@@ -4789,29 +4829,236 @@ var RequestError = class extends Error {
4789
4829
  this.name = "RequestError";
4790
4830
  }
4791
4831
  };
4792
- var toRequestError = (e) => {
4832
+ const nonJoinedHeaders = /* @__PURE__ */ new Set([
4833
+ "age",
4834
+ "authorization",
4835
+ "content-length",
4836
+ "content-type",
4837
+ "etag",
4838
+ "expires",
4839
+ "from",
4840
+ "host",
4841
+ "if-modified-since",
4842
+ "if-unmodified-since",
4843
+ "last-modified",
4844
+ "location",
4845
+ "max-forwards",
4846
+ "proxy-authorization",
4847
+ "referer",
4848
+ "retry-after",
4849
+ "server",
4850
+ "user-agent"
4851
+ ]);
4852
+ const validHeaderName = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;
4853
+ const isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;
4854
+ const normalizeHeaderValue = (value) => {
4855
+ if (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value;
4856
+ let start = 0;
4857
+ let end = value.length;
4858
+ while (start < end && isHttpWhitespace(value.charCodeAt(start))) start++;
4859
+ while (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--;
4860
+ return value.slice(start, end);
4861
+ };
4862
+ const forbiddenHeaderValue = /[\0\r\n]/;
4863
+ const GlobalHeaders = globalThis.Headers;
4864
+ const materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => {
4865
+ const headers = new HeadersCtor();
4866
+ for (let i = 0; i < rawHeaders.length; i += 2) {
4867
+ const name = rawHeaders[i];
4868
+ if (!name.startsWith(":")) headers.append(name, rawHeaders[i + 1]);
4869
+ }
4870
+ return headers;
4871
+ };
4872
+ var RequestHeaders = class {
4873
+ #incoming;
4874
+ #rawHeaders;
4875
+ #headers;
4876
+ #invalidValue;
4877
+ constructor(incoming) {
4878
+ this.#incoming = incoming;
4879
+ if (incoming instanceof Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice();
4880
+ }
4881
+ get #lazyRawHeaders() {
4882
+ return this.#rawHeaders ??= this.#incoming.rawHeaders.slice();
4883
+ }
4884
+ get #native() {
4885
+ if (!this.#headers) {
4886
+ this.#headers = materializeHeaders(this.#lazyRawHeaders);
4887
+ this.#rawHeaders = void 0;
4888
+ }
4889
+ return this.#headers;
4890
+ }
4891
+ #normalizedName(name) {
4892
+ if (typeof name !== "string") return;
4893
+ if (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`);
4894
+ return name.toLowerCase();
4895
+ }
4896
+ #lookupHttp1(lowerName) {
4897
+ const headers = this.#incoming instanceof Http2ServerRequest ? void 0 : this.#incoming.headers;
4898
+ if (!headers || nonJoinedHeaders.has(lowerName) || lowerName === "set-cookie" || lowerName === "__proto__") return;
4899
+ if (!Object.hasOwn(headers, lowerName)) return null;
4900
+ const rawValue = headers[lowerName];
4901
+ if (typeof rawValue === "string") {
4902
+ const value = normalizeHeaderValue(rawValue);
4903
+ return forbiddenHeaderValue.test(value) ? void 0 : value;
4904
+ }
4905
+ }
4906
+ #lookup(rawHeaders, lowerName) {
4907
+ const separator = lowerName === "cookie" ? "; " : ", ";
4908
+ let value = null;
4909
+ for (let i = 0; i < rawHeaders.length; i += 2) {
4910
+ const rawName = rawHeaders[i];
4911
+ if (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) {
4912
+ const rawValue = normalizeHeaderValue(rawHeaders[i + 1]);
4913
+ if (forbiddenHeaderValue.test(rawValue)) {
4914
+ this.#invalidValue = true;
4915
+ return;
4916
+ }
4917
+ value = value === null ? rawValue : value + separator + rawValue;
4918
+ }
4919
+ }
4920
+ return value;
4921
+ }
4922
+ append(name, value) {
4923
+ this.#native.append(name, value);
4924
+ }
4925
+ delete(name) {
4926
+ this.#native.delete(name);
4927
+ }
4928
+ get(name) {
4929
+ const lowerName = this.#normalizedName(name);
4930
+ if (lowerName && !this.#headers && !this.#invalidValue) {
4931
+ const http1Value = this.#lookupHttp1(lowerName);
4932
+ if (http1Value !== void 0) return http1Value;
4933
+ const value = this.#lookup(this.#lazyRawHeaders, lowerName);
4934
+ if (value !== void 0) return value;
4935
+ }
4936
+ return this.#native.get(name);
4937
+ }
4938
+ has(name) {
4939
+ const lowerName = this.#normalizedName(name);
4940
+ if (lowerName && !this.#headers && !this.#invalidValue) {
4941
+ const http1Value = this.#lookupHttp1(lowerName);
4942
+ if (http1Value !== void 0) return http1Value !== null;
4943
+ const value = this.#lookup(this.#lazyRawHeaders, lowerName);
4944
+ if (value !== void 0) return value !== null;
4945
+ }
4946
+ return this.#native.has(name);
4947
+ }
4948
+ set(name, value) {
4949
+ this.#native.set(name, value);
4950
+ }
4951
+ getSetCookie() {
4952
+ return this.#native.getSetCookie();
4953
+ }
4954
+ keys() {
4955
+ return this.#native.keys();
4956
+ }
4957
+ values() {
4958
+ return this.#native.values();
4959
+ }
4960
+ entries() {
4961
+ return this.#native.entries();
4962
+ }
4963
+ forEach(callback, thisArg) {
4964
+ this.#native.forEach((value, key) => {
4965
+ callback.call(thisArg, value, key, this);
4966
+ });
4967
+ }
4968
+ [Symbol.iterator]() {
4969
+ return this.entries();
4970
+ }
4971
+ };
4972
+ Object.defineProperty(RequestHeaders.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
4973
+ return `Headers (lightweight) ${inspectFn(Object.fromEntries(this), {
4974
+ ...options,
4975
+ depth: depth == null ? null : depth - 1
4976
+ })}`;
4977
+ } });
4978
+ Object.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);
4979
+ const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);
4980
+ const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
4981
+ const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
4982
+ const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
4983
+ const buildUrl = (scheme, host, incomingUrl) => {
4984
+ const url = `${scheme}://${host}${incomingUrl}`;
4985
+ if (!reValidHost.test(host)) {
4986
+ const urlObj = new URL(url);
4987
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
4988
+ return urlObj.href;
4989
+ } else if (incomingUrl.length === 0) return url + "/";
4990
+ else {
4991
+ if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
4992
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
4993
+ return url;
4994
+ }
4995
+ };
4996
+ const toRequestError = (e) => {
4793
4997
  if (e instanceof RequestError) return e;
4794
4998
  return new RequestError(e.message, { cause: e });
4795
4999
  };
4796
- var GlobalRequest = global.Request;
5000
+ const GlobalRequest = global.Request;
4797
5001
  var Request$1 = class extends GlobalRequest {
4798
5002
  constructor(input, options) {
4799
- if (typeof input === "object" && getRequestCache in input) input = input[getRequestCache]();
4800
- if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
5003
+ if (typeof input === "object" && getRequestCache in input) {
5004
+ const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
5005
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
5006
+ input = input[getRequestCache]();
5007
+ }
5008
+ if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
4801
5009
  super(input, options);
4802
5010
  }
4803
5011
  };
4804
- var newHeadersFromIncoming = (incoming) => {
4805
- const headerRecord = [];
4806
- const rawHeaders = incoming.rawHeaders;
4807
- for (let i = 0; i < rawHeaders.length; i += 2) {
4808
- const { [i]: key, [i + 1]: value } = rawHeaders;
4809
- if (key.charCodeAt(0) !== 58) headerRecord.push([key, value]);
5012
+ const wrapBodyStream = Symbol("wrapBodyStream");
5013
+ const byteExactEncodings = /* @__PURE__ */ new Set([
5014
+ "latin1",
5015
+ "binary",
5016
+ "hex",
5017
+ "base64",
5018
+ "base64url"
5019
+ ]);
5020
+ const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
5021
+ const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
5022
+ const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
5023
+ const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
5024
+ const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
5025
+ const recordBodyBufferedBeforeDisconnect = (incoming) => {
5026
+ if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
5027
+ const incomingWithRecovery = incoming;
5028
+ incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
5029
+ };
5030
+ const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
5031
+ if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
5032
+ const incomingWithRecovery = incoming;
5033
+ if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
5034
+ let result;
5035
+ const errored = incoming.errored;
5036
+ if (errored && errored.code !== "ECONNRESET") result = errored;
5037
+ else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
5038
+ else {
5039
+ const bodyChunks = chunks ?? [];
5040
+ const chunk = incoming.read();
5041
+ if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
5042
+ const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
5043
+ result = buffer;
5044
+ const contentLength = incoming.headers["content-length"];
5045
+ if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
5046
+ const expectedLength = Number(contentLength);
5047
+ if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
5048
+ }
4810
5049
  }
4811
- return new Headers(headerRecord);
5050
+ incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
5051
+ return result;
4812
5052
  };
4813
- var wrapBodyStream = Symbol("wrapBodyStream");
4814
- var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
5053
+ const enqueueBufferedBody = (controller, buffered) => {
5054
+ if (buffered instanceof Error) {
5055
+ controller.error(buffered);
5056
+ return;
5057
+ }
5058
+ if (buffered.length > 0) controller.enqueue(buffered);
5059
+ controller.close();
5060
+ };
5061
+ const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
4815
5062
  const init = {
4816
5063
  method,
4817
5064
  headers,
@@ -4833,6 +5080,13 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
4833
5080
  let reader;
4834
5081
  init.body = new ReadableStream({ async pull(controller) {
4835
5082
  try {
5083
+ if (!reader) {
5084
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
5085
+ if (buffered !== void 0) {
5086
+ enqueueBufferedBody(controller, buffered);
5087
+ return;
5088
+ }
5089
+ }
4836
5090
  reader ||= Readable.toWeb(incoming).getReader();
4837
5091
  const { done, value } = await reader.read();
4838
5092
  if (done) controller.close();
@@ -4841,18 +5095,192 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
4841
5095
  controller.error(error);
4842
5096
  }
4843
5097
  } });
4844
- } else init.body = Readable.toWeb(incoming);
5098
+ } else {
5099
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
5100
+ if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
5101
+ enqueueBufferedBody(controller, buffered);
5102
+ } });
5103
+ else init.body = Readable.toWeb(incoming);
5104
+ }
4845
5105
  return new Request$1(url, init);
4846
5106
  };
4847
- var getRequestCache = Symbol("getRequestCache");
4848
- var requestCache = Symbol("requestCache");
4849
- var incomingKey = Symbol("incomingKey");
4850
- var urlKey = Symbol("urlKey");
4851
- var headersKey = Symbol("headersKey");
4852
- var abortControllerKey = Symbol("abortControllerKey");
4853
- var requestPrototype = {
5107
+ const getRequestCache = Symbol("getRequestCache");
5108
+ const requestCache = Symbol("requestCache");
5109
+ const incomingKey = Symbol("incomingKey");
5110
+ const urlKey = Symbol("urlKey");
5111
+ const methodKey = Symbol("methodKey");
5112
+ const headersKey = Symbol("headersKey");
5113
+ const abortControllerKey = Symbol("abortControllerKey");
5114
+ const getAbortController = Symbol("getAbortController");
5115
+ const abortRequest = Symbol("abortRequest");
5116
+ const bodyBufferKey = Symbol("bodyBuffer");
5117
+ const bodyReadPromiseKey = Symbol("bodyReadPromise");
5118
+ const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
5119
+ const bodyLockReaderKey = Symbol("bodyLockReader");
5120
+ const abortReasonKey = Symbol("abortReason");
5121
+ const newBodyUnusableError = () => {
5122
+ return /* @__PURE__ */ new TypeError("Body is unusable");
5123
+ };
5124
+ const rejectBodyUnusable = () => {
5125
+ return Promise.reject(newBodyUnusableError());
5126
+ };
5127
+ const textDecoder = new TextDecoder();
5128
+ const consumeBodyDirectOnce = (request) => {
5129
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
5130
+ request[bodyConsumedDirectlyKey] = true;
5131
+ };
5132
+ const toArrayBuffer = (buf) => {
5133
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
5134
+ };
5135
+ const contentType = (request) => {
5136
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
5137
+ };
5138
+ const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
5139
+ const normalizeIncomingMethod = (method) => {
5140
+ if (typeof method !== "string" || method.length === 0) return "GET";
5141
+ switch (method) {
5142
+ case "DELETE":
5143
+ case "GET":
5144
+ case "HEAD":
5145
+ case "OPTIONS":
5146
+ case "PATCH":
5147
+ case "POST":
5148
+ case "PUT":
5149
+ case "QUERY": return method;
5150
+ }
5151
+ const upper = method.toUpperCase();
5152
+ switch (upper) {
5153
+ case "DELETE":
5154
+ case "GET":
5155
+ case "HEAD":
5156
+ case "OPTIONS":
5157
+ case "POST":
5158
+ case "PUT": return upper;
5159
+ default: return method;
5160
+ }
5161
+ };
5162
+ const validateDirectReadMethod = (method) => {
5163
+ if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
5164
+ const normalized = method.toUpperCase();
5165
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
5166
+ };
5167
+ const readBodyWithFastPath = (request, method, fromBuffer) => {
5168
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
5169
+ const methodName = request.method;
5170
+ if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
5171
+ const methodValidationError = validateDirectReadMethod(methodName);
5172
+ if (methodValidationError) return Promise.reject(methodValidationError);
5173
+ if (request[requestCache]) {
5174
+ if (methodName !== "TRACE") return request[requestCache][method]();
5175
+ }
5176
+ const alreadyUsedError = consumeBodyDirectOnce(request);
5177
+ if (alreadyUsedError) return alreadyUsedError;
5178
+ const raw = readRawBodyIfAvailable(request);
5179
+ if (raw) {
5180
+ const result = Promise.resolve(fromBuffer(raw, request));
5181
+ request[bodyBufferKey] = void 0;
5182
+ return result;
5183
+ }
5184
+ return readBodyDirect(request).then((buf) => {
5185
+ const result = fromBuffer(buf, request);
5186
+ request[bodyBufferKey] = void 0;
5187
+ return result;
5188
+ });
5189
+ };
5190
+ const readRawBodyIfAvailable = (request) => {
5191
+ const incoming = request[incomingKey];
5192
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
5193
+ };
5194
+ const normalizeAbortError = (request, incoming) => {
5195
+ if (incoming.errored) return incoming.errored;
5196
+ const reason = request[abortReasonKey];
5197
+ if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
5198
+ return /* @__PURE__ */ new Error("Client connection prematurely closed.");
5199
+ };
5200
+ const readBodyDirect = (request) => {
5201
+ if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
5202
+ if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
5203
+ const incoming = request[incomingKey];
5204
+ if (incoming.readableDidRead) return rejectBodyUnusable();
5205
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
5206
+ if (buffered !== void 0) {
5207
+ if (buffered instanceof Error) return Promise.reject(buffered);
5208
+ request[bodyBufferKey] = buffered;
5209
+ return Promise.resolve(buffered);
5210
+ }
5211
+ const promise = new Promise((resolve, reject) => {
5212
+ const chunks = [];
5213
+ let settled = false;
5214
+ const finish = (callback) => {
5215
+ if (settled) return;
5216
+ settled = true;
5217
+ cleanup();
5218
+ callback();
5219
+ };
5220
+ const recoverCompleteBodyAfterDisconnect = (error) => {
5221
+ const streamError = incoming.errored ?? error;
5222
+ if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
5223
+ finish(() => {
5224
+ const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
5225
+ if (recovered instanceof Error) reject(recovered);
5226
+ else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
5227
+ else {
5228
+ request[bodyBufferKey] = recovered;
5229
+ resolve(recovered);
5230
+ }
5231
+ });
5232
+ return true;
5233
+ };
5234
+ const onData = (chunk) => {
5235
+ chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
5236
+ };
5237
+ const onEnd = () => {
5238
+ finish(() => {
5239
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
5240
+ request[bodyBufferKey] = buffer;
5241
+ resolve(buffer);
5242
+ });
5243
+ };
5244
+ const onError = (error) => {
5245
+ if (recoverCompleteBodyAfterDisconnect(error)) return;
5246
+ finish(() => {
5247
+ reject(error);
5248
+ });
5249
+ };
5250
+ const onClose = () => {
5251
+ if (incoming.readableEnded) {
5252
+ onEnd();
5253
+ return;
5254
+ }
5255
+ if (recoverCompleteBodyAfterDisconnect()) return;
5256
+ finish(() => {
5257
+ reject(normalizeAbortError(request, incoming));
5258
+ });
5259
+ };
5260
+ const cleanup = () => {
5261
+ incoming.off("data", onData);
5262
+ incoming.off("end", onEnd);
5263
+ incoming.off("error", onError);
5264
+ incoming.off("close", onClose);
5265
+ request[bodyReadPromiseKey] = void 0;
5266
+ };
5267
+ incoming.on("data", onData);
5268
+ incoming.on("end", onEnd);
5269
+ incoming.on("error", onError);
5270
+ incoming.on("close", onClose);
5271
+ queueMicrotask(() => {
5272
+ if (settled) return;
5273
+ if (incoming.readableEnded) onEnd();
5274
+ else if (incoming.errored) onError(incoming.errored);
5275
+ else if (incoming.destroyed) onClose();
5276
+ });
5277
+ });
5278
+ request[bodyReadPromiseKey] = promise;
5279
+ return promise;
5280
+ };
5281
+ const requestPrototype = {
4854
5282
  get method() {
4855
- return this[incomingKey].method || "GET";
5283
+ return this[methodKey];
4856
5284
  },
4857
5285
  get url() {
4858
5286
  return this[urlKey];
@@ -4860,18 +5288,57 @@ var requestPrototype = {
4860
5288
  get headers() {
4861
5289
  return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
4862
5290
  },
4863
- [Symbol("getAbortController")]() {
4864
- this[getRequestCache]();
5291
+ [abortRequest](reason) {
5292
+ if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
5293
+ const abortController = this[abortControllerKey];
5294
+ if (abortController && !abortController.signal.aborted) abortController.abort(reason);
5295
+ },
5296
+ [getAbortController]() {
5297
+ this[abortControllerKey] ||= new AbortController();
5298
+ if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
4865
5299
  return this[abortControllerKey];
4866
5300
  },
4867
5301
  [getRequestCache]() {
4868
- this[abortControllerKey] ||= new AbortController();
4869
- return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
5302
+ const abortController = this[getAbortController]();
5303
+ if (this[requestCache]) return this[requestCache];
5304
+ const method = this.method;
5305
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
5306
+ this[bodyBufferKey] = void 0;
5307
+ const init = {
5308
+ method: method === "TRACE" ? "GET" : method,
5309
+ headers: this.headers,
5310
+ signal: abortController.signal
5311
+ };
5312
+ if (method !== "TRACE") {
5313
+ init.body = new ReadableStream({ start(c) {
5314
+ c.close();
5315
+ } });
5316
+ init.duplex = "half";
5317
+ }
5318
+ const req = new Request$1(this[urlKey], init);
5319
+ if (method === "TRACE") Object.defineProperty(req, "method", { get() {
5320
+ return "TRACE";
5321
+ } });
5322
+ return this[requestCache] = req;
5323
+ }
5324
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
5325
+ },
5326
+ get body() {
5327
+ if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
5328
+ const request = this[getRequestCache]();
5329
+ if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
5330
+ return request.body;
5331
+ },
5332
+ get bodyUsed() {
5333
+ if (this[bodyConsumedDirectlyKey]) return true;
5334
+ if (this[requestCache]) return this[requestCache].bodyUsed;
5335
+ return false;
4870
5336
  }
4871
5337
  };
5338
+ Object.defineProperty(requestPrototype, "signal", { get() {
5339
+ return this[getAbortController]().signal;
5340
+ } });
4872
5341
  [
4873
- "body",
4874
- "bodyUsed",
4875
5342
  "cache",
4876
5343
  "credentials",
4877
5344
  "destination",
@@ -4880,25 +5347,37 @@ var requestPrototype = {
4880
5347
  "redirect",
4881
5348
  "referrer",
4882
5349
  "referrerPolicy",
4883
- "signal",
4884
5350
  "keepalive"
4885
5351
  ].forEach((k) => {
4886
5352
  Object.defineProperty(requestPrototype, k, { get() {
4887
5353
  return this[getRequestCache]()[k];
4888
5354
  } });
4889
5355
  });
4890
- [
4891
- "arrayBuffer",
4892
- "blob",
4893
- "clone",
4894
- "formData",
4895
- "json",
4896
- "text"
4897
- ].forEach((k) => {
5356
+ ["clone", "formData"].forEach((k) => {
4898
5357
  Object.defineProperty(requestPrototype, k, { value: function() {
5358
+ if (this[bodyConsumedDirectlyKey]) {
5359
+ if (k === "clone") throw newBodyUnusableError();
5360
+ return rejectBodyUnusable();
5361
+ }
4899
5362
  return this[getRequestCache]()[k]();
4900
5363
  } });
4901
5364
  });
5365
+ Object.defineProperty(requestPrototype, "text", { value: function() {
5366
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
5367
+ } });
5368
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
5369
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
5370
+ } });
5371
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
5372
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
5373
+ const type = contentType(request);
5374
+ return new Response(buf, type ? { headers: { "content-type": type } } : void 0).blob();
5375
+ });
5376
+ } });
5377
+ Object.defineProperty(requestPrototype, "json", { value: function() {
5378
+ if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
5379
+ return this.text().then(JSON.parse);
5380
+ } });
4902
5381
  Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
4903
5382
  return `Request (lightweight) ${inspectFn({
4904
5383
  method: this.method,
@@ -4911,9 +5390,10 @@ Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom")
4911
5390
  })}`;
4912
5391
  } });
4913
5392
  Object.setPrototypeOf(requestPrototype, Request$1.prototype);
4914
- var newRequest = (incoming, defaultHostname) => {
5393
+ const newRequest = (incoming, defaultHostname) => {
4915
5394
  const req = Object.create(requestPrototype);
4916
5395
  req[incomingKey] = incoming;
5396
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
4917
5397
  const incomingUrl = incoming.url || "";
4918
5398
  if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
4919
5399
  if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
@@ -4931,46 +5411,55 @@ var newRequest = (incoming, defaultHostname) => {
4931
5411
  scheme = incoming.scheme;
4932
5412
  if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
4933
5413
  } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
4934
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
4935
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) throw new RequestError("Invalid host header");
4936
- req[urlKey] = url.href;
5414
+ try {
5415
+ req[urlKey] = buildUrl(scheme, host, incomingUrl);
5416
+ } catch (e) {
5417
+ if (e instanceof RequestError) throw e;
5418
+ else throw new RequestError("Invalid URL", { cause: e });
5419
+ }
4937
5420
  return req;
4938
5421
  };
4939
- var responseCache = Symbol("responseCache");
4940
- var getResponseCache = Symbol("getResponseCache");
4941
- var cacheKey = Symbol("cache");
4942
- var GlobalResponse = global.Response;
4943
- var Response2 = class _Response {
5422
+ const defaultContentType = "text/plain; charset=UTF-8";
5423
+ const responseCache = Symbol("responseCache");
5424
+ const getResponseCache = Symbol("getResponseCache");
5425
+ const cacheKey = Symbol("cache");
5426
+ const GlobalResponse = global.Response;
5427
+ var Response$1 = class Response$1 {
4944
5428
  #body;
4945
5429
  #init;
4946
5430
  [getResponseCache]() {
5431
+ const cache = this[cacheKey];
5432
+ const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
4947
5433
  delete this[cacheKey];
4948
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
5434
+ return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
5435
+ status: this.#init?.status,
5436
+ statusText: this.#init?.statusText,
5437
+ headers: liveHeaders
5438
+ } : this.#init);
4949
5439
  }
4950
5440
  constructor(body, init) {
4951
5441
  let headers;
4952
5442
  this.#body = body;
4953
- if (init instanceof _Response) {
5443
+ if (init instanceof GlobalResponse) {
4954
5444
  const cachedGlobalResponse = init[responseCache];
4955
5445
  if (cachedGlobalResponse) {
4956
5446
  this.#init = cachedGlobalResponse;
4957
5447
  this[getResponseCache]();
4958
5448
  return;
4959
- } else {
4960
- this.#init = init.#init;
4961
- headers = new Headers(init.#init.headers);
4962
5449
  }
5450
+ this.#init = init instanceof Response$1 ? init.#init : init;
5451
+ headers = new Headers(init.headers);
4963
5452
  } else this.#init = init;
4964
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
5453
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
4965
5454
  init?.status || 200,
4966
- body,
5455
+ body ?? null,
4967
5456
  headers || init?.headers
4968
5457
  ];
4969
5458
  }
4970
5459
  get headers() {
4971
5460
  const cache = this[cacheKey];
4972
5461
  if (cache) {
4973
- if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
5462
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
4974
5463
  return cache[2];
4975
5464
  }
4976
5465
  return this[getResponseCache]().headers;
@@ -4992,7 +5481,7 @@ var Response2 = class _Response {
4992
5481
  "type",
4993
5482
  "url"
4994
5483
  ].forEach((k) => {
4995
- Object.defineProperty(Response2.prototype, k, { get() {
5484
+ Object.defineProperty(Response$1.prototype, k, { get() {
4996
5485
  return this[getResponseCache]()[k];
4997
5486
  } });
4998
5487
  });
@@ -5004,11 +5493,11 @@ var Response2 = class _Response {
5004
5493
  "json",
5005
5494
  "text"
5006
5495
  ].forEach((k) => {
5007
- Object.defineProperty(Response2.prototype, k, { value: function() {
5496
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
5008
5497
  return this[getResponseCache]()[k]();
5009
5498
  } });
5010
5499
  });
5011
- Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
5500
+ Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
5012
5501
  return `Response (lightweight) ${inspectFn({
5013
5502
  status: this.status,
5014
5503
  headers: this.headers,
@@ -5019,8 +5508,51 @@ Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custo
5019
5508
  depth: depth == null ? null : depth - 1
5020
5509
  })}`;
5021
5510
  } });
5022
- Object.setPrototypeOf(Response2, GlobalResponse);
5023
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
5511
+ Object.setPrototypeOf(Response$1, GlobalResponse);
5512
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
5513
+ const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
5514
+ const parseRedirectUrl = (url) => {
5515
+ if (url instanceof URL) return url.href;
5516
+ if (validRedirectUrl.test(url)) return url;
5517
+ return new URL(url).href;
5518
+ };
5519
+ const validRedirectStatuses = /* @__PURE__ */ new Set([
5520
+ 301,
5521
+ 302,
5522
+ 303,
5523
+ 307,
5524
+ 308
5525
+ ]);
5526
+ Object.defineProperty(Response$1, "redirect", {
5527
+ value: function redirect(url, status = 302) {
5528
+ if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
5529
+ return new Response$1(null, {
5530
+ status,
5531
+ headers: { location: parseRedirectUrl(url) }
5532
+ });
5533
+ },
5534
+ writable: true,
5535
+ configurable: true
5536
+ });
5537
+ Object.defineProperty(Response$1, "json", {
5538
+ value: function json(data, init) {
5539
+ const body = JSON.stringify(data);
5540
+ if (body === void 0) throw new TypeError("The data is not JSON serializable");
5541
+ const initHeaders = init?.headers;
5542
+ let headers;
5543
+ if (initHeaders) {
5544
+ headers = new Headers(initHeaders);
5545
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
5546
+ } else headers = { "content-type": "application/json" };
5547
+ return new Response$1(body, {
5548
+ status: init?.status ?? 200,
5549
+ statusText: init?.statusText,
5550
+ headers
5551
+ });
5552
+ },
5553
+ writable: true,
5554
+ configurable: true
5555
+ });
5024
5556
  async function readWithoutBlocking(readPromise) {
5025
5557
  return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
5026
5558
  }
@@ -5056,23 +5588,23 @@ function writeFromReadableStream(stream, writable) {
5056
5588
  else if (writable.destroyed) return;
5057
5589
  return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
5058
5590
  }
5059
- var buildOutgoingHttpHeaders = (headers) => {
5591
+ const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
5060
5592
  const res = {};
5061
5593
  if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
5062
- const cookies = [];
5063
- for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
5064
- else res[k] = v;
5065
- if (cookies.length > 0) res["set-cookie"] = cookies;
5066
- res["content-type"] ??= "text/plain; charset=UTF-8";
5594
+ if (headers.has("set-cookie")) {
5595
+ const cookies = [];
5596
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
5597
+ else res[k] = v;
5598
+ if (cookies.length > 0) res["set-cookie"] = cookies;
5599
+ } else for (const [k, v] of headers) res[k] = v;
5600
+ if (defaultContentType) res["content-type"] ??= defaultContentType;
5067
5601
  return res;
5068
5602
  };
5069
- var X_ALREADY_SENT = "x-hono-already-sent";
5070
- if (typeof global.crypto === "undefined") global.crypto = crypto$1;
5071
- var outgoingEnded = Symbol("outgoingEnded");
5072
- var incomingDraining = Symbol("incomingDraining");
5073
- var DRAIN_TIMEOUT_MS = 500;
5074
- var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
5075
- var drainIncoming = (incoming) => {
5603
+ const outgoingEnded = Symbol("outgoingEnded");
5604
+ const incomingDraining = Symbol("incomingDraining");
5605
+ const DRAIN_TIMEOUT_MS = 500;
5606
+ const MAX_DRAIN_BYTES = 67108864;
5607
+ const drainIncoming = (incoming) => {
5076
5608
  const incomingWithDrainState = incoming;
5077
5609
  if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
5078
5610
  incomingWithDrainState[incomingDraining] = true;
@@ -5092,7 +5624,10 @@ var drainIncoming = (incoming) => {
5092
5624
  const forceClose = () => {
5093
5625
  cleanup();
5094
5626
  const socket = incoming.socket;
5095
- if (socket && !socket.destroyed) socket.destroySoon();
5627
+ if (socket && !socket.destroyed) {
5628
+ if (typeof socket.destroySoon === "function") socket.destroySoon();
5629
+ else if (typeof socket.destroy === "function") socket.destroy();
5630
+ }
5096
5631
  };
5097
5632
  const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
5098
5633
  timer.unref?.();
@@ -5105,9 +5640,28 @@ var drainIncoming = (incoming) => {
5105
5640
  incoming.on("error", cleanup);
5106
5641
  incoming.resume();
5107
5642
  };
5108
- var handleRequestError = () => new Response(null, { status: 400 });
5109
- var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
5110
- var handleResponseError = (e, outgoing) => {
5643
+ const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
5644
+ if (incoming.errored) {
5645
+ recordBodyBufferedBeforeDisconnect(incoming);
5646
+ req[abortRequest](incoming.errored.toString());
5647
+ } else if (!outgoing.writableFinished) {
5648
+ recordBodyBufferedBeforeDisconnect(incoming);
5649
+ req[abortRequest]("Client connection prematurely closed.");
5650
+ }
5651
+ if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
5652
+ if (!incoming.readableEnded) setTimeout(() => {
5653
+ drainIncoming(incoming);
5654
+ });
5655
+ });
5656
+ };
5657
+ const isImmediateCacheableResponse = (res) => {
5658
+ if (!(cacheKey in res)) return false;
5659
+ const body = res[cacheKey][1];
5660
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
5661
+ };
5662
+ const handleRequestError = () => new Response(null, { status: 400 });
5663
+ const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
5664
+ const handleResponseError = (e, outgoing) => {
5111
5665
  const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
5112
5666
  if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
5113
5667
  else {
@@ -5117,20 +5671,49 @@ var handleResponseError = (e, outgoing) => {
5117
5671
  outgoing.destroy(err);
5118
5672
  }
5119
5673
  };
5120
- var flushHeaders = (outgoing) => {
5674
+ const flushHeaders = (outgoing) => {
5121
5675
  if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
5122
5676
  };
5123
- var responseViaCache = async (res, outgoing) => {
5677
+ const responseViaCache = async (res, outgoing) => {
5124
5678
  let [status, body, header] = res[cacheKey];
5679
+ if (!header) {
5680
+ if (body === null) {
5681
+ outgoing.writeHead(status);
5682
+ outgoing.end();
5683
+ } else if (typeof body === "string") {
5684
+ outgoing.writeHead(status, {
5685
+ "Content-Type": defaultContentType,
5686
+ "Content-Length": Buffer.byteLength(body)
5687
+ });
5688
+ outgoing.end(body);
5689
+ } else if (body instanceof Uint8Array) {
5690
+ outgoing.writeHead(status, {
5691
+ "Content-Type": defaultContentType,
5692
+ "Content-Length": body.byteLength
5693
+ });
5694
+ outgoing.end(body);
5695
+ } else if (body instanceof Blob) {
5696
+ outgoing.writeHead(status, {
5697
+ "Content-Type": defaultContentType,
5698
+ "Content-Length": body.size
5699
+ });
5700
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
5701
+ } else {
5702
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
5703
+ flushHeaders(outgoing);
5704
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
5705
+ }
5706
+ outgoing[outgoingEnded]?.();
5707
+ return;
5708
+ }
5125
5709
  let hasContentLength = false;
5126
- if (!header) header = { "content-type": "text/plain; charset=UTF-8" };
5127
- else if (header instanceof Headers) {
5710
+ if (header instanceof Headers) {
5128
5711
  hasContentLength = header.has("content-length");
5129
- header = buildOutgoingHttpHeaders(header);
5712
+ header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
5130
5713
  } else if (Array.isArray(header)) {
5131
5714
  const headerObj = new Headers(header);
5132
5715
  hasContentLength = headerObj.has("content-length");
5133
- header = buildOutgoingHttpHeaders(headerObj);
5716
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
5134
5717
  } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
5135
5718
  hasContentLength = true;
5136
5719
  break;
@@ -5141,7 +5724,8 @@ var responseViaCache = async (res, outgoing) => {
5141
5724
  else if (body instanceof Blob) header["Content-Length"] = body.size;
5142
5725
  }
5143
5726
  outgoing.writeHead(status, header);
5144
- if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
5727
+ if (body == null) outgoing.end();
5728
+ else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
5145
5729
  else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
5146
5730
  else {
5147
5731
  flushHeaders(outgoing);
@@ -5149,8 +5733,8 @@ var responseViaCache = async (res, outgoing) => {
5149
5733
  }
5150
5734
  outgoing[outgoingEnded]?.();
5151
5735
  };
5152
- var isPromise = (res) => typeof res.then === "function";
5153
- var responseViaResponseObject = async (res, outgoing, options = {}) => {
5736
+ const isPromise = (res) => typeof res.then === "function";
5737
+ const responseViaResponseObject = async (res, outgoing, options = {}) => {
5154
5738
  if (isPromise(res)) if (options.errorHandler) try {
5155
5739
  res = await res;
5156
5740
  } catch (err) {
@@ -5160,7 +5744,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
5160
5744
  }
5161
5745
  else res = await res.catch(handleFetchError);
5162
5746
  if (cacheKey in res) return responseViaCache(res, outgoing);
5163
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
5747
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
5164
5748
  if (res.body) {
5165
5749
  const reader = res.body.getReader();
5166
5750
  const values = [];
@@ -5200,57 +5784,55 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
5200
5784
  if (values.length === 0) flushHeaders(outgoing);
5201
5785
  await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
5202
5786
  }
5203
- } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
5787
+ } else if (resHeaderRecord["x-hono-already-sent"]) {} else {
5204
5788
  outgoing.writeHead(res.status, resHeaderRecord);
5205
5789
  outgoing.end();
5206
5790
  }
5207
5791
  outgoing[outgoingEnded]?.();
5208
5792
  };
5209
- var getRequestListener = (fetchCallback, options = {}) => {
5793
+ const getRequestListener = (fetchCallback, options = {}) => {
5210
5794
  const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
5211
5795
  if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
5212
5796
  Object.defineProperty(global, "Request", { value: Request$1 });
5213
- Object.defineProperty(global, "Response", { value: Response2 });
5797
+ Object.defineProperty(global, "Response", { value: Response$1 });
5214
5798
  }
5215
5799
  return async (incoming, outgoing) => {
5216
5800
  let res, req;
5801
+ let needsBodyCleanup = false;
5802
+ let closeHandlerAttached = false;
5803
+ const ensureCloseHandler = () => {
5804
+ if (!req || closeHandlerAttached) return;
5805
+ closeHandlerAttached = true;
5806
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
5807
+ };
5217
5808
  try {
5218
5809
  req = newRequest(incoming, options.hostname);
5219
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
5220
- if (!incomingEnded) {
5810
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
5811
+ if (needsBodyCleanup) {
5221
5812
  incoming[wrapBodyStream] = true;
5222
- incoming.on("end", () => {
5223
- incomingEnded = true;
5224
- });
5225
5813
  if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
5226
- if (!incomingEnded) setTimeout(() => {
5227
- if (!incomingEnded) setTimeout(() => {
5228
- drainIncoming(incoming);
5814
+ if (!incoming.readableEnded) setTimeout(() => {
5815
+ if (!incoming.readableEnded) setTimeout(() => {
5816
+ incoming.destroy();
5817
+ outgoing.destroy();
5229
5818
  });
5230
5819
  });
5231
5820
  };
5232
- outgoing.on("finish", () => {
5233
- if (!incomingEnded) drainIncoming(incoming);
5234
- });
5235
5821
  }
5236
- outgoing.on("close", () => {
5237
- if (req[abortControllerKey]) {
5238
- if (incoming.errored) req[abortControllerKey].abort(incoming.errored.toString());
5239
- else if (!outgoing.writableFinished) req[abortControllerKey].abort("Client connection prematurely closed.");
5240
- }
5241
- if (!incomingEnded) setTimeout(() => {
5242
- if (!incomingEnded) setTimeout(() => {
5243
- drainIncoming(incoming);
5244
- });
5245
- });
5246
- });
5247
5822
  res = fetchCallback(req, {
5248
5823
  incoming,
5249
5824
  outgoing
5250
5825
  });
5251
- if (cacheKey in res) return responseViaCache(res, outgoing);
5826
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
5827
+ if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
5828
+ if (!incoming.readableEnded) drainIncoming(incoming);
5829
+ });
5830
+ return responseViaCache(res, outgoing);
5831
+ }
5832
+ ensureCloseHandler();
5252
5833
  } catch (e) {
5253
5834
  if (!res) if (options.errorHandler) {
5835
+ ensureCloseHandler();
5254
5836
  res = await options.errorHandler(req ? e : toRequestError(e));
5255
5837
  if (!res) return;
5256
5838
  } else if (!req) res = handleRequestError();
@@ -5264,16 +5846,138 @@ var getRequestListener = (fetchCallback, options = {}) => {
5264
5846
  }
5265
5847
  };
5266
5848
  };
5267
- var createAdaptorServer = (options) => {
5849
+ globalThis.CloseEvent;
5850
+ globalThis.ErrorEvent;
5851
+ const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
5852
+ const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
5853
+ const responseHeadersToSkip = /* @__PURE__ */ new Set([
5854
+ "connection",
5855
+ "content-length",
5856
+ "keep-alive",
5857
+ "proxy-authenticate",
5858
+ "proxy-authorization",
5859
+ "te",
5860
+ "trailer",
5861
+ "transfer-encoding",
5862
+ "upgrade",
5863
+ "sec-websocket-accept",
5864
+ "sec-websocket-extensions",
5865
+ "sec-websocket-protocol"
5866
+ ]);
5867
+ const appendResponseHeaders = (headers, responseHeaders) => {
5868
+ if (!responseHeaders) return;
5869
+ responseHeaders.forEach((value, key) => {
5870
+ if (responseHeadersToSkip.has(key.toLowerCase())) return;
5871
+ headers.push(`${key}: ${value}`);
5872
+ });
5873
+ };
5874
+ const rejectUpgradeRequest = (socket, status, responseHeaders) => {
5875
+ const responseLines = ["Connection: close", "Content-Length: 0"];
5876
+ appendResponseHeaders(responseLines, responseHeaders);
5877
+ socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
5878
+ `);
5879
+ };
5880
+ const createUpgradeRequest = (request) => {
5881
+ const protocol = request.socket.encrypted ? "https" : "http";
5882
+ const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
5883
+ const headers = new Headers();
5884
+ for (const key in request.headers) {
5885
+ const value = request.headers[key];
5886
+ if (!value) continue;
5887
+ headers.append(key, Array.isArray(value) ? value[0] : value);
5888
+ }
5889
+ return new Request(url, { headers });
5890
+ };
5891
+ const setupWebSocket = (options) => {
5892
+ const { server, fetchCallback, wss } = options;
5893
+ const waiterMap = /* @__PURE__ */ new Map();
5894
+ wss.on("connection", (ws, request) => {
5895
+ const waiter = waiterMap.get(request);
5896
+ if (waiter) {
5897
+ waiter.resolve(ws);
5898
+ waiterMap.delete(request);
5899
+ }
5900
+ });
5901
+ const rejectWaiter = (request) => {
5902
+ const waiter = waiterMap.get(request);
5903
+ if (waiter) {
5904
+ waiterMap.delete(request);
5905
+ waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted"));
5906
+ }
5907
+ };
5908
+ const waitForWebSocket = (request, connectionSymbol) => {
5909
+ return new Promise((resolve, reject) => {
5910
+ waiterMap.set(request, {
5911
+ resolve,
5912
+ reject,
5913
+ connectionSymbol
5914
+ });
5915
+ });
5916
+ };
5917
+ server.on("upgrade", async (request, socket, head) => {
5918
+ if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
5919
+ const env = {
5920
+ incoming: request,
5921
+ outgoing: void 0,
5922
+ wss,
5923
+ [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
5924
+ };
5925
+ let status = 400;
5926
+ let responseHeaders;
5927
+ try {
5928
+ const response = await fetchCallback(createUpgradeRequest(request), env);
5929
+ if (response instanceof Response) {
5930
+ status = response.status;
5931
+ responseHeaders = response.headers;
5932
+ }
5933
+ } catch {
5934
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
5935
+ return;
5936
+ }
5937
+ const waiter = waiterMap.get(request);
5938
+ if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
5939
+ rejectWaiter(request);
5940
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
5941
+ return;
5942
+ }
5943
+ const addResponseHeaders = (headers) => {
5944
+ appendResponseHeaders(headers, responseHeaders);
5945
+ };
5946
+ const reclaimWaiterOnClose = () => rejectWaiter(request);
5947
+ socket.once("close", reclaimWaiterOnClose);
5948
+ wss.on("headers", addResponseHeaders);
5949
+ try {
5950
+ wss.handleUpgrade(request, socket, head, (ws) => {
5951
+ socket.off("close", reclaimWaiterOnClose);
5952
+ wss.emit("connection", ws, request);
5953
+ });
5954
+ } finally {
5955
+ wss.off("headers", addResponseHeaders);
5956
+ }
5957
+ });
5958
+ server.on("close", () => {
5959
+ wss.close();
5960
+ });
5961
+ };
5962
+ const createAdaptorServer = (options) => {
5268
5963
  const fetchCallback = options.fetch;
5269
5964
  const requestListener = getRequestListener(fetchCallback, {
5270
5965
  hostname: options.hostname,
5271
5966
  overrideGlobalObjects: options.overrideGlobalObjects,
5272
5967
  autoCleanupIncoming: options.autoCleanupIncoming
5273
5968
  });
5274
- return (options.createServer || createServer)(options.serverOptions || {}, requestListener);
5969
+ const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
5970
+ if (options.websocket && options.websocket.server) {
5971
+ if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
5972
+ setupWebSocket({
5973
+ server,
5974
+ fetchCallback,
5975
+ wss: options.websocket.server
5976
+ });
5977
+ }
5978
+ return server;
5275
5979
  };
5276
- var serve = (options, listeningListener) => {
5980
+ const serve = (options, listeningListener) => {
5277
5981
  const server = createAdaptorServer(options);
5278
5982
  server.listen(options?.port ?? 3e3, options.hostname, () => {
5279
5983
  const serverInfo = server.address();
@@ -5282,6 +5986,65 @@ var serve = (options, listeningListener) => {
5282
5986
  return server;
5283
5987
  };
5284
5988
  //#endregion
5989
+ //#region node_modules/@hono/node-server/dist/utils/stream.mjs
5990
+ const pr54206Applied = () => {
5991
+ const [major, minor] = versions.node.split(".").map((component) => parseInt(component));
5992
+ return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
5993
+ };
5994
+ const useReadableToWeb = pr54206Applied();
5995
+ const createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => {
5996
+ if (useNativeReadableToWeb) return Readable.toWeb(stream);
5997
+ let controller;
5998
+ let settled = false;
5999
+ const cleanup = () => {
6000
+ stream.off("data", onData);
6001
+ stream.off("error", onError);
6002
+ stream.off("end", onTerminate);
6003
+ stream.off("close", onTerminate);
6004
+ };
6005
+ const settle = (callback) => {
6006
+ if (settled) return;
6007
+ settled = true;
6008
+ cleanup();
6009
+ callback?.();
6010
+ };
6011
+ const onData = (chunk) => {
6012
+ if (settled || !controller) return;
6013
+ controller.enqueue(chunk);
6014
+ if ((controller.desiredSize ?? 0) <= 0) stream.pause();
6015
+ };
6016
+ const onError = (error) => {
6017
+ settle(() => {
6018
+ controller?.error(error);
6019
+ });
6020
+ };
6021
+ const onTerminate = () => {
6022
+ settle(() => {
6023
+ controller?.close();
6024
+ });
6025
+ };
6026
+ return new ReadableStream({
6027
+ start(streamController) {
6028
+ controller = streamController;
6029
+ stream.on("data", onData);
6030
+ stream.on("error", onError);
6031
+ stream.on("end", onTerminate);
6032
+ stream.on("close", onTerminate);
6033
+ stream.pause();
6034
+ },
6035
+ pull() {
6036
+ if (!settled) stream.resume();
6037
+ },
6038
+ cancel() {
6039
+ settle();
6040
+ const ignoreError = () => {};
6041
+ stream.on("error", ignoreError);
6042
+ stream.once("close", () => stream.off("error", ignoreError));
6043
+ stream.destroy();
6044
+ }
6045
+ });
6046
+ };
6047
+ //#endregion
5285
6048
  //#region node_modules/hono/dist/utils/mime.js
5286
6049
  var getMimeType = (filename, mimes = baseMimes) => {
5287
6050
  const match = filename.match(/\.([a-zA-Z0-9]+?)$/);
@@ -5348,45 +6111,56 @@ var baseMimes = {
5348
6111
  };
5349
6112
  //#endregion
5350
6113
  //#region node_modules/@hono/node-server/dist/serve-static.mjs
5351
- var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
5352
- var ENCODINGS = {
6114
+ const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
6115
+ const ENCODINGS = {
5353
6116
  br: ".br",
5354
6117
  zstd: ".zst",
5355
6118
  gzip: ".gz"
5356
6119
  };
5357
- var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
5358
- var pr54206Applied = () => {
5359
- const [major, minor] = versions.node.split(".").map((component) => parseInt(component));
5360
- return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
5361
- };
5362
- var useReadableToWeb = pr54206Applied();
5363
- var createStreamBody = (stream) => {
5364
- if (useReadableToWeb) return Readable.toWeb(stream);
5365
- return new ReadableStream({
5366
- start(controller) {
5367
- stream.on("data", (chunk) => {
5368
- controller.enqueue(chunk);
5369
- });
5370
- stream.on("error", (err) => {
5371
- controller.error(err);
5372
- });
5373
- stream.on("end", () => {
5374
- controller.close();
5375
- });
5376
- },
5377
- cancel() {
5378
- stream.destroy();
5379
- }
5380
- });
5381
- };
5382
- var getStats = (path) => {
6120
+ const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
6121
+ const getStats = (path) => {
5383
6122
  let stats;
5384
6123
  try {
5385
6124
  stats = statSync(path);
5386
6125
  } catch {}
5387
6126
  return stats;
5388
6127
  };
5389
- var tryDecode = (str, decoder) => {
6128
+ const BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\d*)-(\d*)$/;
6129
+ const parseByteRange = (range) => {
6130
+ const match = range.match(BYTE_RANGE_PATTERN);
6131
+ if (!match) return;
6132
+ const [, start, end] = match;
6133
+ if (start === "") return {
6134
+ type: "suffix",
6135
+ length: Number(end)
6136
+ };
6137
+ if (end === "") return {
6138
+ type: "open-ended",
6139
+ start: Number(start)
6140
+ };
6141
+ return {
6142
+ type: "bounded",
6143
+ start: Number(start),
6144
+ end: Number(end)
6145
+ };
6146
+ };
6147
+ const resolveByteRange = (spec, size) => {
6148
+ if (size === 0) return;
6149
+ if (spec.type === "suffix") {
6150
+ if (spec.length === 0) return;
6151
+ return {
6152
+ start: Math.max(size - spec.length, 0),
6153
+ end: size - 1
6154
+ };
6155
+ }
6156
+ const end = spec.type === "bounded" ? Math.min(spec.end, size - 1) : size - 1;
6157
+ if (spec.start >= size || spec.start > end) return;
6158
+ return {
6159
+ start: spec.start,
6160
+ end
6161
+ };
6162
+ };
6163
+ const tryDecode = (str, decoder) => {
5390
6164
  try {
5391
6165
  return decoder(str);
5392
6166
  } catch {
@@ -5399,27 +6173,27 @@ var tryDecode = (str, decoder) => {
5399
6173
  });
5400
6174
  }
5401
6175
  };
5402
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
5403
- var serveStatic = (options = { root: "" }) => {
6176
+ const tryDecodeURI = (str) => tryDecode(str, decodeURI);
6177
+ const serveStatic = (options = { root: "" }) => {
5404
6178
  const root = options.root || "";
5405
6179
  const optionPath = options.path;
5406
- if (root !== "" && !existsSync$1(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
6180
+ if (root !== "" && !existsSync(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
5407
6181
  return async (c, next) => {
5408
6182
  if (c.finalized) return next();
5409
6183
  let filename;
5410
6184
  if (optionPath) filename = optionPath;
5411
6185
  else try {
5412
6186
  filename = tryDecodeURI(c.req.path);
5413
- if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(filename)) throw new Error();
6187
+ if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) throw new Error();
5414
6188
  } catch {
5415
6189
  await options.onNotFound?.(c.req.path, c);
5416
6190
  return next();
5417
6191
  }
5418
- let path = join$1(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename);
6192
+ let path = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename);
5419
6193
  let stats = getStats(path);
5420
6194
  if (stats && stats.isDirectory()) {
5421
6195
  const indexFile = options.index ?? "index.html";
5422
- path = join$1(path, indexFile);
6196
+ path = join(path, indexFile);
5423
6197
  stats = getStats(path);
5424
6198
  }
5425
6199
  if (!stats) {
@@ -5428,7 +6202,7 @@ var serveStatic = (options = { root: "" }) => {
5428
6202
  }
5429
6203
  const mimeType = getMimeType(path);
5430
6204
  c.header("Content-Type", mimeType || "application/octet-stream");
5431
- if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
6205
+ if (options.precompressed && (!mimeType || mimeType === "application/octet-stream" || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
5432
6206
  const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
5433
6207
  for (const encoding of ENCODINGS_ORDERED_KEYS) {
5434
6208
  if (!acceptEncodingSet.has(encoding)) continue;
@@ -5445,6 +6219,7 @@ var serveStatic = (options = { root: "" }) => {
5445
6219
  let result;
5446
6220
  const size = stats.size;
5447
6221
  const range = c.req.header("range") || "";
6222
+ c.header("Last-Modified", stats.mtime.toUTCString());
5448
6223
  if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
5449
6224
  c.header("Content-Length", size.toString());
5450
6225
  c.status(200);
@@ -5454,19 +6229,24 @@ var serveStatic = (options = { root: "" }) => {
5454
6229
  result = c.body(createStreamBody(createReadStream(path)), 200);
5455
6230
  } else {
5456
6231
  c.header("Accept-Ranges", "bytes");
5457
- c.header("Date", stats.birthtime.toUTCString());
5458
- const parts = range.replace(/bytes=/, "").split("-", 2);
5459
- const start = parseInt(parts[0], 10) || 0;
5460
- let end = parseInt(parts[1], 10) || size - 1;
5461
- if (size < end - start + 1) end = size - 1;
5462
- const chunksize = end - start + 1;
5463
- const stream = createReadStream(path, {
5464
- start,
5465
- end
5466
- });
5467
- c.header("Content-Length", chunksize.toString());
5468
- c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
5469
- result = c.body(createStreamBody(stream), 206);
6232
+ const resolvedRange = resolveByteRange(parseByteRange(range) ?? {
6233
+ type: "open-ended",
6234
+ start: 0
6235
+ }, size);
6236
+ if (!resolvedRange) {
6237
+ c.header("Content-Range", `bytes */${size}`);
6238
+ result = c.body(null, 416);
6239
+ } else {
6240
+ const { start, end } = resolvedRange;
6241
+ const chunkSize = end - start + 1;
6242
+ const stream = createReadStream(path, {
6243
+ start,
6244
+ end
6245
+ });
6246
+ c.header("Content-Length", chunkSize.toString());
6247
+ c.header("Content-Range", `bytes ${start}-${end}/${size}`);
6248
+ result = c.body(createStreamBody(stream), 206);
6249
+ }
5470
6250
  }
5471
6251
  await options.onFound?.(path, c);
5472
6252
  return result;
@@ -5474,7 +6254,7 @@ var serveStatic = (options = { root: "" }) => {
5474
6254
  };
5475
6255
  //#endregion
5476
6256
  //#region node_modules/hono/dist/utils/cookie.js
5477
- var validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
6257
+ var relaxedCookieNameRegEx = /^[!#-:<>-[\]-~]+$/;
5478
6258
  var validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
5479
6259
  var trimCookieWhitespace = (value) => {
5480
6260
  let start = 0;
@@ -5499,11 +6279,11 @@ var parse$1 = (cookie, name) => {
5499
6279
  const valueStartPos = pairStr.indexOf("=");
5500
6280
  if (valueStartPos === -1) continue;
5501
6281
  const cookieName = trimCookieWhitespace(pairStr.substring(0, valueStartPos));
5502
- if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName) || cookieName in parsedCookie) continue;
6282
+ if (name && name !== cookieName || !relaxedCookieNameRegEx.test(cookieName) || cookieName in parsedCookie) continue;
5503
6283
  let cookieValue = trimCookieWhitespace(pairStr.substring(valueStartPos + 1));
5504
6284
  if (cookieValue.startsWith("\"") && cookieValue.endsWith("\"")) cookieValue = cookieValue.slice(1, -1);
5505
6285
  if (validCookieValueRegEx.test(cookieValue)) {
5506
- parsedCookie[cookieName] = cookieValue.indexOf("%") !== -1 ? tryDecode$1(cookieValue, decodeURIComponent_) : cookieValue;
6286
+ parsedCookie[cookieName] = tryDecodeURIComponent(cookieValue);
5507
6287
  if (name) break;
5508
6288
  }
5509
6289
  }
@@ -5524,15 +6304,10 @@ var getCookie = (c, key, prefix) => {
5524
6304
  return parse$1(cookie);
5525
6305
  };
5526
6306
  //#endregion
5527
- //#region node_modules/hono/dist/utils/buffer.js
5528
- var bufferToFormData = (arrayBuffer, contentType) => {
5529
- return new Response(arrayBuffer, { headers: { "Content-Type": contentType } }).formData();
5530
- };
5531
- //#endregion
5532
6307
  //#region node_modules/hono/dist/validator/validator.js
5533
- var jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
5534
- var multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/;
5535
- var urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
6308
+ var jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/i;
6309
+ var multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/i;
6310
+ var urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/i;
5536
6311
  var validator = (target, validationFunc) => {
5537
6312
  return async (c, next) => {
5538
6313
  let value = {};
@@ -5579,9 +6354,7 @@ var validator = (target, validationFunc) => {
5579
6354
  case "header":
5580
6355
  value = c.req.header();
5581
6356
  break;
5582
- case "cookie":
5583
- value = getCookie(c);
5584
- break;
6357
+ case "cookie": value = getCookie(c);
5585
6358
  }
5586
6359
  const res = await validationFunc(value, c);
5587
6360
  if (res instanceof Response) return res;
@@ -5590,14 +6363,14 @@ var validator = (target, validationFunc) => {
5590
6363
  };
5591
6364
  };
5592
6365
  //#endregion
5593
- //#region node_modules/@hono/zod-validator/dist/index.js
6366
+ //#region node_modules/@hono/zod-validator/dist/index.mjs
5594
6367
  function zValidatorFunction(target, schema, hook, options) {
5595
6368
  return validator(target, async (value, c) => {
5596
6369
  let validatorValue = value;
5597
6370
  if (target === "header" && "_def" in schema || target === "header" && "_zod" in schema) {
5598
6371
  const schemaKeys = Object.keys("in" in schema ? schema.in.shape : schema.shape);
5599
6372
  const caseInsensitiveKeymap = Object.fromEntries(schemaKeys.map((key) => [key.toLowerCase(), key]));
5600
- validatorValue = Object.fromEntries(Object.entries(value).map(([key, value$1]) => [caseInsensitiveKeymap[key] || key, value$1]));
6373
+ validatorValue = Object.fromEntries(Object.entries(value).map(([key, value]) => [caseInsensitiveKeymap[key] || key, value]));
5601
6374
  }
5602
6375
  const result = options && options.validationFunction ? await options.validationFunction(schema, validatorValue) : await schema.safeParseAsync(validatorValue);
5603
6376
  if (hook) {
@@ -5791,11 +6564,11 @@ async function getFileContents(src, cwd, path, oldPath) {
5791
6564
  *
5792
6565
  * Entries older than 30 days are pruned on load.
5793
6566
  */
5794
- const BASE_DIR = join$1(process.env["HOME"] ?? "~", ".local", "share", "skepsis");
5795
- const MAX_AGE_MS = 720 * 60 * 60 * 1e3;
6567
+ const BASE_DIR$1 = join$1(process.env["HOME"] ?? "~", ".local", "share", "skepsis");
6568
+ const MAX_AGE_MS = 2592e6;
5796
6569
  function viewedPath(cwd) {
5797
6570
  const hash = createHash("sha256").update(cwd).digest("hex").slice(0, 12);
5798
- return join$1(BASE_DIR, `${hash}.viewed`);
6571
+ return join$1(BASE_DIR$1, `${hash}.viewed`);
5799
6572
  }
5800
6573
  async function loadAll(cwd) {
5801
6574
  const map = /* @__PURE__ */ new Map();
@@ -5820,7 +6593,7 @@ async function loadAll(cwd) {
5820
6593
  return map;
5821
6594
  }
5822
6595
  async function saveAll(cwd, map) {
5823
- await mkdir(BASE_DIR, { recursive: true });
6596
+ await mkdir(BASE_DIR$1, { recursive: true });
5824
6597
  const lines = [];
5825
6598
  for (const [file, entries] of map) for (const { hash, timestamp } of entries) lines.push(`${file}\t${hash}\t${timestamp}`);
5826
6599
  await writeFile$1(viewedPath(cwd), lines.join("\n") + "\n");
@@ -18350,7 +19123,8 @@ function detectLanguage(file, firstLine) {
18350
19123
  * callers that insert comments fall back to bare tags, and the UI can
18351
19124
  * distinguish "unknown, so no marker" from a known-markerless format. */
18352
19125
  function getCommentSyntax(file, firstLine) {
18353
- const ext = extname(basename(file).toLowerCase());
19126
+ const base = basename(file).toLowerCase();
19127
+ const ext = extname(base);
18354
19128
  const syntaxOverride = EXTENSION_SYNTAX_OVERRIDES[ext];
18355
19129
  if (syntaxOverride) return syntaxOverride;
18356
19130
  const lang = detectLanguage(file, firstLine);
@@ -18489,7 +19263,6 @@ function cached(getter) {
18489
19263
  Object.defineProperty(this, "value", { value });
18490
19264
  return value;
18491
19265
  }
18492
- throw new Error("cached value already set");
18493
19266
  } };
18494
19267
  }
18495
19268
  function nullish(input) {
@@ -19011,8 +19784,10 @@ const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst,
19011
19784
  inst._zod.onattach.push((inst) => {
19012
19785
  const bag = inst._zod.bag;
19013
19786
  const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
19014
- if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
19015
- else bag.exclusiveMaximum = def.value;
19787
+ if (def.value < curr) {
19788
+ if (def.inclusive) bag.maximum = def.value;
19789
+ else bag.exclusiveMaximum = def.value;
19790
+ }
19016
19791
  });
19017
19792
  inst._zod.check = (payload) => {
19018
19793
  if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
@@ -19033,8 +19808,10 @@ const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan",
19033
19808
  inst._zod.onattach.push((inst) => {
19034
19809
  const bag = inst._zod.bag;
19035
19810
  const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
19036
- if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
19037
- else bag.exclusiveMinimum = def.value;
19811
+ if (def.value > curr) {
19812
+ if (def.inclusive) bag.minimum = def.value;
19813
+ else bag.exclusiveMinimum = def.value;
19814
+ }
19038
19815
  });
19039
19816
  inst._zod.check = (payload) => {
19040
19817
  if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
@@ -19886,13 +20663,13 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
19886
20663
  }
19887
20664
  return propValues;
19888
20665
  });
19889
- const isObject$1 = isObject;
20666
+ const isObject$2 = isObject;
19890
20667
  const catchall = def.catchall;
19891
20668
  let value;
19892
20669
  inst._zod.parse = (payload, ctx) => {
19893
20670
  value ?? (value = _normalized.value);
19894
20671
  const input = payload.value;
19895
- if (!isObject$1(input)) {
20672
+ if (!isObject$2(input)) {
19896
20673
  payload.issues.push({
19897
20674
  expected: "object",
19898
20675
  code: "invalid_type",
@@ -19986,7 +20763,7 @@ const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) =>
19986
20763
  return (payload, ctx) => fn(shape, payload, ctx);
19987
20764
  };
19988
20765
  let fastpass;
19989
- const isObject$2 = isObject;
20766
+ const isObject$1 = isObject;
19990
20767
  const jit = !globalConfig.jitless;
19991
20768
  const fastEnabled = jit && allowsEval.value;
19992
20769
  const catchall = def.catchall;
@@ -19994,7 +20771,7 @@ const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) =>
19994
20771
  inst._zod.parse = (payload, ctx) => {
19995
20772
  value ?? (value = _normalized.value);
19996
20773
  const input = payload.value;
19997
- if (!isObject$2(input)) {
20774
+ if (!isObject$1(input)) {
19998
20775
  payload.issues.push({
19999
20776
  expected: "object",
20000
20777
  code: "invalid_type",
@@ -21158,8 +21935,10 @@ function finalize(ctx, schema) {
21158
21935
  const seen = entry[1];
21159
21936
  if (seen.def && seen.defId) defs[seen.defId] = seen.def;
21160
21937
  }
21161
- if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs;
21162
- else result.definitions = defs;
21938
+ if (ctx.external) {} else if (Object.keys(defs).length > 0) {
21939
+ if (ctx.target === "draft-2020-12") result.$defs = defs;
21940
+ else result.definitions = defs;
21941
+ }
21163
21942
  try {
21164
21943
  const finalized = JSON.parse(JSON.stringify(result));
21165
21944
  Object.defineProperty(finalized, "~standard", {
@@ -21266,23 +22045,31 @@ const numberProcessor = (schema, ctx, _json, _params) => {
21266
22045
  const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
21267
22046
  if (typeof format === "string" && format.includes("int")) json.type = "integer";
21268
22047
  else json.type = "number";
21269
- if (typeof exclusiveMinimum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
21270
- json.minimum = exclusiveMinimum;
21271
- json.exclusiveMinimum = true;
21272
- } else json.exclusiveMinimum = exclusiveMinimum;
22048
+ if (typeof exclusiveMinimum === "number") {
22049
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
22050
+ json.minimum = exclusiveMinimum;
22051
+ json.exclusiveMinimum = true;
22052
+ } else json.exclusiveMinimum = exclusiveMinimum;
22053
+ }
21273
22054
  if (typeof minimum === "number") {
21274
22055
  json.minimum = minimum;
21275
- if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") if (exclusiveMinimum >= minimum) delete json.minimum;
21276
- else delete json.exclusiveMinimum;
22056
+ if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") {
22057
+ if (exclusiveMinimum >= minimum) delete json.minimum;
22058
+ else delete json.exclusiveMinimum;
22059
+ }
22060
+ }
22061
+ if (typeof exclusiveMaximum === "number") {
22062
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
22063
+ json.maximum = exclusiveMaximum;
22064
+ json.exclusiveMaximum = true;
22065
+ } else json.exclusiveMaximum = exclusiveMaximum;
21277
22066
  }
21278
- if (typeof exclusiveMaximum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
21279
- json.maximum = exclusiveMaximum;
21280
- json.exclusiveMaximum = true;
21281
- } else json.exclusiveMaximum = exclusiveMaximum;
21282
22067
  if (typeof maximum === "number") {
21283
22068
  json.maximum = maximum;
21284
- if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") if (exclusiveMaximum <= maximum) delete json.maximum;
21285
- else delete json.exclusiveMaximum;
22069
+ if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") {
22070
+ if (exclusiveMaximum <= maximum) delete json.maximum;
22071
+ else delete json.exclusiveMaximum;
22072
+ }
21286
22073
  }
21287
22074
  if (typeof multipleOf === "number") json.multipleOf = multipleOf;
21288
22075
  };
@@ -22088,6 +22875,46 @@ const fileContentsQuerySchema = object({
22088
22875
  path: string(),
22089
22876
  oldPath: string().optional()
22090
22877
  });
22878
+ /** Color scheme. 'system' follows the OS preference; 'light' and 'dark' force
22879
+ * it (e.g. light diffs on a dark desktop). One list drives the API schema,
22880
+ * the toggle cycle, and the client's data-theme validation. */
22881
+ const THEME_MODES = [
22882
+ "light",
22883
+ "dark",
22884
+ "system"
22885
+ ];
22886
+ const themeRequestSchema = object({ theme: _enum(THEME_MODES) });
22887
+ //#endregion
22888
+ //#region server/settings.ts
22889
+ /**
22890
+ * Global UI settings at ~/.local/share/skepsis/settings.json. Unlike viewed
22891
+ * state, settings are not per-repo (no cwd hashing): a theme preference is
22892
+ * about the user, not the diff under review. Server-side storage is what
22893
+ * makes the preference survive restarts at all — the ephemeral port means a
22894
+ * fresh browser origin every run, so web storage can't.
22895
+ */
22896
+ const BASE_DIR = join$1(process.env["HOME"] ?? "~", ".local", "share", "skepsis");
22897
+ const SETTINGS_PATH = join$1(BASE_DIR, "settings.json");
22898
+ /** Missing file, unparseable JSON, or an unknown value → 'system'. */
22899
+ async function loadTheme() {
22900
+ try {
22901
+ const theme = JSON.parse(await readFile$1(SETTINGS_PATH, "utf-8")).theme;
22902
+ if (THEME_MODES.includes(theme)) return theme;
22903
+ } catch {}
22904
+ return "system";
22905
+ }
22906
+ async function saveTheme(theme) {
22907
+ await mkdir(BASE_DIR, { recursive: true });
22908
+ await writeFile$1(SETTINGS_PATH, JSON.stringify({ theme }, null, 2) + "\n");
22909
+ }
22910
+ /** Body of /api/theme.js, loaded by a render-blocking <script> in index.html
22911
+ * so a forced theme's data-theme lands on <html> before first paint (CSS
22912
+ * keys color-scheme off the attribute). 'system' means no attribute: an
22913
+ * empty script leaves the page following the OS. */
22914
+ function themeBootScript(theme) {
22915
+ if (theme === "system") return "";
22916
+ return `document.documentElement.dataset.theme = '${theme}'\n`;
22917
+ }
22091
22918
  //#endregion
22092
22919
  //#region server/main.ts
22093
22920
  async function startServer(opts) {
@@ -22139,6 +22966,18 @@ async function startServer(opts) {
22139
22966
  await removeComment(cwd, file, line);
22140
22967
  return c.json({ ok: true });
22141
22968
  });
22969
+ app.get("/api/theme", async (c) => {
22970
+ return c.json({ theme: await loadTheme() });
22971
+ });
22972
+ app.get("/api/theme.js", async (c) => {
22973
+ c.header("Cache-Control", "no-store");
22974
+ c.header("Content-Type", "text/javascript");
22975
+ return c.body(themeBootScript(await loadTheme()));
22976
+ });
22977
+ app.post("/api/theme", zValidator("json", themeRequestSchema), async (c) => {
22978
+ await saveTheme(c.req.valid("json").theme);
22979
+ return c.json({ ok: true });
22980
+ });
22142
22981
  const distDir = join(import.meta.dirname, "..", "dist", "web");
22143
22982
  app.use("*", serveStatic({ root: relative(cwd, distDir) }));
22144
22983
  app.get("*", async (c) => {
@@ -22148,7 +22987,7 @@ async function startServer(opts) {
22148
22987
  app.onError((err, c) => {
22149
22988
  return c.json({ error: err.message }, 500);
22150
22989
  });
22151
- return new Promise((resolve) => {
22990
+ return new Promise((resolve, reject) => {
22152
22991
  const server = serve({
22153
22992
  fetch: app.fetch,
22154
22993
  port,
@@ -22161,11 +23000,17 @@ async function startServer(opts) {
22161
23000
  close: () => server.close()
22162
23001
  });
22163
23002
  });
23003
+ server.on("error", reject);
22164
23004
  });
22165
23005
  }
22166
23006
  //#endregion
22167
23007
  //#region cli.ts
22168
- const program = new Command().name("skepsis").description("Local diff review UI (auto-detects jj or git)").option("-r, --revisions <revsets>", "Show changes in these revisions").option("-f, --from <rev>", "Show changes from this revision").option("-t, --to <rev>", "Show changes to this revision").option("--git", "force git mode (skip jj detection)").option("--dev", "run with Vite dev server for development").option("--host <address>", "address to bind the HTTP server to", "localhost").argument("[files...]", "Limit diff to these paths (passed through to jj/git)").parse();
23008
+ function parsePort(value) {
23009
+ const port = /^\d+$/.test(value) ? Number(value) : NaN;
23010
+ if (!(port >= 1 && port <= 65535)) throw new InvalidArgumentError("port must be an integer between 1 and 65535");
23011
+ return port;
23012
+ }
23013
+ const program = new Command().name("skepsis").description("Local diff review UI (auto-detects jj or git)").option("-r, --revisions <revsets>", "Show changes in these revisions").option("-f, --from <rev>", "Show changes from this revision").option("-t, --to <rev>", "Show changes to this revision").option("--git", "force git mode (skip jj detection)").option("--dev", "run with Vite dev server for development").option("--host <address>", "address to bind the HTTP server to", "localhost").option("-p, --port <number>", "port for the browser UI", parsePort).argument("[files...]", "Limit diff to these paths (passed through to jj/git)").parse();
22169
23014
  const opts = program.opts();
22170
23015
  const files = program.processedArgs[0] ?? [];
22171
23016
  const hostname = opts.host;
@@ -22274,22 +23119,23 @@ function buildDiffSource() {
22274
23119
  let commentsEnabled;
22275
23120
  let endpoints;
22276
23121
  let displayArgs;
22277
- if (opts.from || opts.to) if (opts.to) {
22278
- args = [opts.from ?? "HEAD", opts.to];
22279
- commentsEnabled = false;
22280
- endpoints = {
22281
- left: opts.from ?? "HEAD",
22282
- right: { rev: opts.to }
22283
- };
22284
- } else {
22285
- args = [opts.from];
22286
- commentsEnabled = true;
22287
- endpoints = {
22288
- left: opts.from,
22289
- right: "workingCopy"
22290
- };
22291
- }
22292
- else if (!opts.revisions) {
23122
+ if (opts.from || opts.to) {
23123
+ if (opts.to) {
23124
+ args = [opts.from ?? "HEAD", opts.to];
23125
+ commentsEnabled = false;
23126
+ endpoints = {
23127
+ left: opts.from ?? "HEAD",
23128
+ right: { rev: opts.to }
23129
+ };
23130
+ } else {
23131
+ args = [opts.from];
23132
+ commentsEnabled = true;
23133
+ endpoints = {
23134
+ left: opts.from,
23135
+ right: "workingCopy"
23136
+ };
23137
+ }
23138
+ } else if (!opts.revisions) {
22293
23139
  const { base, mergeBase } = resolveGitBase();
22294
23140
  args = [mergeBase];
22295
23141
  displayArgs = ["--merge-base", base];
@@ -22351,7 +23197,11 @@ const checkoutRoot = opts.dev ? requireCheckoutRoot() : void 0;
22351
23197
  const { port: apiPort } = await startServer({
22352
23198
  diffSource,
22353
23199
  cwd,
22354
- hostname
23200
+ hostname,
23201
+ port: opts.dev ? void 0 : opts.port
23202
+ }).catch((err) => {
23203
+ console.error(err.message);
23204
+ return cleanup(1);
22355
23205
  });
22356
23206
  function urlOpenCommand(url) {
22357
23207
  switch (process.platform) {
@@ -22381,6 +23231,7 @@ if (opts.dev) {
22381
23231
  "--host",
22382
23232
  hostname
22383
23233
  ];
23234
+ if (opts.port !== void 0) viteArgs.push("--port", String(opts.port), "--strictPort");
22384
23235
  if (shouldAutoOpen) viteArgs.push("--open");
22385
23236
  const vite = spawn("npx", viteArgs, {
22386
23237
  cwd: checkoutRoot,
@@ -22393,16 +23244,12 @@ if (opts.dev) {
22393
23244
  });
22394
23245
  children.push(vite);
22395
23246
  } else if (shouldAutoOpen) {
22396
- const url = `http://localhost:${apiPort}`;
22397
- const { cmd, args } = urlOpenCommand(url);
23247
+ const { cmd, args } = urlOpenCommand(`http://localhost:${apiPort}`);
22398
23248
  const opener = spawn(cmd, args, {
22399
23249
  detached: true,
22400
23250
  stdio: "ignore"
22401
23251
  });
22402
- opener.on("error", (err) => {
22403
- console.error(`Could not open URL with ${cmd}: ${err.message}`);
22404
- console.error(`Open ${url} to see the diff`);
22405
- });
23252
+ opener.on("error", () => {});
22406
23253
  opener.unref();
22407
23254
  }
22408
23255
  //#endregion