@aopslab/aops-server 0.1.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 (185) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +6 -0
  3. package/README.md +21 -0
  4. package/aops-server-runtime.json +11 -0
  5. package/build/client/_app/immutable/chunks/2_TffmqH.js +1 -0
  6. package/build/client/_app/immutable/chunks/3DOfIKW0.js +1 -0
  7. package/build/client/_app/immutable/chunks/B2EkC-sy.js +1 -0
  8. package/build/client/_app/immutable/chunks/CMkIcmi1.js +2 -0
  9. package/build/client/_app/immutable/chunks/rqnVXeyB.js +1 -0
  10. package/build/client/_app/immutable/chunks/sZYZbj9W.js +1 -0
  11. package/build/client/_app/immutable/chunks/wbPk3Yxo.js +81 -0
  12. package/build/client/_app/immutable/entry/app.C7STLTX8.js +2 -0
  13. package/build/client/_app/immutable/entry/start.BC94hOaC.js +1 -0
  14. package/build/client/_app/immutable/nodes/0.BYBfjxZ5.js +1 -0
  15. package/build/client/_app/immutable/nodes/1.BNXFXajG.js +1 -0
  16. package/build/client/_app/version.json +1 -0
  17. package/build/env.js +70 -0
  18. package/build/env.js.map +1 -0
  19. package/build/handler.js +16 -0
  20. package/build/handler.js.map +1 -0
  21. package/build/index.js +139 -0
  22. package/build/index.js.map +1 -0
  23. package/build/server/chunks/0-RfB6m2nq.js +7 -0
  24. package/build/server/chunks/0-RfB6m2nq.js.map +1 -0
  25. package/build/server/chunks/1-_gg8Q0UT.js +9 -0
  26. package/build/server/chunks/1-_gg8Q0UT.js.map +1 -0
  27. package/build/server/chunks/_server.ts-6276EQIF.js +44 -0
  28. package/build/server/chunks/_server.ts-6276EQIF.js.map +1 -0
  29. package/build/server/chunks/_server.ts-B59WFQzX.js +174 -0
  30. package/build/server/chunks/_server.ts-B59WFQzX.js.map +1 -0
  31. package/build/server/chunks/_server.ts-BauJsLZI.js +40 -0
  32. package/build/server/chunks/_server.ts-BauJsLZI.js.map +1 -0
  33. package/build/server/chunks/_server.ts-BnGzJw2-.js +81 -0
  34. package/build/server/chunks/_server.ts-BnGzJw2-.js.map +1 -0
  35. package/build/server/chunks/_server.ts-CP7qM24V.js +34 -0
  36. package/build/server/chunks/_server.ts-CP7qM24V.js.map +1 -0
  37. package/build/server/chunks/_server.ts-Cbq_u99d.js +9 -0
  38. package/build/server/chunks/_server.ts-Cbq_u99d.js.map +1 -0
  39. package/build/server/chunks/_server.ts-Ch8fPT-o.js +92 -0
  40. package/build/server/chunks/_server.ts-Ch8fPT-o.js.map +1 -0
  41. package/build/server/chunks/_server.ts-Cv-yaXZI.js +7 -0
  42. package/build/server/chunks/_server.ts-Cv-yaXZI.js.map +1 -0
  43. package/build/server/chunks/_server.ts-D6lBwOON.js +34 -0
  44. package/build/server/chunks/_server.ts-D6lBwOON.js.map +1 -0
  45. package/build/server/chunks/_server.ts-D84K3pp9.js +11 -0
  46. package/build/server/chunks/_server.ts-D84K3pp9.js.map +1 -0
  47. package/build/server/chunks/_server.ts-DNzU1ToA.js +277 -0
  48. package/build/server/chunks/_server.ts-DNzU1ToA.js.map +1 -0
  49. package/build/server/chunks/_server.ts-DQQnw77t.js +17 -0
  50. package/build/server/chunks/_server.ts-DQQnw77t.js.map +1 -0
  51. package/build/server/chunks/_server.ts-DSxr5l15.js +18 -0
  52. package/build/server/chunks/_server.ts-DSxr5l15.js.map +1 -0
  53. package/build/server/chunks/_server.ts-DZYokvuR.js +80 -0
  54. package/build/server/chunks/_server.ts-DZYokvuR.js.map +1 -0
  55. package/build/server/chunks/_server.ts-Dcqwpz2t.js +144 -0
  56. package/build/server/chunks/_server.ts-Dcqwpz2t.js.map +1 -0
  57. package/build/server/chunks/_server.ts-Di9VJnF4.js +81 -0
  58. package/build/server/chunks/_server.ts-Di9VJnF4.js.map +1 -0
  59. package/build/server/chunks/_server.ts-FBEHFT8b.js +33 -0
  60. package/build/server/chunks/_server.ts-FBEHFT8b.js.map +1 -0
  61. package/build/server/chunks/_server.ts-gZytCuiJ.js +10 -0
  62. package/build/server/chunks/_server.ts-gZytCuiJ.js.map +1 -0
  63. package/build/server/chunks/_server.ts-tNULLyEO.js +261 -0
  64. package/build/server/chunks/_server.ts-tNULLyEO.js.map +1 -0
  65. package/build/server/chunks/agent-gateway-runtime-DTZ4SxaC.js +2598 -0
  66. package/build/server/chunks/agent-gateway-runtime-DTZ4SxaC.js.map +1 -0
  67. package/build/server/chunks/aops-runtime-config-wpVmg7T-.js +179 -0
  68. package/build/server/chunks/aops-runtime-config-wpVmg7T-.js.map +1 -0
  69. package/build/server/chunks/discovery-D9JnSgfu.js +894 -0
  70. package/build/server/chunks/discovery-D9JnSgfu.js.map +1 -0
  71. package/build/server/chunks/error.svelte-DgUOqi-L.js +45 -0
  72. package/build/server/chunks/error.svelte-DgUOqi-L.js.map +1 -0
  73. package/build/server/chunks/handler-BN3-p5rP.js +1733 -0
  74. package/build/server/chunks/handler-BN3-p5rP.js.map +1 -0
  75. package/build/server/chunks/hooks.server-C4wxiH5m.js +52 -0
  76. package/build/server/chunks/hooks.server-C4wxiH5m.js.map +1 -0
  77. package/build/server/chunks/index.js-nbqdVuWC.js +10698 -0
  78. package/build/server/chunks/index.js-nbqdVuWC.js.map +1 -0
  79. package/build/server/chunks/manifest.js-_Re-Wj-y.js +167 -0
  80. package/build/server/chunks/manifest.js-_Re-Wj-y.js.map +1 -0
  81. package/build/server/chunks/plugin-error-normalize-Bq14Qbz3.js +297 -0
  82. package/build/server/chunks/plugin-error-normalize-Bq14Qbz3.js.map +1 -0
  83. package/build/server/chunks/project-alias-DqE2v58Q.js +29 -0
  84. package/build/server/chunks/project-alias-DqE2v58Q.js.map +1 -0
  85. package/build/server/chunks/registry-5amIZito.js +289 -0
  86. package/build/server/chunks/registry-5amIZito.js.map +1 -0
  87. package/build/server/chunks/request-base-url-BDdrsaga.js +24 -0
  88. package/build/server/chunks/request-base-url-BDdrsaga.js.map +1 -0
  89. package/build/server/chunks/request-context-tNeFQjgb.js +422 -0
  90. package/build/server/chunks/request-context-tNeFQjgb.js.map +1 -0
  91. package/build/server/chunks/xf-result-BRDjvftr.js +17 -0
  92. package/build/server/chunks/xf-result-BRDjvftr.js.map +1 -0
  93. package/build/shims.js +33 -0
  94. package/build/shims.js.map +1 -0
  95. package/cockpit/.vite/manifest.json +198 -0
  96. package/cockpit/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  97. package/cockpit/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  98. package/cockpit/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  99. package/cockpit/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  100. package/cockpit/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
  101. package/cockpit/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
  102. package/cockpit/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  103. package/cockpit/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  104. package/cockpit/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  105. package/cockpit/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  106. package/cockpit/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
  107. package/cockpit/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
  108. package/cockpit/assets/index-DDswO4B1.css +1 -0
  109. package/cockpit/assets/index-bovtnZ98.js +18 -0
  110. package/cockpit/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  111. package/cockpit/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  112. package/cockpit/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  113. package/cockpit/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  114. package/cockpit/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  115. package/cockpit/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  116. package/cockpit/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  117. package/cockpit/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  118. package/cockpit/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  119. package/cockpit/assets/outfit-latin-400-normal-BGsTXAXT.woff2 +0 -0
  120. package/cockpit/assets/outfit-latin-400-normal-DMwTpYkH.woff +0 -0
  121. package/cockpit/assets/outfit-latin-600-normal-B7SfZ07L.woff2 +0 -0
  122. package/cockpit/assets/outfit-latin-600-normal-BEfTtDA7.woff +0 -0
  123. package/cockpit/assets/outfit-latin-ext-400-normal-5tcqmc2S.woff2 +0 -0
  124. package/cockpit/assets/outfit-latin-ext-400-normal-DHm7mdGe.woff +0 -0
  125. package/cockpit/assets/outfit-latin-ext-600-normal-B85nYjL1.woff2 +0 -0
  126. package/cockpit/assets/outfit-latin-ext-600-normal-CWJcPgd7.woff +0 -0
  127. package/cockpit/assets/unbounded-cyrillic-600-normal-B-s5c2Kn.woff +0 -0
  128. package/cockpit/assets/unbounded-cyrillic-600-normal-DW6uzIMB.woff2 +0 -0
  129. package/cockpit/assets/unbounded-latin-600-normal-BPdB_PEv.woff +0 -0
  130. package/cockpit/assets/unbounded-latin-600-normal-oRSANpZr.woff2 +0 -0
  131. package/cockpit/assets/unbounded-latin-ext-600-normal-0iZLtTDV.woff2 +0 -0
  132. package/cockpit/assets/unbounded-latin-ext-600-normal-ClMPf-bu.woff +0 -0
  133. package/cockpit/assets/unbounded-vietnamese-600-normal-BzfrgZ_C.woff +0 -0
  134. package/cockpit/assets/unbounded-vietnamese-600-normal-Cx2bTSHN.woff2 +0 -0
  135. package/cockpit/community.module-inventory.json +2389 -0
  136. package/cockpit/index.html +14 -0
  137. package/community-postgres.json +13 -0
  138. package/migrations/agentspace/0000_thin_carlie_cooper.sql +764 -0
  139. package/migrations/agentspace/meta/0000_snapshot.json +6885 -0
  140. package/migrations/agentspace/meta/_journal.json +13 -0
  141. package/migrations/chatv3/0000_dry_ego.sql +218 -0
  142. package/migrations/chatv3/0001_nosy_obadiah_stane.sql +35 -0
  143. package/migrations/chatv3/0002_narrow_darkhawk.sql +4 -0
  144. package/migrations/chatv3/0003_damp_zarek.sql +2 -0
  145. package/migrations/chatv3/0004_nervous_martin_li.sql +60 -0
  146. package/migrations/chatv3/0005_chatv3_server_encrypted_mode.sql +1 -0
  147. package/migrations/chatv3/meta/0000_snapshot.json +1887 -0
  148. package/migrations/chatv3/meta/0001_snapshot.json +2175 -0
  149. package/migrations/chatv3/meta/0002_snapshot.json +2229 -0
  150. package/migrations/chatv3/meta/0003_snapshot.json +2241 -0
  151. package/migrations/chatv3/meta/0004_snapshot.json +2746 -0
  152. package/migrations/chatv3/meta/_journal.json +48 -0
  153. package/migrations/docman/0000_curvy_valeria_richards.sql +257 -0
  154. package/migrations/docman/0001_massive_risque.sql +2 -0
  155. package/migrations/docman/0002_simple_logan.sql +50 -0
  156. package/migrations/docman/0003_quick_index.sql +45 -0
  157. package/migrations/docman/0004_known_summary.sql +9 -0
  158. package/migrations/docman/0005_vector_signal.sql +9 -0
  159. package/migrations/docman/0006_document_version_current_invariant.sql +15 -0
  160. package/migrations/docman/meta/_journal.json +55 -0
  161. package/migrations/projectman/0000_smooth_klaw.sql +257 -0
  162. package/migrations/projectman/0001_worthless_zodiak.sql +9 -0
  163. package/migrations/projectman/0002_board_rename.sql +108 -0
  164. package/migrations/projectman/0003_review_request.sql +62 -0
  165. package/migrations/projectman/0004_review_request_idempotency.sql +3 -0
  166. package/migrations/projectman/0005_allow_multi_sprint_per_task.sql +1 -0
  167. package/migrations/projectman/meta/_journal.json +48 -0
  168. package/migrations/sys/0000_loose_praxagora.sql +31 -0
  169. package/migrations/sys/0001_awesome_ronan.sql +2 -0
  170. package/migrations/sys/0002_steady_maximus.sql +2 -0
  171. package/migrations/sys/0003_escalating_rate_limiter.sql +2 -0
  172. package/migrations/sys/0004_rate_limiter_timestamptz.sql +22 -0
  173. package/migrations/sys/0005_sys_counters.sql +21 -0
  174. package/migrations/sys/meta/_journal.json +48 -0
  175. package/npm-shrinkwrap.json +4375 -0
  176. package/package.json +62 -0
  177. package/runtime/agentspace-host-adapter.mjs +64 -0
  178. package/runtime/agentspace-tooling.mjs +389 -0
  179. package/runtime/docman-host-adapter.mjs +177 -0
  180. package/runtime/docman-policy.mjs +450 -0
  181. package/runtime/docman-tooling.mjs +20 -0
  182. package/runtime/projectman-host-adapter.mjs +597 -0
  183. package/runtime/scope-context.mjs +99 -0
  184. package/scripts/community-host.mjs +626 -0
  185. package/scripts/community-migration-policy-v1.json +296 -0
@@ -0,0 +1,1733 @@
1
+ import '../../shims.js';
2
+ import * as fs from 'node:fs';
3
+ import fs__default, { readdirSync, statSync, createReadStream } from 'node:fs';
4
+ import path, { resolve, sep, join, normalize } from 'node:path';
5
+ import process from 'node:process';
6
+ import http from 'node:http';
7
+ import { setImmediate } from 'node:timers';
8
+ import * as qs from 'node:querystring';
9
+ import { Readable } from 'node:stream';
10
+ import { S as SvelteKitError, a as Server } from './index.js-nbqdVuWC.js';
11
+ import { m as manifest } from './manifest.js-_Re-Wj-y.js';
12
+ import { env, dir, env_prefix } from '../../env.js';
13
+ import { format } from 'node:url';
14
+
15
+ function totalist(dir, callback, pre='') {
16
+ dir = resolve('.', dir);
17
+ let arr = readdirSync(dir);
18
+ let i=0, abs, stats;
19
+ for (; i < arr.length; i++) {
20
+ abs = join(dir, arr[i]);
21
+ stats = statSync(abs);
22
+ stats.isDirectory()
23
+ ? totalist(abs, callback, join(pre, arr[i]))
24
+ : callback(join(pre, arr[i]), abs, stats);
25
+ }
26
+ }
27
+
28
+ /**
29
+ * @typedef ParsedURL
30
+ * @type {import('.').ParsedURL}
31
+ */
32
+
33
+ /**
34
+ * @typedef Request
35
+ * @property {string} url
36
+ * @property {ParsedURL} _parsedUrl
37
+ */
38
+
39
+ /**
40
+ * @param {Request} req
41
+ * @returns {ParsedURL|void}
42
+ */
43
+ function parse$1(req) {
44
+ let raw = req.url;
45
+ if (raw == null) return;
46
+
47
+ let prev = req._parsedUrl;
48
+ if (prev && prev.raw === raw) return prev;
49
+
50
+ let pathname=raw, search='', query;
51
+
52
+ if (raw.length > 1) {
53
+ let idx = raw.indexOf('?', 1);
54
+
55
+ if (idx !== -1) {
56
+ search = raw.substring(idx);
57
+ pathname = raw.substring(0, idx);
58
+ if (search.length > 1) {
59
+ query = qs.parse(search.substring(1));
60
+ }
61
+ }
62
+ }
63
+
64
+ return req._parsedUrl = { pathname, search, query, raw };
65
+ }
66
+
67
+ const mimes = {
68
+ "3g2": "video/3gpp2",
69
+ "3gp": "video/3gpp",
70
+ "3gpp": "video/3gpp",
71
+ "3mf": "model/3mf",
72
+ "aac": "audio/aac",
73
+ "ac": "application/pkix-attr-cert",
74
+ "adp": "audio/adpcm",
75
+ "adts": "audio/aac",
76
+ "ai": "application/postscript",
77
+ "aml": "application/automationml-aml+xml",
78
+ "amlx": "application/automationml-amlx+zip",
79
+ "amr": "audio/amr",
80
+ "apng": "image/apng",
81
+ "appcache": "text/cache-manifest",
82
+ "appinstaller": "application/appinstaller",
83
+ "appx": "application/appx",
84
+ "appxbundle": "application/appxbundle",
85
+ "asc": "application/pgp-keys",
86
+ "atom": "application/atom+xml",
87
+ "atomcat": "application/atomcat+xml",
88
+ "atomdeleted": "application/atomdeleted+xml",
89
+ "atomsvc": "application/atomsvc+xml",
90
+ "au": "audio/basic",
91
+ "avci": "image/avci",
92
+ "avcs": "image/avcs",
93
+ "avif": "image/avif",
94
+ "aw": "application/applixware",
95
+ "bdoc": "application/bdoc",
96
+ "bin": "application/octet-stream",
97
+ "bmp": "image/bmp",
98
+ "bpk": "application/octet-stream",
99
+ "btf": "image/prs.btif",
100
+ "btif": "image/prs.btif",
101
+ "buffer": "application/octet-stream",
102
+ "ccxml": "application/ccxml+xml",
103
+ "cdfx": "application/cdfx+xml",
104
+ "cdmia": "application/cdmi-capability",
105
+ "cdmic": "application/cdmi-container",
106
+ "cdmid": "application/cdmi-domain",
107
+ "cdmio": "application/cdmi-object",
108
+ "cdmiq": "application/cdmi-queue",
109
+ "cer": "application/pkix-cert",
110
+ "cgm": "image/cgm",
111
+ "cjs": "application/node",
112
+ "class": "application/java-vm",
113
+ "coffee": "text/coffeescript",
114
+ "conf": "text/plain",
115
+ "cpl": "application/cpl+xml",
116
+ "cpt": "application/mac-compactpro",
117
+ "crl": "application/pkix-crl",
118
+ "css": "text/css",
119
+ "csv": "text/csv",
120
+ "cu": "application/cu-seeme",
121
+ "cwl": "application/cwl",
122
+ "cww": "application/prs.cww",
123
+ "davmount": "application/davmount+xml",
124
+ "dbk": "application/docbook+xml",
125
+ "deb": "application/octet-stream",
126
+ "def": "text/plain",
127
+ "deploy": "application/octet-stream",
128
+ "dib": "image/bmp",
129
+ "disposition-notification": "message/disposition-notification",
130
+ "dist": "application/octet-stream",
131
+ "distz": "application/octet-stream",
132
+ "dll": "application/octet-stream",
133
+ "dmg": "application/octet-stream",
134
+ "dms": "application/octet-stream",
135
+ "doc": "application/msword",
136
+ "dot": "application/msword",
137
+ "dpx": "image/dpx",
138
+ "drle": "image/dicom-rle",
139
+ "dsc": "text/prs.lines.tag",
140
+ "dssc": "application/dssc+der",
141
+ "dtd": "application/xml-dtd",
142
+ "dump": "application/octet-stream",
143
+ "dwd": "application/atsc-dwd+xml",
144
+ "ear": "application/java-archive",
145
+ "ecma": "application/ecmascript",
146
+ "elc": "application/octet-stream",
147
+ "emf": "image/emf",
148
+ "eml": "message/rfc822",
149
+ "emma": "application/emma+xml",
150
+ "emotionml": "application/emotionml+xml",
151
+ "eps": "application/postscript",
152
+ "epub": "application/epub+zip",
153
+ "exe": "application/octet-stream",
154
+ "exi": "application/exi",
155
+ "exp": "application/express",
156
+ "exr": "image/aces",
157
+ "ez": "application/andrew-inset",
158
+ "fdf": "application/fdf",
159
+ "fdt": "application/fdt+xml",
160
+ "fits": "image/fits",
161
+ "g3": "image/g3fax",
162
+ "gbr": "application/rpki-ghostbusters",
163
+ "geojson": "application/geo+json",
164
+ "gif": "image/gif",
165
+ "glb": "model/gltf-binary",
166
+ "gltf": "model/gltf+json",
167
+ "gml": "application/gml+xml",
168
+ "gpx": "application/gpx+xml",
169
+ "gram": "application/srgs",
170
+ "grxml": "application/srgs+xml",
171
+ "gxf": "application/gxf",
172
+ "gz": "application/gzip",
173
+ "h261": "video/h261",
174
+ "h263": "video/h263",
175
+ "h264": "video/h264",
176
+ "heic": "image/heic",
177
+ "heics": "image/heic-sequence",
178
+ "heif": "image/heif",
179
+ "heifs": "image/heif-sequence",
180
+ "hej2": "image/hej2k",
181
+ "held": "application/atsc-held+xml",
182
+ "hjson": "application/hjson",
183
+ "hlp": "application/winhlp",
184
+ "hqx": "application/mac-binhex40",
185
+ "hsj2": "image/hsj2",
186
+ "htm": "text/html",
187
+ "html": "text/html",
188
+ "ics": "text/calendar",
189
+ "ief": "image/ief",
190
+ "ifb": "text/calendar",
191
+ "iges": "model/iges",
192
+ "igs": "model/iges",
193
+ "img": "application/octet-stream",
194
+ "in": "text/plain",
195
+ "ini": "text/plain",
196
+ "ink": "application/inkml+xml",
197
+ "inkml": "application/inkml+xml",
198
+ "ipfix": "application/ipfix",
199
+ "iso": "application/octet-stream",
200
+ "its": "application/its+xml",
201
+ "jade": "text/jade",
202
+ "jar": "application/java-archive",
203
+ "jhc": "image/jphc",
204
+ "jls": "image/jls",
205
+ "jp2": "image/jp2",
206
+ "jpe": "image/jpeg",
207
+ "jpeg": "image/jpeg",
208
+ "jpf": "image/jpx",
209
+ "jpg": "image/jpeg",
210
+ "jpg2": "image/jp2",
211
+ "jpgm": "image/jpm",
212
+ "jpgv": "video/jpeg",
213
+ "jph": "image/jph",
214
+ "jpm": "image/jpm",
215
+ "jpx": "image/jpx",
216
+ "js": "text/javascript",
217
+ "json": "application/json",
218
+ "json5": "application/json5",
219
+ "jsonld": "application/ld+json",
220
+ "jsonml": "application/jsonml+json",
221
+ "jsx": "text/jsx",
222
+ "jt": "model/jt",
223
+ "jxr": "image/jxr",
224
+ "jxra": "image/jxra",
225
+ "jxrs": "image/jxrs",
226
+ "jxs": "image/jxs",
227
+ "jxsc": "image/jxsc",
228
+ "jxsi": "image/jxsi",
229
+ "jxss": "image/jxss",
230
+ "kar": "audio/midi",
231
+ "ktx": "image/ktx",
232
+ "ktx2": "image/ktx2",
233
+ "less": "text/less",
234
+ "lgr": "application/lgr+xml",
235
+ "list": "text/plain",
236
+ "litcoffee": "text/coffeescript",
237
+ "log": "text/plain",
238
+ "lostxml": "application/lost+xml",
239
+ "lrf": "application/octet-stream",
240
+ "m1v": "video/mpeg",
241
+ "m21": "application/mp21",
242
+ "m2a": "audio/mpeg",
243
+ "m2v": "video/mpeg",
244
+ "m3a": "audio/mpeg",
245
+ "m4a": "audio/mp4",
246
+ "m4p": "application/mp4",
247
+ "m4s": "video/iso.segment",
248
+ "ma": "application/mathematica",
249
+ "mads": "application/mads+xml",
250
+ "maei": "application/mmt-aei+xml",
251
+ "man": "text/troff",
252
+ "manifest": "text/cache-manifest",
253
+ "map": "application/json",
254
+ "mar": "application/octet-stream",
255
+ "markdown": "text/markdown",
256
+ "mathml": "application/mathml+xml",
257
+ "mb": "application/mathematica",
258
+ "mbox": "application/mbox",
259
+ "md": "text/markdown",
260
+ "mdx": "text/mdx",
261
+ "me": "text/troff",
262
+ "mesh": "model/mesh",
263
+ "meta4": "application/metalink4+xml",
264
+ "metalink": "application/metalink+xml",
265
+ "mets": "application/mets+xml",
266
+ "mft": "application/rpki-manifest",
267
+ "mid": "audio/midi",
268
+ "midi": "audio/midi",
269
+ "mime": "message/rfc822",
270
+ "mj2": "video/mj2",
271
+ "mjp2": "video/mj2",
272
+ "mjs": "text/javascript",
273
+ "mml": "text/mathml",
274
+ "mods": "application/mods+xml",
275
+ "mov": "video/quicktime",
276
+ "mp2": "audio/mpeg",
277
+ "mp21": "application/mp21",
278
+ "mp2a": "audio/mpeg",
279
+ "mp3": "audio/mpeg",
280
+ "mp4": "video/mp4",
281
+ "mp4a": "audio/mp4",
282
+ "mp4s": "application/mp4",
283
+ "mp4v": "video/mp4",
284
+ "mpd": "application/dash+xml",
285
+ "mpe": "video/mpeg",
286
+ "mpeg": "video/mpeg",
287
+ "mpf": "application/media-policy-dataset+xml",
288
+ "mpg": "video/mpeg",
289
+ "mpg4": "video/mp4",
290
+ "mpga": "audio/mpeg",
291
+ "mpp": "application/dash-patch+xml",
292
+ "mrc": "application/marc",
293
+ "mrcx": "application/marcxml+xml",
294
+ "ms": "text/troff",
295
+ "mscml": "application/mediaservercontrol+xml",
296
+ "msh": "model/mesh",
297
+ "msi": "application/octet-stream",
298
+ "msix": "application/msix",
299
+ "msixbundle": "application/msixbundle",
300
+ "msm": "application/octet-stream",
301
+ "msp": "application/octet-stream",
302
+ "mtl": "model/mtl",
303
+ "musd": "application/mmt-usd+xml",
304
+ "mxf": "application/mxf",
305
+ "mxmf": "audio/mobile-xmf",
306
+ "mxml": "application/xv+xml",
307
+ "n3": "text/n3",
308
+ "nb": "application/mathematica",
309
+ "nq": "application/n-quads",
310
+ "nt": "application/n-triples",
311
+ "obj": "model/obj",
312
+ "oda": "application/oda",
313
+ "oga": "audio/ogg",
314
+ "ogg": "audio/ogg",
315
+ "ogv": "video/ogg",
316
+ "ogx": "application/ogg",
317
+ "omdoc": "application/omdoc+xml",
318
+ "onepkg": "application/onenote",
319
+ "onetmp": "application/onenote",
320
+ "onetoc": "application/onenote",
321
+ "onetoc2": "application/onenote",
322
+ "opf": "application/oebps-package+xml",
323
+ "opus": "audio/ogg",
324
+ "otf": "font/otf",
325
+ "owl": "application/rdf+xml",
326
+ "oxps": "application/oxps",
327
+ "p10": "application/pkcs10",
328
+ "p7c": "application/pkcs7-mime",
329
+ "p7m": "application/pkcs7-mime",
330
+ "p7s": "application/pkcs7-signature",
331
+ "p8": "application/pkcs8",
332
+ "pdf": "application/pdf",
333
+ "pfr": "application/font-tdpfr",
334
+ "pgp": "application/pgp-encrypted",
335
+ "pkg": "application/octet-stream",
336
+ "pki": "application/pkixcmp",
337
+ "pkipath": "application/pkix-pkipath",
338
+ "pls": "application/pls+xml",
339
+ "png": "image/png",
340
+ "prc": "model/prc",
341
+ "prf": "application/pics-rules",
342
+ "provx": "application/provenance+xml",
343
+ "ps": "application/postscript",
344
+ "pskcxml": "application/pskc+xml",
345
+ "pti": "image/prs.pti",
346
+ "qt": "video/quicktime",
347
+ "raml": "application/raml+yaml",
348
+ "rapd": "application/route-apd+xml",
349
+ "rdf": "application/rdf+xml",
350
+ "relo": "application/p2p-overlay+xml",
351
+ "rif": "application/reginfo+xml",
352
+ "rl": "application/resource-lists+xml",
353
+ "rld": "application/resource-lists-diff+xml",
354
+ "rmi": "audio/midi",
355
+ "rnc": "application/relax-ng-compact-syntax",
356
+ "rng": "application/xml",
357
+ "roa": "application/rpki-roa",
358
+ "roff": "text/troff",
359
+ "rq": "application/sparql-query",
360
+ "rs": "application/rls-services+xml",
361
+ "rsat": "application/atsc-rsat+xml",
362
+ "rsd": "application/rsd+xml",
363
+ "rsheet": "application/urc-ressheet+xml",
364
+ "rss": "application/rss+xml",
365
+ "rtf": "text/rtf",
366
+ "rtx": "text/richtext",
367
+ "rusd": "application/route-usd+xml",
368
+ "s3m": "audio/s3m",
369
+ "sbml": "application/sbml+xml",
370
+ "scq": "application/scvp-cv-request",
371
+ "scs": "application/scvp-cv-response",
372
+ "sdp": "application/sdp",
373
+ "senmlx": "application/senml+xml",
374
+ "sensmlx": "application/sensml+xml",
375
+ "ser": "application/java-serialized-object",
376
+ "setpay": "application/set-payment-initiation",
377
+ "setreg": "application/set-registration-initiation",
378
+ "sgi": "image/sgi",
379
+ "sgm": "text/sgml",
380
+ "sgml": "text/sgml",
381
+ "shex": "text/shex",
382
+ "shf": "application/shf+xml",
383
+ "shtml": "text/html",
384
+ "sieve": "application/sieve",
385
+ "sig": "application/pgp-signature",
386
+ "sil": "audio/silk",
387
+ "silo": "model/mesh",
388
+ "siv": "application/sieve",
389
+ "slim": "text/slim",
390
+ "slm": "text/slim",
391
+ "sls": "application/route-s-tsid+xml",
392
+ "smi": "application/smil+xml",
393
+ "smil": "application/smil+xml",
394
+ "snd": "audio/basic",
395
+ "so": "application/octet-stream",
396
+ "spdx": "text/spdx",
397
+ "spp": "application/scvp-vp-response",
398
+ "spq": "application/scvp-vp-request",
399
+ "spx": "audio/ogg",
400
+ "sql": "application/sql",
401
+ "sru": "application/sru+xml",
402
+ "srx": "application/sparql-results+xml",
403
+ "ssdl": "application/ssdl+xml",
404
+ "ssml": "application/ssml+xml",
405
+ "stk": "application/hyperstudio",
406
+ "stl": "model/stl",
407
+ "stpx": "model/step+xml",
408
+ "stpxz": "model/step-xml+zip",
409
+ "stpz": "model/step+zip",
410
+ "styl": "text/stylus",
411
+ "stylus": "text/stylus",
412
+ "svg": "image/svg+xml",
413
+ "svgz": "image/svg+xml",
414
+ "swidtag": "application/swid+xml",
415
+ "t": "text/troff",
416
+ "t38": "image/t38",
417
+ "td": "application/urc-targetdesc+xml",
418
+ "tei": "application/tei+xml",
419
+ "teicorpus": "application/tei+xml",
420
+ "text": "text/plain",
421
+ "tfi": "application/thraud+xml",
422
+ "tfx": "image/tiff-fx",
423
+ "tif": "image/tiff",
424
+ "tiff": "image/tiff",
425
+ "toml": "application/toml",
426
+ "tr": "text/troff",
427
+ "trig": "application/trig",
428
+ "ts": "video/mp2t",
429
+ "tsd": "application/timestamped-data",
430
+ "tsv": "text/tab-separated-values",
431
+ "ttc": "font/collection",
432
+ "ttf": "font/ttf",
433
+ "ttl": "text/turtle",
434
+ "ttml": "application/ttml+xml",
435
+ "txt": "text/plain",
436
+ "u3d": "model/u3d",
437
+ "u8dsn": "message/global-delivery-status",
438
+ "u8hdr": "message/global-headers",
439
+ "u8mdn": "message/global-disposition-notification",
440
+ "u8msg": "message/global",
441
+ "ubj": "application/ubjson",
442
+ "uri": "text/uri-list",
443
+ "uris": "text/uri-list",
444
+ "urls": "text/uri-list",
445
+ "vcard": "text/vcard",
446
+ "vrml": "model/vrml",
447
+ "vtt": "text/vtt",
448
+ "vxml": "application/voicexml+xml",
449
+ "war": "application/java-archive",
450
+ "wasm": "application/wasm",
451
+ "wav": "audio/wav",
452
+ "weba": "audio/webm",
453
+ "webm": "video/webm",
454
+ "webmanifest": "application/manifest+json",
455
+ "webp": "image/webp",
456
+ "wgsl": "text/wgsl",
457
+ "wgt": "application/widget",
458
+ "wif": "application/watcherinfo+xml",
459
+ "wmf": "image/wmf",
460
+ "woff": "font/woff",
461
+ "woff2": "font/woff2",
462
+ "wrl": "model/vrml",
463
+ "wsdl": "application/wsdl+xml",
464
+ "wspolicy": "application/wspolicy+xml",
465
+ "x3d": "model/x3d+xml",
466
+ "x3db": "model/x3d+fastinfoset",
467
+ "x3dbz": "model/x3d+binary",
468
+ "x3dv": "model/x3d-vrml",
469
+ "x3dvz": "model/x3d+vrml",
470
+ "x3dz": "model/x3d+xml",
471
+ "xaml": "application/xaml+xml",
472
+ "xav": "application/xcap-att+xml",
473
+ "xca": "application/xcap-caps+xml",
474
+ "xcs": "application/calendar+xml",
475
+ "xdf": "application/xcap-diff+xml",
476
+ "xdssc": "application/dssc+xml",
477
+ "xel": "application/xcap-el+xml",
478
+ "xenc": "application/xenc+xml",
479
+ "xer": "application/patch-ops-error+xml",
480
+ "xfdf": "application/xfdf",
481
+ "xht": "application/xhtml+xml",
482
+ "xhtml": "application/xhtml+xml",
483
+ "xhvml": "application/xv+xml",
484
+ "xlf": "application/xliff+xml",
485
+ "xm": "audio/xm",
486
+ "xml": "text/xml",
487
+ "xns": "application/xcap-ns+xml",
488
+ "xop": "application/xop+xml",
489
+ "xpl": "application/xproc+xml",
490
+ "xsd": "application/xml",
491
+ "xsf": "application/prs.xsf+xml",
492
+ "xsl": "application/xml",
493
+ "xslt": "application/xml",
494
+ "xspf": "application/xspf+xml",
495
+ "xvm": "application/xv+xml",
496
+ "xvml": "application/xv+xml",
497
+ "yaml": "text/yaml",
498
+ "yang": "application/yang",
499
+ "yin": "application/yin+xml",
500
+ "yml": "text/yaml",
501
+ "zip": "application/zip"
502
+ };
503
+
504
+ function lookup(extn) {
505
+ let tmp = ('' + extn).trim().toLowerCase();
506
+ let idx = tmp.lastIndexOf('.');
507
+ return mimes[!~idx ? tmp : tmp.substring(++idx)];
508
+ }
509
+
510
+ const noop$1 = () => {};
511
+
512
+ function isMatch(uri, arr) {
513
+ for (let i=0; i < arr.length; i++) {
514
+ if (arr[i].test(uri)) return true;
515
+ }
516
+ }
517
+
518
+ function toAssume(uri, extns) {
519
+ let i=0, x, len=uri.length - 1;
520
+ if (uri.charCodeAt(len) === 47) {
521
+ uri = uri.substring(0, len);
522
+ }
523
+
524
+ let arr=[], tmp=`${uri}/index`;
525
+ for (; i < extns.length; i++) {
526
+ x = extns[i] ? `.${extns[i]}` : '';
527
+ if (uri) arr.push(uri + x);
528
+ arr.push(tmp + x);
529
+ }
530
+
531
+ return arr;
532
+ }
533
+
534
+ function viaCache(cache, uri, extns) {
535
+ let i=0, data, arr=toAssume(uri, extns);
536
+ for (; i < arr.length; i++) {
537
+ if (data = cache[arr[i]]) return data;
538
+ }
539
+ }
540
+
541
+ function viaLocal(dir, isEtag, uri, extns) {
542
+ let i=0, arr=toAssume(uri, extns);
543
+ let abs, stats, name, headers;
544
+ for (; i < arr.length; i++) {
545
+ abs = normalize(
546
+ join(dir, name=arr[i])
547
+ );
548
+
549
+ if (abs.startsWith(dir) && fs.existsSync(abs)) {
550
+ stats = fs.statSync(abs);
551
+ if (stats.isDirectory()) continue;
552
+ headers = toHeaders(name, stats, isEtag);
553
+ headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
554
+ return { abs, stats, headers };
555
+ }
556
+ }
557
+ }
558
+
559
+ function is404(req, res) {
560
+ return (res.statusCode=404,res.end());
561
+ }
562
+
563
+ function send(req, res, file, stats, headers) {
564
+ let code=200, tmp, opts={};
565
+ headers = { ...headers };
566
+
567
+ for (let key in headers) {
568
+ tmp = res.getHeader(key);
569
+ if (tmp) headers[key] = tmp;
570
+ }
571
+
572
+ if (tmp = res.getHeader('content-type')) {
573
+ headers['Content-Type'] = tmp;
574
+ }
575
+
576
+ if (req.headers.range) {
577
+ code = 206;
578
+ let [x, y] = req.headers.range.replace('bytes=', '').split('-');
579
+ let end = opts.end = parseInt(y, 10) || stats.size - 1;
580
+ let start = opts.start = parseInt(x, 10) || 0;
581
+
582
+ if (end >= stats.size) {
583
+ end = stats.size - 1;
584
+ }
585
+
586
+ if (start >= stats.size) {
587
+ res.setHeader('Content-Range', `bytes */${stats.size}`);
588
+ res.statusCode = 416;
589
+ return res.end();
590
+ }
591
+
592
+ headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
593
+ headers['Content-Length'] = (end - start + 1);
594
+ headers['Accept-Ranges'] = 'bytes';
595
+ }
596
+
597
+ res.writeHead(code, headers);
598
+ fs.createReadStream(file, opts).pipe(res);
599
+ }
600
+
601
+ const ENCODING = {
602
+ '.br': 'br',
603
+ '.gz': 'gzip',
604
+ };
605
+
606
+ function toHeaders(name, stats, isEtag) {
607
+ let enc = ENCODING[name.slice(-3)];
608
+
609
+ let ctype = lookup(name.slice(0, enc && -3)) || '';
610
+ if (ctype === 'text/html') ctype += ';charset=utf-8';
611
+
612
+ let headers = {
613
+ 'Content-Length': stats.size,
614
+ 'Content-Type': ctype,
615
+ 'Last-Modified': stats.mtime.toUTCString(),
616
+ };
617
+
618
+ if (enc) headers['Content-Encoding'] = enc;
619
+ if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
620
+
621
+ return headers;
622
+ }
623
+
624
+ function sirv (dir, opts={}) {
625
+ dir = resolve(dir || '.');
626
+
627
+ let isNotFound = opts.onNoMatch || is404;
628
+ let setHeaders = opts.setHeaders || noop$1;
629
+
630
+ let extensions = opts.extensions || ['html', 'htm'];
631
+ let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
632
+ let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
633
+
634
+ const FILES = {};
635
+
636
+ let fallback = '/';
637
+ let isEtag = !!opts.etag;
638
+ let isSPA = !!opts.single;
639
+ if (typeof opts.single === 'string') {
640
+ let idx = opts.single.lastIndexOf('.');
641
+ fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
642
+ }
643
+
644
+ let ignores = [];
645
+ if (opts.ignores !== false) {
646
+ ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
647
+ if (opts.dotfiles) ignores.push(/\/\.\w/);
648
+ else ignores.push(/\/\.well-known/);
649
+ [].concat(opts.ignores || []).forEach(x => {
650
+ ignores.push(new RegExp(x, 'i'));
651
+ });
652
+ }
653
+
654
+ let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
655
+ if (cc && opts.immutable) cc += ',immutable';
656
+ else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
657
+
658
+ if (!opts.dev) {
659
+ totalist(dir, (name, abs, stats) => {
660
+ if (/\.well-known[\\+\/]/.test(name)) ; // keep
661
+ else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
662
+
663
+ let headers = toHeaders(name, stats, isEtag);
664
+ if (cc) headers['Cache-Control'] = cc;
665
+
666
+ FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
667
+ });
668
+ }
669
+
670
+ let lookup = opts.dev ? viaLocal.bind(0, dir + sep, isEtag) : viaCache.bind(0, FILES);
671
+
672
+ return function (req, res, next) {
673
+ let extns = [''];
674
+ let pathname = parse$1(req).pathname;
675
+ let val = req.headers['accept-encoding'] || '';
676
+ if (gzips && val.includes('gzip')) extns.unshift(...gzips);
677
+ if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
678
+ extns.push(...extensions); // [...br, ...gz, orig, ...exts]
679
+
680
+ if (pathname.indexOf('%') !== -1) {
681
+ try { pathname = decodeURI(pathname); }
682
+ catch (err) { /* malform uri */ }
683
+ }
684
+
685
+ let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
686
+ if (!data) return next ? next() : isNotFound(req, res);
687
+
688
+ if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
689
+ res.writeHead(304);
690
+ return res.end();
691
+ }
692
+
693
+ if (gzips || brots) {
694
+ res.setHeader('Vary', 'Accept-Encoding');
695
+ }
696
+
697
+ setHeaders(res, pathname, data.stats);
698
+ send(req, res, data.abs, data.stats, data.headers);
699
+ };
700
+ }
701
+
702
+ /**
703
+ * @param {string|RegExp} input The route pattern
704
+ * @param {boolean} [loose] Allow open-ended matching. Ignored with `RegExp` input.
705
+ */
706
+ function parse(input, loose) {
707
+ if (input instanceof RegExp) return { keys:false, pattern:input };
708
+ var c, o, tmp, ext, keys=[], pattern='', arr = input.split('/');
709
+ arr[0] || arr.shift();
710
+
711
+ while (tmp = arr.shift()) {
712
+ c = tmp[0];
713
+ if (c === '*') {
714
+ keys.push(c);
715
+ pattern += tmp[1] === '?' ? '(?:/(.*))?' : '/(.*)';
716
+ } else if (c === ':') {
717
+ o = tmp.indexOf('?', 1);
718
+ ext = tmp.indexOf('.', 1);
719
+ keys.push( tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length) );
720
+ pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';
721
+ if (!!~ext) pattern += (!!~o ? '?' : '') + '\\' + tmp.substring(ext);
722
+ } else {
723
+ pattern += '/' + tmp;
724
+ }
725
+ }
726
+
727
+ return {
728
+ keys: keys,
729
+ pattern: new RegExp('^' + pattern + (loose ? '(?=$|\/)' : '\/?$'), 'i')
730
+ };
731
+ }
732
+
733
+ const MAP = {
734
+ "": 0,
735
+ GET: 1,
736
+ HEAD: 2,
737
+ PATCH: 3,
738
+ OPTIONS: 4,
739
+ CONNECT: 5,
740
+ DELETE: 6,
741
+ TRACE: 7,
742
+ POST: 8,
743
+ PUT: 9,
744
+ };
745
+
746
+ class Trouter {
747
+ constructor() {
748
+ this.routes = [];
749
+
750
+ this.all = this.add.bind(this, '');
751
+ this.get = this.add.bind(this, 'GET');
752
+ this.head = this.add.bind(this, 'HEAD');
753
+ this.patch = this.add.bind(this, 'PATCH');
754
+ this.options = this.add.bind(this, 'OPTIONS');
755
+ this.connect = this.add.bind(this, 'CONNECT');
756
+ this.delete = this.add.bind(this, 'DELETE');
757
+ this.trace = this.add.bind(this, 'TRACE');
758
+ this.post = this.add.bind(this, 'POST');
759
+ this.put = this.add.bind(this, 'PUT');
760
+ }
761
+
762
+ use(route, ...fns) {
763
+ let handlers = [].concat.apply([], fns);
764
+ let { keys, pattern } = parse(route, true);
765
+ this.routes.push({ keys, pattern, method: '', handlers, midx: MAP[''] });
766
+ return this;
767
+ }
768
+
769
+ add(method, route, ...fns) {
770
+ let { keys, pattern } = parse(route);
771
+ let handlers = [].concat.apply([], fns);
772
+ this.routes.push({ keys, pattern, method, handlers, midx: MAP[method] });
773
+ return this;
774
+ }
775
+
776
+ find(method, url) {
777
+ let midx = MAP[method];
778
+ let isHEAD = (midx === 2);
779
+ let i=0, j=0, k, tmp, arr=this.routes;
780
+ let matches=[], params={}, handlers=[];
781
+ for (; i < arr.length; i++) {
782
+ tmp = arr[i];
783
+ if (tmp.midx === midx || tmp.midx === 0 || (isHEAD && tmp.midx===1) ) {
784
+ if (tmp.keys === false) {
785
+ matches = tmp.pattern.exec(url);
786
+ if (matches === null) continue;
787
+ if (matches.groups !== void 0) for (k in matches.groups) params[k]=matches.groups[k];
788
+ tmp.handlers.length > 1 ? (handlers=handlers.concat(tmp.handlers)) : handlers.push(tmp.handlers[0]);
789
+ } else if (tmp.keys.length > 0) {
790
+ matches = tmp.pattern.exec(url);
791
+ if (matches === null) continue;
792
+ for (j=0; j < tmp.keys.length;) params[tmp.keys[j]]=matches[++j];
793
+ tmp.handlers.length > 1 ? (handlers=handlers.concat(tmp.handlers)) : handlers.push(tmp.handlers[0]);
794
+ } else if (tmp.pattern.test(url)) {
795
+ tmp.handlers.length > 1 ? (handlers=handlers.concat(tmp.handlers)) : handlers.push(tmp.handlers[0]);
796
+ }
797
+ } // else not a match
798
+ }
799
+
800
+ return { params, handlers };
801
+ }
802
+ }
803
+
804
+ function onError(err, req, res) {
805
+ let code = typeof err.status === 'number' && err.status;
806
+ code = res.statusCode = (code && code >= 100 ? code : 500);
807
+ if (typeof err === 'string' || Buffer.isBuffer(err)) res.end(err);
808
+ else res.end(err.message || http.STATUS_CODES[code]);
809
+ }
810
+
811
+ const mount = fn => fn instanceof Polka ? fn.attach : fn;
812
+
813
+ class Polka extends Trouter {
814
+ constructor(opts={}) {
815
+ super();
816
+ this.parse = parse$1;
817
+ this.server = opts.server;
818
+ this.handler = this.handler.bind(this);
819
+ this.onError = opts.onError || onError; // catch-all handler
820
+ this.onNoMatch = opts.onNoMatch || this.onError.bind(null, { status: 404 });
821
+ this.attach = (req, res) => setImmediate(this.handler, req, res);
822
+ }
823
+
824
+ use(base, ...fns) {
825
+ if (base === '/') {
826
+ super.use(base, fns.map(mount));
827
+ } else if (typeof base === 'function' || base instanceof Polka) {
828
+ super.use('/', [base, ...fns].map(mount));
829
+ } else {
830
+ super.use(base,
831
+ (req, _, next) => {
832
+ if (typeof base === 'string') {
833
+ let len = base.length;
834
+ base.startsWith('/') || len++;
835
+ req.url = req.url.substring(len) || '/';
836
+ req.path = req.path.substring(len) || '/';
837
+ } else {
838
+ req.url = req.url.replace(base, '') || '/';
839
+ req.path = req.path.replace(base, '') || '/';
840
+ }
841
+ if (req.url.charAt(0) !== '/') {
842
+ req.url = '/' + req.url;
843
+ }
844
+ next();
845
+ },
846
+ fns.map(mount),
847
+ (req, _, next) => {
848
+ req.path = req._parsedUrl.pathname;
849
+ req.url = req.path + req._parsedUrl.search;
850
+ next();
851
+ }
852
+ );
853
+ }
854
+ return this; // chainable
855
+ }
856
+
857
+ listen() {
858
+ (this.server = this.server || http.createServer()).on('request', this.attach);
859
+ this.server.listen.apply(this.server, arguments);
860
+ return this;
861
+ }
862
+
863
+ handler(req, res, next) {
864
+ let info = this.parse(req), path = info.pathname;
865
+ let obj = this.find(req.method, req.path=path);
866
+
867
+ req.url = path + info.search;
868
+ req.originalUrl = req.originalUrl || req.url;
869
+ req.query = info.query || {};
870
+ req.search = info.search;
871
+ req.params = obj.params;
872
+
873
+ if (path.length > 1 && path.indexOf('%', 1) !== -1) {
874
+ for (let k in req.params) {
875
+ try { req.params[k] = decodeURIComponent(req.params[k]); }
876
+ catch (e) { /* malform uri segment */ }
877
+ }
878
+ }
879
+
880
+ let i=0, arr=obj.handlers.concat(this.onNoMatch), len=arr.length;
881
+ let loop = async () => res.finished || (i < len) && arr[i++](req, res, next);
882
+ (next = next || (err => err ? this.onError(err, req, res, next) : loop().catch(next)))(); // init
883
+ }
884
+ }
885
+
886
+ function polka (opts) {
887
+ return new Polka(opts);
888
+ }
889
+
890
+ function noop() {}
891
+
892
+ var defaultParseOptions = {
893
+ decodeValues: true,
894
+ map: false,
895
+ silent: false,
896
+ split: "auto", // auto = split strings but not arrays
897
+ };
898
+
899
+ function isForbiddenKey(key) {
900
+ return typeof key !== "string" || key in {};
901
+ }
902
+
903
+ function createNullObj() {
904
+ return Object.create(null);
905
+ }
906
+
907
+ function isNonEmptyString(str) {
908
+ return typeof str === "string" && !!str.trim();
909
+ }
910
+
911
+ function parseString(setCookieValue, options) {
912
+ var parts = setCookieValue.split(";").filter(isNonEmptyString);
913
+
914
+ var nameValuePairStr = parts.shift();
915
+ if (!nameValuePairStr) {
916
+ return null;
917
+ }
918
+ var parsed = parseNameValuePair(nameValuePairStr);
919
+ var name = parsed.name;
920
+ var value = parsed.value;
921
+
922
+ options = options
923
+ ? Object.assign({}, defaultParseOptions, options)
924
+ : defaultParseOptions;
925
+
926
+ if (isForbiddenKey(name)) {
927
+ return null;
928
+ }
929
+
930
+ try {
931
+ value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
932
+ } catch (e) {
933
+ console.error(
934
+ "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",
935
+ e
936
+ );
937
+ }
938
+
939
+ var cookie = createNullObj();
940
+ cookie.name = name;
941
+ cookie.value = value;
942
+
943
+ parts.forEach(function (part) {
944
+ var sides = part.split("=");
945
+ var key = sides.shift().trim().toLowerCase();
946
+ if (isForbiddenKey(key)) {
947
+ return;
948
+ }
949
+ var value = sides.join("=").trim();
950
+ if (key === "expires") {
951
+ cookie.expires = new Date(value);
952
+ } else if (key === "max-age") {
953
+ var n = parseInt(value, 10);
954
+ if (!Number.isNaN(n)) cookie.maxAge = n;
955
+ } else if (key === "secure") {
956
+ cookie.secure = true;
957
+ } else if (key === "httponly") {
958
+ cookie.httpOnly = true;
959
+ } else if (key === "samesite") {
960
+ cookie.sameSite = value;
961
+ } else if (key === "partitioned") {
962
+ cookie.partitioned = true;
963
+ } else if (key) {
964
+ cookie[key] = value;
965
+ }
966
+ });
967
+
968
+ return cookie;
969
+ }
970
+
971
+ function parseNameValuePair(nameValuePairStr) {
972
+ // Parses name-value-pair according to rfc6265bis draft
973
+
974
+ var name = "";
975
+ var value = "";
976
+ var nameValueArr = nameValuePairStr.split("=");
977
+ if (nameValueArr.length > 1) {
978
+ name = nameValueArr.shift();
979
+ value = nameValueArr.join("="); // everything after the first =, joined by a "=" if there was more than one part
980
+ } else {
981
+ value = nameValuePairStr;
982
+ }
983
+
984
+ return { name: name, value: value };
985
+ }
986
+
987
+ function parseSetCookie(input, options) {
988
+ options = options
989
+ ? Object.assign({}, defaultParseOptions, options)
990
+ : defaultParseOptions;
991
+
992
+ if (!input) {
993
+ if (!options.map) {
994
+ return [];
995
+ } else {
996
+ return createNullObj();
997
+ }
998
+ }
999
+
1000
+ if (input.headers) {
1001
+ if (typeof input.headers.getSetCookie === "function") {
1002
+ // for fetch responses - they combine headers of the same type in the headers array,
1003
+ // but getSetCookie returns an uncombined array
1004
+ input = input.headers.getSetCookie();
1005
+ } else if (input.headers["set-cookie"]) {
1006
+ // fast-path for node.js (which automatically normalizes header names to lower-case)
1007
+ input = input.headers["set-cookie"];
1008
+ } else {
1009
+ // slow-path for other environments - see #25
1010
+ var sch =
1011
+ input.headers[
1012
+ Object.keys(input.headers).find(function (key) {
1013
+ return key.toLowerCase() === "set-cookie";
1014
+ })
1015
+ ];
1016
+ // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
1017
+ if (!sch && input.headers.cookie && !options.silent) {
1018
+ console.warn(
1019
+ "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
1020
+ );
1021
+ }
1022
+ input = sch;
1023
+ }
1024
+ }
1025
+
1026
+ var split = options.split;
1027
+ var isArray = Array.isArray(input);
1028
+
1029
+ if (split === "auto") {
1030
+ split = !isArray;
1031
+ }
1032
+
1033
+ if (!isArray) {
1034
+ input = [input];
1035
+ }
1036
+
1037
+ input = input.filter(isNonEmptyString);
1038
+
1039
+ if (split) {
1040
+ input = input.map(splitCookiesString).flat();
1041
+ }
1042
+
1043
+ if (!options.map) {
1044
+ return input
1045
+ .map(function (str) {
1046
+ return parseString(str, options);
1047
+ })
1048
+ .filter(Boolean);
1049
+ } else {
1050
+ var cookies = createNullObj();
1051
+ return input.reduce(function (cookies, str) {
1052
+ var cookie = parseString(str, options);
1053
+ if (cookie && !isForbiddenKey(cookie.name)) {
1054
+ cookies[cookie.name] = cookie;
1055
+ }
1056
+ return cookies;
1057
+ }, cookies);
1058
+ }
1059
+ }
1060
+
1061
+ /*
1062
+ Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
1063
+ that are within a single set-cookie field-value, such as in the Expires portion.
1064
+
1065
+ This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
1066
+ Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
1067
+ React Native's fetch does this for *every* header, including set-cookie.
1068
+
1069
+ Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
1070
+ Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
1071
+ */
1072
+ function splitCookiesString(cookiesString) {
1073
+ if (Array.isArray(cookiesString)) {
1074
+ return cookiesString;
1075
+ }
1076
+ if (typeof cookiesString !== "string") {
1077
+ return [];
1078
+ }
1079
+
1080
+ var cookiesStrings = [];
1081
+ var pos = 0;
1082
+ var start;
1083
+ var ch;
1084
+ var lastComma;
1085
+ var nextStart;
1086
+ var cookiesSeparatorFound;
1087
+
1088
+ function skipWhitespace() {
1089
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
1090
+ pos += 1;
1091
+ }
1092
+ return pos < cookiesString.length;
1093
+ }
1094
+
1095
+ function notSpecialChar() {
1096
+ ch = cookiesString.charAt(pos);
1097
+
1098
+ return ch !== "=" && ch !== ";" && ch !== ",";
1099
+ }
1100
+
1101
+ while (pos < cookiesString.length) {
1102
+ start = pos;
1103
+ cookiesSeparatorFound = false;
1104
+
1105
+ while (skipWhitespace()) {
1106
+ ch = cookiesString.charAt(pos);
1107
+ if (ch === ",") {
1108
+ // ',' is a cookie separator if we have later first '=', not ';' or ','
1109
+ lastComma = pos;
1110
+ pos += 1;
1111
+
1112
+ skipWhitespace();
1113
+ nextStart = pos;
1114
+
1115
+ while (pos < cookiesString.length && notSpecialChar()) {
1116
+ pos += 1;
1117
+ }
1118
+
1119
+ // currently special character
1120
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
1121
+ // we found cookies separator
1122
+ cookiesSeparatorFound = true;
1123
+ // pos is inside the next cookie, so back up and return it.
1124
+ pos = nextStart;
1125
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
1126
+ start = pos;
1127
+ } else {
1128
+ // in param ',' or param separator ';',
1129
+ // we continue from that comma
1130
+ pos = lastComma + 1;
1131
+ }
1132
+ } else {
1133
+ pos += 1;
1134
+ }
1135
+ }
1136
+
1137
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
1138
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
1139
+ }
1140
+ }
1141
+
1142
+ return cookiesStrings;
1143
+ }
1144
+
1145
+ // named export for CJS
1146
+ parseSetCookie.parseSetCookie = parseSetCookie;
1147
+ // for backwards compatibility
1148
+ parseSetCookie.parse = parseSetCookie;
1149
+ parseSetCookie.parseString = parseString;
1150
+ parseSetCookie.splitCookiesString = splitCookiesString;
1151
+
1152
+ /** @import { RemoteForm } from '@sveltejs/kit' */
1153
+ /** @import { BinaryFormMeta, InternalRemoteFormIssue } from 'types' */
1154
+ /** @import { StandardSchemaV1 } from '@standard-schema/spec' */
1155
+
1156
+
1157
+ new TextDecoder();
1158
+
1159
+ /**
1160
+ * Reads all `Set-Cookie` headers as separate values. `Headers.get('set-cookie')`
1161
+ * collapses them into a single comma-joined string that browsers cannot parse, so
1162
+ * we use `Headers.getSetCookie()` where available and fall back to splitting the
1163
+ * joined string otherwise.
1164
+ *
1165
+ * TODO 3.0 `getSetCookie` is available in Node 19.7+; once we drop support for
1166
+ * older versions we can use it directly and remove the `splitCookiesString` fallback
1167
+ * @param {Headers} headers
1168
+ * @returns {string[]}
1169
+ */
1170
+ function get_set_cookies(headers) {
1171
+ if (typeof headers.getSetCookie === 'function') {
1172
+ return headers.getSetCookie();
1173
+ }
1174
+
1175
+ const set_cookie = headers.get('set-cookie');
1176
+ return set_cookie ? splitCookiesString(set_cookie) : [];
1177
+ }
1178
+
1179
+ /**
1180
+ * @param {import('http').IncomingMessage} req
1181
+ * @param {number} [body_size_limit]
1182
+ */
1183
+ function get_raw_body(req, body_size_limit) {
1184
+ const h = req.headers;
1185
+
1186
+ if (!h['content-type']) {
1187
+ return null;
1188
+ }
1189
+
1190
+ const content_length = Number(h['content-length']);
1191
+ const has_content_length = Number.isFinite(content_length);
1192
+
1193
+ // check if no request body
1194
+ if (
1195
+ (req.httpVersionMajor === 1 && !has_content_length && h['transfer-encoding'] == null) ||
1196
+ content_length === 0
1197
+ ) {
1198
+ return null;
1199
+ }
1200
+
1201
+ if (req.destroyed) {
1202
+ const readable = new ReadableStream();
1203
+ void readable.cancel();
1204
+ return readable;
1205
+ }
1206
+
1207
+ let size = 0;
1208
+ let cancelled = false;
1209
+
1210
+ return new ReadableStream({
1211
+ start(controller) {
1212
+ if (body_size_limit !== undefined && has_content_length && content_length > body_size_limit) {
1213
+ let message = `Content-length of ${content_length} exceeds limit of ${body_size_limit} bytes.`;
1214
+
1215
+ if (body_size_limit === 0) {
1216
+ // https://github.com/sveltejs/kit/pull/11589
1217
+ // TODO this exists to aid migration — remove in a future version
1218
+ message += ' To disable body size limits, specify Infinity rather than 0.';
1219
+ }
1220
+
1221
+ const error = new SvelteKitError(413, 'Payload Too Large', message);
1222
+
1223
+ controller.error(error);
1224
+ return;
1225
+ }
1226
+
1227
+ req.on('error', (error) => {
1228
+ cancelled = true;
1229
+ controller.error(error);
1230
+ });
1231
+
1232
+ req.on('end', () => {
1233
+ if (cancelled) return;
1234
+ controller.close();
1235
+ });
1236
+
1237
+ req.on('data', (chunk) => {
1238
+ if (cancelled) return;
1239
+
1240
+ size += chunk.length;
1241
+
1242
+ if (body_size_limit !== undefined && size > body_size_limit) {
1243
+ cancelled = true;
1244
+
1245
+ const message = `request body size exceeded BODY_SIZE_LIMIT of ${body_size_limit}`;
1246
+
1247
+ const error = new SvelteKitError(413, 'Payload Too Large', message);
1248
+ controller.error(error);
1249
+
1250
+ return;
1251
+ }
1252
+
1253
+ if (has_content_length && size > content_length) {
1254
+ cancelled = true;
1255
+
1256
+ const message = `request body size exceeded content-length of ${content_length}`;
1257
+
1258
+ const error = new SvelteKitError(413, 'Payload Too Large', message);
1259
+ controller.error(error);
1260
+
1261
+ return;
1262
+ }
1263
+
1264
+ controller.enqueue(chunk);
1265
+
1266
+ if (controller.desiredSize === null || controller.desiredSize <= 0) {
1267
+ req.pause();
1268
+ }
1269
+ });
1270
+ },
1271
+
1272
+ pull() {
1273
+ req.resume();
1274
+ },
1275
+
1276
+ cancel(reason) {
1277
+ cancelled = true;
1278
+ req.destroy(reason);
1279
+ }
1280
+ });
1281
+ }
1282
+
1283
+ /**
1284
+ * @param {{
1285
+ * request: import('http').IncomingMessage;
1286
+ * base: string;
1287
+ * bodySizeLimit?: number;
1288
+ * }} options
1289
+ * @returns {Promise<Request>}
1290
+ */
1291
+ // TODO 3.0 make the signature synchronous?
1292
+ // eslint-disable-next-line @typescript-eslint/require-await
1293
+ async function getRequest({ request, base, bodySizeLimit }) {
1294
+ let headers = /** @type {Record<string, string>} */ (request.headers);
1295
+ if (request.httpVersionMajor >= 2) {
1296
+ // the Request constructor rejects headers with ':' in the name
1297
+ headers = Object.assign({}, headers);
1298
+ // https://www.rfc-editor.org/rfc/rfc9113.html#section-8.3.1-2.3.5
1299
+ if (headers[':authority']) {
1300
+ headers.host = headers[':authority'];
1301
+ }
1302
+ delete headers[':authority'];
1303
+ delete headers[':method'];
1304
+ delete headers[':path'];
1305
+ delete headers[':scheme'];
1306
+ }
1307
+
1308
+ // TODO: Whenever Node >=22 is minimum supported version, we can use `request.readableAborted`
1309
+ // @see https://github.com/nodejs/node/blob/5cf3c3e24c7257a0c6192ed8ef71efec8ddac22b/lib/internal/streams/readable.js#L1443-L1453
1310
+ const controller = new AbortController();
1311
+ let errored = false;
1312
+ let end_emitted = false;
1313
+ request.once('error', () => (errored = true));
1314
+ request.once('end', () => (end_emitted = true));
1315
+ request.once('close', () => {
1316
+ if ((errored || request.destroyed) && !end_emitted) {
1317
+ controller.abort();
1318
+ }
1319
+ });
1320
+
1321
+ return new Request(base + request.url, {
1322
+ // @ts-expect-error
1323
+ duplex: 'half',
1324
+ method: request.method,
1325
+ headers: Object.entries(headers),
1326
+ signal: controller.signal,
1327
+ body:
1328
+ request.method === 'GET' || request.method === 'HEAD'
1329
+ ? undefined
1330
+ : get_raw_body(request, bodySizeLimit)
1331
+ });
1332
+ }
1333
+
1334
+ /**
1335
+ * @param {import('http').ServerResponse} res
1336
+ * @param {Response} response
1337
+ * @returns {Promise<void>}
1338
+ */
1339
+ // TODO 3.0 make the signature synchronous?
1340
+ // eslint-disable-next-line @typescript-eslint/require-await
1341
+ async function setResponse(res, response) {
1342
+ for (const [key, value] of response.headers) {
1343
+ try {
1344
+ res.setHeader(key, key === 'set-cookie' ? get_set_cookies(response.headers) : value);
1345
+ } catch (error) {
1346
+ res.getHeaderNames().forEach((name) => res.removeHeader(name));
1347
+ res.writeHead(500).end(String(error));
1348
+ return;
1349
+ }
1350
+ }
1351
+
1352
+ res.writeHead(response.status);
1353
+
1354
+ if (!response.body) {
1355
+ res.end();
1356
+ return;
1357
+ }
1358
+
1359
+ if (response.body.locked) {
1360
+ res.end(
1361
+ 'Fatal error: Response body is locked. ' +
1362
+ "This can happen when the response was already read (for example through 'response.json()' or 'response.text()')."
1363
+ );
1364
+ return;
1365
+ }
1366
+
1367
+ const reader = response.body.getReader();
1368
+
1369
+ if (res.destroyed) {
1370
+ void reader.cancel();
1371
+ return;
1372
+ }
1373
+
1374
+ const cancel = (/** @type {Error|undefined} */ error) => {
1375
+ res.off('close', cancel);
1376
+ res.off('error', cancel);
1377
+
1378
+ // If the reader has already been interrupted with an error earlier,
1379
+ // then it will appear here, it is useless, but it needs to be catch.
1380
+ reader.cancel(error).catch(noop);
1381
+ if (error) res.destroy(error);
1382
+ };
1383
+
1384
+ res.on('close', cancel);
1385
+ res.on('error', cancel);
1386
+
1387
+ void next();
1388
+ async function next() {
1389
+ try {
1390
+ for (;;) {
1391
+ const { done, value } = await reader.read();
1392
+
1393
+ if (done) break;
1394
+
1395
+ if (!res.write(value)) {
1396
+ res.once('drain', next);
1397
+ return;
1398
+ }
1399
+ }
1400
+ res.end();
1401
+ } catch (error) {
1402
+ cancel(error instanceof Error ? error : new Error(String(error)));
1403
+ }
1404
+ }
1405
+ }
1406
+
1407
+ /**
1408
+ * Converts a file on disk to a readable stream
1409
+ * @param {string} file
1410
+ * @returns {ReadableStream}
1411
+ * @since 2.4.0
1412
+ */
1413
+ function createReadableStream(file) {
1414
+ return /** @type {ReadableStream} */ (Readable.toWeb(createReadStream(file)));
1415
+ }
1416
+
1417
+ /**
1418
+ * Parses the given value into number of bytes.
1419
+ *
1420
+ * @param {string} value - Size in bytes. Can also be specified with a unit suffix kilobytes (K), megabytes (M), or gigabytes (G).
1421
+ * @returns {number}
1422
+ */
1423
+ function parse_as_bytes(value) {
1424
+ const multiplier =
1425
+ {
1426
+ K: 1024,
1427
+ M: 1024 * 1024,
1428
+ G: 1024 * 1024 * 1024
1429
+ }[value[value.length - 1]?.toUpperCase()] ?? 1;
1430
+ return Number(multiplier != 1 ? value.substring(0, value.length - 1) : value) * multiplier;
1431
+ }
1432
+
1433
+ /**
1434
+ * Parses and validates an origin URL.
1435
+ *
1436
+ * @param {string | undefined} value - Origin URL with http:// or https:// protocol
1437
+ * @returns {string | undefined} The validated origin, or undefined if value is undefined
1438
+ * @throws {Error} If value is provided but invalid
1439
+ */
1440
+ function parse_origin(value) {
1441
+ if (value === undefined) {
1442
+ return undefined;
1443
+ }
1444
+
1445
+ const trimmed = value.trim();
1446
+
1447
+ let url;
1448
+ try {
1449
+ url = new URL(trimmed);
1450
+ } catch (error) {
1451
+ throw new Error(
1452
+ `Invalid ORIGIN: '${trimmed}'. ` +
1453
+ `ORIGIN must be a valid URL with http:// or https:// protocol. ` +
1454
+ `For example: 'http://localhost:3000' or 'https://my.site'`,
1455
+ { cause: error }
1456
+ );
1457
+ }
1458
+
1459
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
1460
+ throw new Error(
1461
+ `Invalid ORIGIN: '${trimmed}'. ` +
1462
+ `Only http:// and https:// protocols are supported. ` +
1463
+ `Received protocol: ${url.protocol}`
1464
+ );
1465
+ }
1466
+
1467
+ return url.origin;
1468
+ }
1469
+
1470
+ /**
1471
+ * Formats the address the server is listening on.
1472
+ *
1473
+ * @param {string | false} path
1474
+ * @param {string} host
1475
+ * @param {string | false} port
1476
+ * @param {import('node:net').AddressInfo | string | null} address
1477
+ * @returns {string}
1478
+ */
1479
+ function format_listening_address(path, host, port, address) {
1480
+ if (path) {
1481
+ return path;
1482
+ }
1483
+
1484
+ if (address && typeof address === 'object') {
1485
+ return format({
1486
+ protocol: 'http:',
1487
+ hostname: address.address,
1488
+ port: address.port
1489
+ });
1490
+ }
1491
+
1492
+ return format({
1493
+ protocol: 'http:',
1494
+ hostname: host,
1495
+ port: String(port)
1496
+ });
1497
+ }
1498
+
1499
+ const prerendered = new Set([]);
1500
+
1501
+ const server = new Server(manifest);
1502
+
1503
+ // parse_origin validates ORIGIN and throws descriptive errors for invalid values
1504
+ const origin = parse_origin(env('ORIGIN', undefined));
1505
+
1506
+ const xff_depth = parseInt(env('XFF_DEPTH', '1'));
1507
+ const address_header = env('ADDRESS_HEADER', '').toLowerCase();
1508
+ const protocol_header = env('PROTOCOL_HEADER', '').toLowerCase();
1509
+ const host_header = env('HOST_HEADER', '').toLowerCase();
1510
+ const port_header = env('PORT_HEADER', '').toLowerCase();
1511
+
1512
+ const body_size_limit = parse_as_bytes(env('BODY_SIZE_LIMIT', '512K'));
1513
+
1514
+ if (isNaN(body_size_limit)) {
1515
+ throw new Error(
1516
+ `Invalid BODY_SIZE_LIMIT: '${env('BODY_SIZE_LIMIT')}'. Please provide a numeric value.`
1517
+ );
1518
+ }
1519
+
1520
+ const asset_dir = `${dir}/client${""}`;
1521
+
1522
+ await server.init({
1523
+ env: /** @type {Record<string, string>} */ (process.env),
1524
+ read: (file) => createReadableStream(`${asset_dir}/${file}`)
1525
+ });
1526
+
1527
+ /**
1528
+ * @param {string} path
1529
+ * @param {boolean} client
1530
+ */
1531
+ function serve(path, client = false) {
1532
+ return fs__default.existsSync(path)
1533
+ ? sirv(path, {
1534
+ etag: true,
1535
+ gzip: false,
1536
+ brotli: false,
1537
+ setHeaders: client
1538
+ ? (res, pathname) => {
1539
+ // only apply to build directory, not e.g. version.json
1540
+ if (
1541
+ pathname.startsWith(`/${manifest.appPath}/immutable/`) &&
1542
+ res.statusCode === 200
1543
+ ) {
1544
+ res.setHeader('cache-control', 'public,max-age=31536000,immutable');
1545
+ }
1546
+ }
1547
+ : undefined
1548
+ })
1549
+ : undefined;
1550
+ }
1551
+
1552
+ // required because the static file server ignores trailing slashes
1553
+ /** @returns {import('polka').Middleware} */
1554
+ function serve_prerendered() {
1555
+ const handler = serve(path.join(dir, 'prerendered'));
1556
+
1557
+ return (req, res, next) => {
1558
+ let { pathname, search, query } = parse$1(req);
1559
+
1560
+ try {
1561
+ pathname = decodeURIComponent(pathname);
1562
+ } catch {
1563
+ // ignore invalid URI
1564
+ }
1565
+
1566
+ if (prerendered.has(pathname)) {
1567
+ return handler?.(req, res, next);
1568
+ }
1569
+
1570
+ // remove or add trailing slash as appropriate
1571
+ let location = pathname.at(-1) === '/' ? pathname.slice(0, -1) : pathname + '/';
1572
+ if (prerendered.has(location)) {
1573
+ if (query) location += search;
1574
+ res.writeHead(308, { location }).end();
1575
+ } else {
1576
+ void next();
1577
+ }
1578
+ };
1579
+ }
1580
+
1581
+ /** @type {import('polka').Middleware} */
1582
+ const ssr = async (req, res) => {
1583
+ /** @type {Request} */
1584
+ let request;
1585
+
1586
+ try {
1587
+ request = await getRequest({
1588
+ base: origin || get_origin(req.headers),
1589
+ request: req,
1590
+ bodySizeLimit: body_size_limit
1591
+ });
1592
+ } catch {
1593
+ res.statusCode = 400;
1594
+ res.end('Bad Request');
1595
+ return;
1596
+ }
1597
+
1598
+ const response = await server.respond(request, {
1599
+ platform: { req },
1600
+ getClientAddress: () => {
1601
+ if (address_header) {
1602
+ if (!(address_header in req.headers)) {
1603
+ throw new Error(
1604
+ `Address header was specified with ${
1605
+ env_prefix + 'ADDRESS_HEADER'
1606
+ }=${address_header} but is absent from request`
1607
+ );
1608
+ }
1609
+
1610
+ const value = /** @type {string} */ (req.headers[address_header]) || '';
1611
+
1612
+ if (address_header === 'x-forwarded-for') {
1613
+ const addresses = value.split(',');
1614
+
1615
+ if (xff_depth < 1) {
1616
+ throw new Error(`${env_prefix + 'XFF_DEPTH'} must be a positive integer`);
1617
+ }
1618
+
1619
+ if (xff_depth > addresses.length) {
1620
+ throw new Error(
1621
+ `${env_prefix + 'XFF_DEPTH'} is ${xff_depth}, but only found ${
1622
+ addresses.length
1623
+ } addresses`
1624
+ );
1625
+ }
1626
+ return addresses[addresses.length - xff_depth].trim();
1627
+ }
1628
+
1629
+ return value;
1630
+ }
1631
+
1632
+ return (
1633
+ req.connection?.remoteAddress ||
1634
+ // @ts-expect-error
1635
+ req.connection?.socket?.remoteAddress ||
1636
+ req.socket?.remoteAddress ||
1637
+ // @ts-expect-error
1638
+ req.info?.remoteAddress
1639
+ );
1640
+ }
1641
+ });
1642
+
1643
+ // Reverse proxies such as nginx buffer responses by default (ignoring
1644
+ // `cache-control`), which breaks streaming responses like server-sent events.
1645
+ // `X-Accel-Buffering: no` opts out of that buffering and is a no-op on proxies
1646
+ // that don't recognise it. See https://github.com/sveltejs/kit/issues/15790
1647
+ if (response.headers.get('content-type') === 'text/event-stream') {
1648
+ response.headers.set('x-accel-buffering', 'no');
1649
+ }
1650
+
1651
+ await setResponse(res, response);
1652
+ };
1653
+
1654
+ /** @param {import('polka').Middleware[]} handlers */
1655
+ function sequence(handlers) {
1656
+ /** @type {import('polka').Middleware} */
1657
+ return (req, res, next) => {
1658
+ /**
1659
+ * @param {number} i
1660
+ * @returns {ReturnType<import('polka').Middleware>}
1661
+ */
1662
+ function handle(i) {
1663
+ if (i < handlers.length) {
1664
+ return handlers[i](req, res, () => handle(i + 1));
1665
+ } else {
1666
+ return next();
1667
+ }
1668
+ }
1669
+
1670
+ return handle(0);
1671
+ };
1672
+ }
1673
+
1674
+ /**
1675
+ * @param {string} name
1676
+ * @param {string | string[] | undefined} value
1677
+ * @returns {string | undefined}
1678
+ */
1679
+ function normalise_header(name, value) {
1680
+ if (!name) return undefined;
1681
+ if (Array.isArray(value)) {
1682
+ if (value.length === 0) return undefined;
1683
+ if (value.length === 1) return value[0];
1684
+ throw new Error(
1685
+ `Multiple values provided for ${name} header where only one expected: ${value}`
1686
+ );
1687
+ }
1688
+ return value;
1689
+ }
1690
+
1691
+ /**
1692
+ * @param {import('http').IncomingHttpHeaders} headers
1693
+ * @returns {string}
1694
+ */
1695
+ function get_origin(headers) {
1696
+ const protocol = decodeURIComponent(
1697
+ normalise_header(protocol_header, headers[protocol_header]) || 'https'
1698
+ );
1699
+
1700
+ // this helps us avoid host injections through the protocol header
1701
+ if (protocol.includes(':')) {
1702
+ throw new Error(
1703
+ `The ${protocol_header} header specified ${protocol} which is an invalid because it includes \`:\`. It should only contain the protocol scheme (e.g. \`https\`)`
1704
+ );
1705
+ }
1706
+
1707
+ const host =
1708
+ normalise_header(host_header, headers[host_header]) ||
1709
+ normalise_header('host', headers['host']);
1710
+ if (!host) {
1711
+ const header_names = host_header ? `${host_header} or host headers` : 'host header';
1712
+ throw new Error(
1713
+ `Could not determine host. The request must have a value provided by the ${header_names}`
1714
+ );
1715
+ }
1716
+
1717
+ const port = normalise_header(port_header, headers[port_header]);
1718
+ if (port && isNaN(+port)) {
1719
+ throw new Error(
1720
+ `The ${port_header} header specified ${port} which is an invalid port because it is not a number. The value should only contain the port number (e.g. 443)`
1721
+ );
1722
+ }
1723
+
1724
+ return port ? `${protocol}://${host}:${port}` : `${protocol}://${host}`;
1725
+ }
1726
+
1727
+ const handler = sequence(
1728
+ /** @type {(import('sirv').RequestHandler | import('polka').Middleware)[]} */
1729
+ ([serve(path.join(dir, 'client'), true), serve_prerendered(), ssr].filter(Boolean))
1730
+ );
1731
+
1732
+ export { format_listening_address as f, handler as h, polka as p };
1733
+ //# sourceMappingURL=handler-BN3-p5rP.js.map