@rocket.chat/houston 0.27.0-next.3 → 2.1.9

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 (294) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +109 -15
  3. package/bin/houston +62 -0
  4. package/data/docs/ARCHITECTURE.md +387 -0
  5. package/data/docs/automation.md +107 -0
  6. package/data/docs/e2ee.md +76 -0
  7. package/data/docs/eks.md +258 -0
  8. package/data/docs/gui.md +282 -0
  9. package/data/docs/guide.md +642 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/loadtest.md +264 -0
  12. package/data/docs/troubleshooting.md +203 -0
  13. package/data/docs/upgrading.md +84 -0
  14. package/data/docs/voice.md +253 -0
  15. package/data/iam/engineer-policy.json +11 -0
  16. package/data/iam/engineer-rbac.yaml +42 -0
  17. package/data/iam/operator-policy.json +211 -0
  18. package/data/loadtest/badbot.js +22 -0
  19. package/data/loadtest/common.js +170 -0
  20. package/data/loadtest/custom.js +20 -0
  21. package/data/loadtest/journey.js +58 -0
  22. package/data/loadtest/login.js +18 -0
  23. package/data/loadtest/messages.js +13 -0
  24. package/data/loadtest/mixed.js +57 -0
  25. package/data/loadtest/read.js +12 -0
  26. package/data/loadtest/webhook.js +20 -0
  27. package/data/monitoring/houston-logs.json +98 -0
  28. package/data/monitoring/k6-loadtest.json +610 -0
  29. package/data/monitoring/mongodb-exporter.json +3007 -0
  30. package/data/monitoring/node-exporter-full.json +16114 -0
  31. package/data/monitoring/rocketchat-metrics.json +6471 -0
  32. package/data/presets/airgapped.yaml +16 -0
  33. package/data/presets/default.yaml +9 -0
  34. package/data/seed/avatar-0.png +0 -0
  35. package/data/seed/avatar-1.png +0 -0
  36. package/data/seed/avatar-2.png +0 -0
  37. package/data/seed/avatar-3.png +0 -0
  38. package/data/seed/avatar-4.png +0 -0
  39. package/data/seed/avatar-5.png +0 -0
  40. package/data/seed/avatar-6.png +0 -0
  41. package/data/seed/avatar-7.png +0 -0
  42. package/data/seed/seed-metrics.csv +3 -0
  43. package/data/seed/seed-preview.png +0 -0
  44. package/data/seed/seed-report.pdf +32 -0
  45. package/data/seed/seed-runbook.txt +3 -0
  46. package/data/skill/SKILL.md +399 -0
  47. package/data/versions.yaml +55 -0
  48. package/data/voice/freeswitch/drachtio.xml +52 -0
  49. package/data/voice/freeswitch/public.xml +87 -0
  50. package/data/webui/app.css +2003 -0
  51. package/data/webui/index.html +678 -0
  52. package/data/webui/js/api.js +561 -0
  53. package/data/webui/js/boot.js +44 -0
  54. package/data/webui/js/clusters-tail.js +1377 -0
  55. package/data/webui/js/clusters.js +896 -0
  56. package/data/webui/js/create.js +276 -0
  57. package/data/webui/js/detail.js +507 -0
  58. package/data/webui/js/jobs.js +636 -0
  59. package/data/webui/js/logs.js +634 -0
  60. package/data/webui/js/main.js +14 -0
  61. package/data/webui/js/options.js +408 -0
  62. package/data/webui/js/people.js +438 -0
  63. package/data/webui/js/perf.js +303 -0
  64. package/data/webui/js/render.js +438 -0
  65. package/data/webui/js/shared.js +3 -0
  66. package/data/webui/js/state.js +583 -0
  67. package/data/webui/js/theme.js +123 -0
  68. package/data/webui/js/util.js +584 -0
  69. package/dist/cli/app.js +593 -0
  70. package/dist/cli/capabilities.js +76 -0
  71. package/dist/cli/cell-widths.js +495 -0
  72. package/dist/cli/entry.js +10 -0
  73. package/dist/cli/error-panel.js +492 -0
  74. package/dist/cli/handlers/actor.js +84 -0
  75. package/dist/cli/handlers/https.js +614 -0
  76. package/dist/cli/handlers/prompt.js +299 -0
  77. package/dist/cli/handlers/users.js +226 -0
  78. package/dist/cli/handlers.js +3694 -0
  79. package/dist/cli/help.js +183 -0
  80. package/dist/cli/index.js +15 -0
  81. package/dist/cli/perf.js +814 -0
  82. package/dist/cli/render.js +254 -0
  83. package/dist/cli/serve.js +858 -0
  84. package/dist/cli/spec-data.js +2599 -0
  85. package/dist/cli/spec-types.js +8 -0
  86. package/dist/cli/usage-error.js +520 -0
  87. package/dist/cli/wire.js +70 -0
  88. package/dist/core/audit.js +346 -0
  89. package/dist/core/backup-compat.js +85 -0
  90. package/dist/core/backup.js +1639 -0
  91. package/dist/core/cluster.js +1398 -0
  92. package/dist/core/configimport.js +345 -0
  93. package/dist/core/data.js +267 -0
  94. package/dist/core/database-of.js +82 -0
  95. package/dist/core/diagnose.js +159 -0
  96. package/dist/core/doctor.js +1518 -0
  97. package/dist/core/edge/acme.js +338 -0
  98. package/dist/core/edge/engine.js +500 -0
  99. package/dist/core/edge/networks.js +174 -0
  100. package/dist/core/edge/paths.js +107 -0
  101. package/dist/core/edge/routes.js +251 -0
  102. package/dist/core/edge/routeyml.js +195 -0
  103. package/dist/core/edge/runtime.js +493 -0
  104. package/dist/core/edge/spec.js +305 -0
  105. package/dist/core/edge/types.js +202 -0
  106. package/dist/core/eks-docs.js +135 -0
  107. package/dist/core/eks.js +2240 -0
  108. package/dist/core/envvars.js +562 -0
  109. package/dist/core/eventlog.js +541 -0
  110. package/dist/core/firstrun.js +153 -0
  111. package/dist/core/journal.js +694 -0
  112. package/dist/core/kube/ask.js +231 -0
  113. package/dist/core/kube/capabilities.js +269 -0
  114. package/dist/core/kube/certmanager.js +452 -0
  115. package/dist/core/kube/chart.js +413 -0
  116. package/dist/core/kube/cluster.js +196 -0
  117. package/dist/core/kube/context.js +545 -0
  118. package/dist/core/kube/endpoints.js +448 -0
  119. package/dist/core/kube/exec.js +195 -0
  120. package/dist/core/kube/forward.js +732 -0
  121. package/dist/core/kube/grafana-ingress.js +110 -0
  122. package/dist/core/kube/ingress.js +218 -0
  123. package/dist/core/kube/manifests.js +361 -0
  124. package/dist/core/kube/monitoring.js +768 -0
  125. package/dist/core/kube/names.js +237 -0
  126. package/dist/core/kube/namespace.js +678 -0
  127. package/dist/core/kube/operator.js +941 -0
  128. package/dist/core/kube/probe.js +202 -0
  129. package/dist/core/kube/reachability.js +163 -0
  130. package/dist/core/kube/release.js +439 -0
  131. package/dist/core/kube/replicaset.js +180 -0
  132. package/dist/core/kube/scale.js +398 -0
  133. package/dist/core/kube/status.js +633 -0
  134. package/dist/core/kube/tools.js +238 -0
  135. package/dist/core/kube/transfer.js +173 -0
  136. package/dist/core/kube/workspace.js +423 -0
  137. package/dist/core/lifecycle/admin.js +64 -0
  138. package/dist/core/lifecycle/create-docker.js +1549 -0
  139. package/dist/core/lifecycle/create-k8s.js +960 -0
  140. package/dist/core/lifecycle/destroy.js +339 -0
  141. package/dist/core/lifecycle/inspect.js +636 -0
  142. package/dist/core/lifecycle/naming.js +298 -0
  143. package/dist/core/lifecycle/notes.js +862 -0
  144. package/dist/core/lifecycle/ownership.js +313 -0
  145. package/dist/core/lifecycle/payload.js +401 -0
  146. package/dist/core/lifecycle/ports.js +388 -0
  147. package/dist/core/lifecycle/preconditions.js +367 -0
  148. package/dist/core/lifecycle/pruning.js +551 -0
  149. package/dist/core/lifecycle/ready.js +818 -0
  150. package/dist/core/lifecycle/request.js +510 -0
  151. package/dist/core/lifecycle/seeding.js +281 -0
  152. package/dist/core/lifecycle/sizing.js +392 -0
  153. package/dist/core/lifecycle/state.js +286 -0
  154. package/dist/core/lifecycle/tlsplan.js +704 -0
  155. package/dist/core/lifecycle/types.js +232 -0
  156. package/dist/core/loadtest.js +1051 -0
  157. package/dist/core/migrate.js +612 -0
  158. package/dist/core/monitor.js +494 -0
  159. package/dist/core/postready.js +976 -0
  160. package/dist/core/promote.js +804 -0
  161. package/dist/core/rcapi.js +1336 -0
  162. package/dist/core/recovery.js +75 -0
  163. package/dist/core/runner/engine.js +394 -0
  164. package/dist/core/runner/host.js +298 -0
  165. package/dist/core/runner/locks.js +129 -0
  166. package/dist/core/runner/paths.js +173 -0
  167. package/dist/core/runner/ports.js +172 -0
  168. package/dist/core/runner/queries.js +612 -0
  169. package/dist/core/runner/record.js +563 -0
  170. package/dist/core/scaleseed.js +271 -0
  171. package/dist/core/seed-db.js +208 -0
  172. package/dist/core/sessions.js +472 -0
  173. package/dist/core/skill.js +326 -0
  174. package/dist/core/sso-identities.js +172 -0
  175. package/dist/core/sso.js +703 -0
  176. package/dist/core/tls-local.js +311 -0
  177. package/dist/core/tls.js +878 -0
  178. package/dist/core/topology.js +482 -0
  179. package/dist/core/upgrade.js +877 -0
  180. package/dist/core/users.js +739 -0
  181. package/dist/lib/audit.js +100 -0
  182. package/dist/lib/close-matches.js +238 -0
  183. package/dist/lib/compose.js +672 -0
  184. package/dist/lib/config.js +1398 -0
  185. package/dist/lib/context.js +18 -0
  186. package/dist/lib/errors.js +305 -0
  187. package/dist/lib/events.js +208 -0
  188. package/dist/lib/float-text.js +126 -0
  189. package/dist/lib/format.js +1320 -0
  190. package/dist/lib/home.js +325 -0
  191. package/dist/lib/journal.js +122 -0
  192. package/dist/lib/json-text.js +733 -0
  193. package/dist/lib/jsonout.js +382 -0
  194. package/dist/lib/lock.js +516 -0
  195. package/dist/lib/login-name.js +202 -0
  196. package/dist/lib/map-limit.js +29 -0
  197. package/dist/lib/mkdir-parents.js +90 -0
  198. package/dist/lib/mongo-kernel.js +67 -0
  199. package/dist/lib/monitoring.js +492 -0
  200. package/dist/lib/platform-name.js +59 -0
  201. package/dist/lib/presets/common.js +390 -0
  202. package/dist/lib/presets/composite.js +326 -0
  203. package/dist/lib/presets/e2ee.js +143 -0
  204. package/dist/lib/presets/email.js +172 -0
  205. package/dist/lib/presets/guides.js +27 -0
  206. package/dist/lib/presets/index.js +490 -0
  207. package/dist/lib/presets/keycloak.js +371 -0
  208. package/dist/lib/presets/ldap.js +1285 -0
  209. package/dist/lib/presets/livechat.js +220 -0
  210. package/dist/lib/presets/multi-instance.js +124 -0
  211. package/dist/lib/presets/oidc.js +161 -0
  212. package/dist/lib/presets/public.js +496 -0
  213. package/dist/lib/presets/registry.js +64 -0
  214. package/dist/lib/presets/s3-minio.js +300 -0
  215. package/dist/lib/presets/saml.js +149 -0
  216. package/dist/lib/presets/scenario.js +51 -0
  217. package/dist/lib/presets/types.js +86 -0
  218. package/dist/lib/presets/voice-pbx.js +320 -0
  219. package/dist/lib/presets/voice.js +345 -0
  220. package/dist/lib/presets/webhooks.js +182 -0
  221. package/dist/lib/redact.js +106 -0
  222. package/dist/lib/seed-options.js +68 -0
  223. package/dist/lib/seed-profiles.js +59 -0
  224. package/dist/lib/targz.js +1383 -0
  225. package/dist/lib/teammode.js +25 -0
  226. package/dist/lib/tempdir.js +162 -0
  227. package/dist/lib/unicode-tables.js +2335 -0
  228. package/dist/lib/version-spec.js +357 -0
  229. package/dist/lib/versions.js +463 -0
  230. package/dist/lib/yaml-dump.js +1361 -0
  231. package/dist/perf/baseline.js +168 -0
  232. package/dist/perf/constrain.js +299 -0
  233. package/dist/perf/k6.js +235 -0
  234. package/dist/perf/mongoprof.js +171 -0
  235. package/dist/perf/rcmetrics.js +191 -0
  236. package/dist/perf/report.js +386 -0
  237. package/dist/perf/resources.js +236 -0
  238. package/dist/perf/slo.js +111 -0
  239. package/dist/perf/timeline.js +187 -0
  240. package/dist/perf/timings.js +85 -0
  241. package/dist/perf/verdict.js +201 -0
  242. package/dist/seams/aws-cli.js +126 -0
  243. package/dist/seams/docker-cli.js +280 -0
  244. package/dist/seams/exec.js +861 -0
  245. package/dist/seams/fs/lock.js +528 -0
  246. package/dist/seams/kubectl.js +83 -0
  247. package/dist/seams/rc-http.js +921 -0
  248. package/dist/seed/apply.js +190 -0
  249. package/dist/seed/assets.js +76 -0
  250. package/dist/seed/check.js +391 -0
  251. package/dist/seed/client.js +172 -0
  252. package/dist/seed/executor.js +726 -0
  253. package/dist/seed/history.js +281 -0
  254. package/dist/seed/kinds.js +91 -0
  255. package/dist/seed/plan.js +432 -0
  256. package/dist/seed/receipt.js +339 -0
  257. package/dist/seed/repairs.js +75 -0
  258. package/dist/seed/verification.js +363 -0
  259. package/dist/seed/wording.js +248 -0
  260. package/dist/web/app.js +326 -0
  261. package/dist/web/jobs.js +510 -0
  262. package/dist/web/route-deps.js +211 -0
  263. package/dist/web/route-table.js +213 -0
  264. package/dist/web/routes/backup.js +244 -0
  265. package/dist/web/routes/clusters.js +303 -0
  266. package/dist/web/routes/data.js +187 -0
  267. package/dist/web/routes/edge.js +82 -0
  268. package/dist/web/routes/index.js +63 -0
  269. package/dist/web/routes/jobs.js +95 -0
  270. package/dist/web/routes/logs.js +297 -0
  271. package/dist/web/routes/meta.js +191 -0
  272. package/dist/web/routes/people.js +151 -0
  273. package/dist/web/routes/perf.js +95 -0
  274. package/dist/web/routes/repros.js +550 -0
  275. package/dist/web/routes/session.js +361 -0
  276. package/dist/web/routes/spa.js +198 -0
  277. package/dist/web/security.js +475 -0
  278. package/dist/web/signin.js +246 -0
  279. package/package.json +70 -32
  280. package/.eslintrc +0 -94
  281. package/.swcrc +0 -18
  282. package/dist/bin.js +0 -3
  283. package/dist/cli.js +0 -184
  284. package/dist/commands/createBranch.js +0 -194
  285. package/dist/outputCI.js +0 -59
  286. package/src/bin.js +0 -4
  287. package/src/cli.ts +0 -25
  288. package/src/commands/createBranch.ts +0 -28
  289. package/src/outputCI.ts +0 -12
  290. package/src-old/logs.js +0 -323
  291. package/src-old/md.js +0 -191
  292. package/src-old/release-table.js +0 -60
  293. package/src-old/set-version.js +0 -614
  294. package/src-old/utils.js +0 -15
@@ -0,0 +1,921 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.rcHttp = exports.DEFAULT_TIMEOUT_MS = exports.RequestFailed = void 0;
37
+ const tls = __importStar(require("node:tls"));
38
+ const node_crypto_1 = require("node:crypto");
39
+ const json_text_1 = require("../lib/json-text");
40
+ const float_text_1 = require("../lib/float-text");
41
+ const exec_1 = require("./exec");
42
+ /**
43
+ * A transport failure: the exchange did not complete. The only thing this module throws.
44
+ *
45
+ * `cause` carries the underlying error, so a caller that wants to distinguish a timeout
46
+ * from a refused connection still can -- rcapi does not, because the established failure
47
+ * handling it reproduces does not either.
48
+ */
49
+ class RequestFailed extends Error {
50
+ constructor(message, url, options = {}) {
51
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
52
+ this.url = url;
53
+ this.name = 'RequestFailed';
54
+ this.kind = options.kind ?? 'connection';
55
+ }
56
+ }
57
+ exports.RequestFailed = RequestFailed;
58
+ /**
59
+ * The default deadline, and why there is one at all.
60
+ *
61
+ * An HTTP client without a timeout waits FOREVER -- a socket to a host that accepts and then
62
+ * says nothing never returns. Every rcapi call site passes its own; this is the floor for
63
+ * one that forgets, and 30 s is `call()`'s own default, the most general entry point.
64
+ */
65
+ exports.DEFAULT_TIMEOUT_MS = 30000;
66
+ function withParams(url, params) {
67
+ if (params === undefined)
68
+ return url;
69
+ const entries = Object.entries(params).map(([key, value]) => [
70
+ key,
71
+ String(value),
72
+ ]);
73
+ if (entries.length === 0)
74
+ return url;
75
+ // `URLSearchParams`, NOT `encodeURIComponent`, and that is a decision to match the
76
+ // established client rather than a convenience. Its query is form encoding: a space
77
+ // becomes `+`. `encodeURIComponent` makes it `%20`. The two are interchangeable to a
78
+ // well-behaved server and this tool exists to reproduce customers' servers, so the
79
+ // established spelling wins. Measured: the established client gives `q=a+b%26c`, and so
80
+ // does this.
81
+ //
82
+ // Appended to whatever is already there rather than replacing it -- `settingIds` writes
83
+ // `?count=0` into its path -- as the established client appends it.
84
+ const query = new URLSearchParams(entries).toString();
85
+ return `${url}${url.includes('?') ? '&' : '?'}${query}`;
86
+ }
87
+ /**
88
+ * The bytes a JSON body is sent as: the established JSON spelling, NaN and the infinities
89
+ * refused.
90
+ *
91
+ * `JSON.stringify` was used here and differs in every way that reaches the wire. Its layout
92
+ * is compact where the established spelling has `', '` and `': '`, and it writes non-ASCII
93
+ * raw where that escapes it -- so every login, every PAT mint and every `api -d` body went
94
+ * out as different bytes. It writes NaN and the infinities as `null`, so
95
+ * `api -d '{"n": 1e400}'` SENT `{"n":null}` where the request is refused with
96
+ * `Out of range float values are not JSON compliant: inf`, and NaN likewise. And a null
97
+ * body is no body, where this sent `null` with a JSON Content-Type.
98
+ *
99
+ * The refusal is a `RequestFailed`, as it has always been a request failure: `api` then
100
+ * says `request failed: ...`. It is raised before anything is sent. A value the JSON writer
101
+ * cannot spell at all is its TypeError, which is not caught either.
102
+ */
103
+ function jsonBody(value, target) {
104
+ if (value === undefined || value === null)
105
+ return undefined;
106
+ try {
107
+ return (0, json_text_1.dumps)(value, { allowNan: false });
108
+ }
109
+ catch (error) {
110
+ if (error.name !== 'InvalidValue')
111
+ throw error;
112
+ throw new RequestFailed(error.message, target, { cause: error, kind: 'other' });
113
+ }
114
+ }
115
+ /**
116
+ * The established client's default headers, in its order: what every request sends ahead
117
+ * of the caller's own headers.
118
+ *
119
+ * These were fetch's -- `accept`, `accept-language: *`, `sec-fetch-mode: cors`, `user-agent:
120
+ * node`, `accept-encoding`, after the caller's -- so every request of seed, config-import,
121
+ * monitor and every other REST command carried two headers the established client never
122
+ * sends, in another order. fetch cannot be told to leave `accept-language` and
123
+ * `sec-fetch-mode` out, so no hop goes through it any more (see `viaNode`).
124
+ *
125
+ * THE USER-AGENT IS NOT the established client's, by the owner's decision: this build does
126
+ * not claim that client's `<name>/<version>`, a string an upgrade of it would change anyway.
127
+ * It keeps the `node` it always sent, in that header's place. Rocket.Chat records a login's
128
+ * user agent, so the admin's session and device entries name the build that logged in.
129
+ */
130
+ const DEFAULT_HEADERS = Object.freeze([
131
+ ['User-Agent', 'node'],
132
+ ['Accept-Encoding', 'gzip, deflate'],
133
+ ['Accept', '*/*'],
134
+ ['Connection', 'keep-alive'],
135
+ ]);
136
+ /**
137
+ * The headers a request is prepared with: the defaults merged with the caller's, names
138
+ * compared case-insensitively -- a caller's header takes the place of the default it names,
139
+ * in the caller's spelling -- then the body's Content-Length, then the JSON Content-Type
140
+ * unless the caller set one. Measured against the established client: `Content-Length`
141
+ * before `Content-Type` when both are set by it, and `Content-Length: 0` for a method other
142
+ * than GET or HEAD that has no body.
143
+ */
144
+ function preparedHeaders(caller, method, body) {
145
+ const merged = new Map();
146
+ const put = (name, value) => merged.set(name.toLowerCase(), [name, value]);
147
+ for (const [name, value] of DEFAULT_HEADERS)
148
+ put(name, value);
149
+ for (const [name, value] of Object.entries(caller))
150
+ put(name, value);
151
+ // A body's Content-Length only when it is not empty, which the JSON writer never leaves it.
152
+ if (body !== undefined) {
153
+ if (Buffer.byteLength(body) > 0)
154
+ put('Content-Length', String(Buffer.byteLength(body)));
155
+ }
156
+ else if (method !== 'GET' && method !== 'HEAD' && !merged.has('content-length')) {
157
+ put('Content-Length', '0');
158
+ }
159
+ // JSON is the only body this seam sends, so a body is a JSON one.
160
+ if (body !== undefined && !merged.has('content-type'))
161
+ put('Content-Type', 'application/json');
162
+ return [...merged.values()];
163
+ }
164
+ /** The methods that are framed with no `Content-Length: 0` when they carry no body. */
165
+ const NOT_EXPECTING_BODY = new Set([
166
+ 'GET',
167
+ 'HEAD',
168
+ 'DELETE',
169
+ 'TRACE',
170
+ 'OPTIONS',
171
+ 'CONNECT',
172
+ ]);
173
+ /**
174
+ * The `Host` header as the established client writes it: the host lower-cased, without an
175
+ * IPv6 literal's brackets, and without a trailing dot -- bracketed again for IPv6, with the
176
+ * port only when it is not the scheme's default.
177
+ */
178
+ function hostHeader(url) {
179
+ const host = url.hostname.replace(/^\[(.*)\]$/u, '$1').replace(/\.+$/u, '');
180
+ const shown = host.includes(':') ? `[${host}]` : host;
181
+ return url.port === '' ? shown : `${shown}:${url.port}`;
182
+ }
183
+ /**
184
+ * The header lines of one hop, in the established order: `Host` first, then a framing
185
+ * header when the prepared headers carry none (`Content-Length: 0` for a redirected PUT
186
+ * whose body was dropped, which is not prepared again), then the prepared headers. As a
187
+ * flat array, which node's client writes verbatim -- spelling and order kept, nothing of
188
+ * its own added while `Connection` and the framing are present.
189
+ */
190
+ function onTheWire(url, method, headers, body) {
191
+ const named = new Set(headers.map(([name]) => name.toLowerCase()));
192
+ const lines = [];
193
+ if (!named.has('host'))
194
+ lines.push('Host', hostHeader(url));
195
+ if (!named.has('content-length') && !named.has('transfer-encoding')) {
196
+ if (body !== undefined)
197
+ lines.push('Content-Length', String(Buffer.byteLength(body)));
198
+ else if (!NOT_EXPECTING_BODY.has(method))
199
+ lines.push('Content-Length', '0');
200
+ }
201
+ for (const [name, value] of headers)
202
+ lines.push(name, value);
203
+ return lines;
204
+ }
205
+ /**
206
+ * Whether node may send this through the environment's proxy: plain HTTP, with the proxy
207
+ * settings node read at startup (NODE_USE_ENV_PROXY). It decides NO_PROXY itself.
208
+ */
209
+ function proxiedHttp(url, shared) {
210
+ return url.protocol === 'http:' && shared.options?.proxyEnv !== undefined;
211
+ }
212
+ /**
213
+ * The same header lines as one object, in the same order and spelling -- or the lines, when
214
+ * a name repeats and an object would drop one.
215
+ *
216
+ * Node before 24.19 builds a proxied request's absolute URI from `getHeader('host')`, which
217
+ * a raw list never reaches, and falls back to `localhost`: behind a proxy on Node
218
+ * 24.10-24.18, which `engines` admits, every plain-HTTP call houston made asked the proxy
219
+ * for localhost. From an object node reads `Host`, and adds nothing of its own while
220
+ * `Host`, `Connection` and the framing are there -- so the bytes are the list's.
221
+ */
222
+ function asHeaderObject(lines) {
223
+ const out = Object.create(null);
224
+ const seen = new Set();
225
+ for (let at = 0; at < lines.length; at += 2) {
226
+ const name = lines[at];
227
+ if (seen.has(name.toLowerCase()))
228
+ return lines;
229
+ seen.add(name.toLowerCase());
230
+ out[name] = lines[at + 1];
231
+ }
232
+ return out;
233
+ }
234
+ /** The statuses that redirect, and how many redirects are followed. */
235
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
236
+ const MAX_REDIRECTS = 30;
237
+ /**
238
+ * Where a hop broke -- before its status line arrived, or while its body was arriving -- and
239
+ * how much of a body of a stated length had: which decides what the established message says.
240
+ */
241
+ class Broken extends Error {
242
+ constructor(stage, read, length, cause,
243
+ /** The proxy whose connection failed, when it was the proxy's and not the host's. */
244
+ proxy = null) {
245
+ super(String(cause.message || cause), { cause });
246
+ this.stage = stage;
247
+ this.read = read;
248
+ this.length = length;
249
+ this.proxy = proxy;
250
+ }
251
+ }
252
+ /** A body past the caller's `maxBytes`. */
253
+ class TooLarge extends Error {
254
+ constructor(limit) {
255
+ super(`more than ${String(limit)} bytes`);
256
+ this.limit = limit;
257
+ }
258
+ }
259
+ /**
260
+ * The proxy node's agent takes for `url` from the environment it read at startup, as node
261
+ * picks it -- the lower-case name first -- or null. Whether NO_PROXY exempts the host is
262
+ * node's to decide; `failedAtProxy` reads it off what failed.
263
+ */
264
+ function proxyOf(url, env) {
265
+ if (env === undefined)
266
+ return null;
267
+ const raw = url.protocol === 'https:'
268
+ ? env.https_proxy || env.HTTPS_PROXY
269
+ : env.http_proxy || env.HTTP_PROXY;
270
+ if (raw === undefined || raw === '')
271
+ return null;
272
+ try {
273
+ return new URL(raw);
274
+ }
275
+ catch {
276
+ return null;
277
+ }
278
+ }
279
+ /** A URL's host as a socket wants it (no IPv6 brackets), and its port or the scheme's. */
280
+ function endpoint(url) {
281
+ return {
282
+ host: url.hostname.replace(/^\[(.*)\]$/u, '$1'),
283
+ port: url.port === '' ? (url.protocol === 'https:' ? '443' : '80') : url.port,
284
+ };
285
+ }
286
+ /**
287
+ * Whether a connection that failed was the one to `proxy` rather than to the host. For http
288
+ * node asks the proxy for the absolute URL, so a request whose target it rewrote went only to
289
+ * the proxy. For https it tunnels, and the target is left alone, so the failed endpoint says:
290
+ * the proxy's name that did not resolve, or the proxy's port that did not connect.
291
+ */
292
+ function failedAtProxy(error, hop, proxy, rewritten) {
293
+ if (proxy === null)
294
+ return null;
295
+ if (hop.protocol === 'http:')
296
+ return rewritten ? proxy : null;
297
+ const failed = error;
298
+ const via = endpoint(proxy);
299
+ const direct = endpoint(hop);
300
+ if (failed.hostname !== undefined)
301
+ return failed.hostname === via.host ? proxy : null;
302
+ const port = String(failed.port);
303
+ return port === via.port && (port !== direct.port || failed.address === via.host) ? proxy : null;
304
+ }
305
+ function contentLength(headers) {
306
+ const stated = (headers['content-length'] ?? '').trim();
307
+ return /^\d+$/u.test(stated) ? Number(stated) : null;
308
+ }
309
+ /**
310
+ * A body its Content-Encoding does not describe: a content-decoding error -- not a
311
+ * connection error, so not "not answering yet".
312
+ */
313
+ class Undecodable extends Error {
314
+ constructor(
315
+ /** The Content-Encoding, lower-cased, or '' when there is none. */
316
+ encoding, cause) {
317
+ super(String(cause.message || cause), { cause });
318
+ this.encoding = encoding;
319
+ }
320
+ }
321
+ /**
322
+ * The body content-decoded, then read as UTF-8 with the BOM dropped.
323
+ *
324
+ * LENIENT ABOUT AN END CUT SHORT, as the established decoders are (an incremental decoder
325
+ * gives what it has and does not complain at the end) and as fetch's were: a gzip body
326
+ * missing its trailer is the text it holds, where node's one-shot decoders refuse it with
327
+ * "unexpected end of file". A body that is not the encoding at all is an `Undecodable`.
328
+ */
329
+ function decodedBytes(bytes, headers, maxBytes) {
330
+ const zlib = require('node:zlib');
331
+ const lenient = {
332
+ finishFlush: zlib.constants.Z_SYNC_FLUSH,
333
+ ...(maxBytes === undefined ? {} : { maxOutputLength: maxBytes }),
334
+ };
335
+ const encoding = (headers['content-encoding'] ?? '').trim().toLowerCase();
336
+ let plain = bytes;
337
+ try {
338
+ if (encoding === 'gzip' || encoding === 'x-gzip')
339
+ plain = zlib.gunzipSync(bytes, lenient);
340
+ else if (encoding === 'deflate') {
341
+ // Deflate: zlib-wrapped first, raw deflate when that fails.
342
+ try {
343
+ plain = zlib.inflateSync(bytes, lenient);
344
+ }
345
+ catch {
346
+ plain = zlib.inflateRawSync(bytes, lenient);
347
+ }
348
+ }
349
+ }
350
+ catch (error) {
351
+ if (maxBytes !== undefined && error.code === 'ERR_BUFFER_TOO_LARGE')
352
+ throw new TooLarge(maxBytes);
353
+ throw new Undecodable(encoding, error);
354
+ }
355
+ return plain;
356
+ }
357
+ function decoded(bytes, headers, maxBytes) {
358
+ return new TextDecoder('utf-8').decode(decodedBytes(bytes, headers, maxBytes));
359
+ }
360
+ /**
361
+ * Response headers, lower-cased, every repeat of a name joined with `, ` (as fetch did
362
+ * too) -- where node's `headers` keeps only the first `Location` or `Content-Type` it sees.
363
+ */
364
+ function collect(incoming) {
365
+ const collected = {};
366
+ for (const [name, values] of Object.entries(incoming.headersDistinct)) {
367
+ if (values !== undefined)
368
+ collected[name.toLowerCase()] = values.join(', ');
369
+ }
370
+ return collected;
371
+ }
372
+ /**
373
+ * One hop, through node's own client: EVERY hop, where fetch used to carry most of them.
374
+ *
375
+ * fetch adds `accept-language: *` and `sec-fetch-mode: cors` to every request and orders the
376
+ * headers itself, and neither can be turned off, so what went out was never what the
377
+ * established client sends. Here the header lines are written as `onTheWire` lists them. It
378
+ * also sends what fetch refused: a body on GET or HEAD, and TRACE or TRACK.
379
+ *
380
+ * A CONNECTION PER REQUEST, as the established client opens one for a call and closes it
381
+ * after: an agent of its own that keeps nothing alive. node's shared agent would keep the
382
+ * socket for the next request, and a kept socket the other end has since closed fails that
383
+ * request where connecting again does not.
384
+ *
385
+ * THROUGH THE PROXY THE SHARED AGENT WOULD USE. HTTP_PROXY, HTTPS_PROXY and NO_PROXY have
386
+ * always been honoured; node honours them only under NODE_USE_ENV_PROXY (or
387
+ * `--use-env-proxy`), read at startup into its global agents' `proxyEnv`, and bin/houston
388
+ * sets it for this build. An
389
+ * agent of one's own is not given it -- `agent: false` sent every request around the proxy,
390
+ * the release lookup's included -- so it is handed the global agent's, whatever node
391
+ * decided: the proxy under the flag, none without it, as fetch's dispatcher was.
392
+ *
393
+ * Guarded in the suite by `testsetup-network.ts`, which refuses a non-loopback
394
+ * `http.request` / `https.request` as it refuses a non-loopback `fetch`.
395
+ */
396
+ const viaNode = async (url, path, method, headers, body, signal, loopbackOrigin, maxBytes) => {
397
+ const client = (url.protocol === 'https:' ? require('node:https') : require('node:http'));
398
+ // `options` is there on both modules' agents; only https' type declares it.
399
+ const shared = client.globalAgent;
400
+ const originTls = loopbackOrigin === undefined
401
+ ? {}
402
+ : {
403
+ ca: loopbackOrigin.certificate,
404
+ allowPartialTrustChain: true,
405
+ rejectUnauthorized: true,
406
+ servername: url.hostname,
407
+ checkServerIdentity: (host, certificate) => {
408
+ const pinned = new node_crypto_1.X509Certificate(loopbackOrigin.certificate);
409
+ if (certificate.fingerprint256 !== pinned.fingerprint256)
410
+ return new Error('the origin certificate changed during the readiness probe');
411
+ return loopbackOrigin.allowCertificateNameMismatch === true
412
+ ? undefined
413
+ : tls.checkServerIdentity(host, certificate);
414
+ },
415
+ };
416
+ const agent = new client.Agent({
417
+ keepAlive: false,
418
+ proxyEnv: loopbackOrigin === undefined ? shared.options?.proxyEnv : undefined,
419
+ ...originTls,
420
+ });
421
+ const lines = onTheWire(url, method, headers, body);
422
+ return await new Promise((resolve, reject) => {
423
+ const outgoing = client.request({
424
+ protocol: url.protocol,
425
+ // `[::1]` is how a URL spells the host and `::1` is how a socket wants it.
426
+ hostname: loopbackOrigin === undefined ? url.hostname.replace(/^\[(.*)\]$/u, '$1') : '127.0.0.1',
427
+ port: url.port,
428
+ path,
429
+ method,
430
+ headers: loopbackOrigin === undefined && proxiedHttp(url, shared) ? asHeaderObject(lines) : lines,
431
+ agent,
432
+ signal,
433
+ ...originTls,
434
+ }, (incoming) => {
435
+ const collected = collect(incoming);
436
+ const length = contentLength(collected);
437
+ const chunks = [];
438
+ let read = 0;
439
+ // The message only says `aborted`; the socket says whether it was reset, which is
440
+ // what the established message reports.
441
+ let socketError = null;
442
+ const onSocketError = (error) => {
443
+ socketError = error;
444
+ };
445
+ // Held here: a kept-alive socket is gone from the message by the time it closes.
446
+ const socket = incoming.socket;
447
+ socket.on('error', onSocketError);
448
+ const arrived = new Promise((done, broke) => {
449
+ incoming.on('data', (chunk) => {
450
+ chunks.push(chunk);
451
+ read += chunk.length;
452
+ if (maxBytes !== undefined && read > maxBytes)
453
+ incoming.destroy(new TooLarge(maxBytes));
454
+ });
455
+ incoming.on('error', (error) => {
456
+ broke(new Broken('body', read, length, socketError ?? error));
457
+ });
458
+ incoming.on('close', () => {
459
+ socket.off('error', onSocketError);
460
+ if (incoming.complete)
461
+ done(Buffer.concat(chunks));
462
+ else
463
+ broke(new Broken('body', read, length, socketError ?? new Error('aborted')));
464
+ });
465
+ });
466
+ // Read by `text()` or `discard()`; never a rejection nobody is waiting for.
467
+ arrived.catch(() => undefined);
468
+ resolve({
469
+ status: incoming.statusCode ?? 0,
470
+ reason: incoming.statusMessage ?? '',
471
+ headers: collected,
472
+ text: async () => decoded(await arrived, collected, maxBytes),
473
+ bytes: async () => decodedBytes(await arrived, collected, maxBytes),
474
+ discard: async () => {
475
+ await arrived.catch(() => undefined);
476
+ },
477
+ });
478
+ });
479
+ outgoing.on('error', (error) => {
480
+ const proxy = loopbackOrigin === undefined ? proxyOf(url, shared.options?.proxyEnv) : null;
481
+ const via = failedAtProxy(error, url, proxy, outgoing.path !== path);
482
+ reject(new Broken('send', 0, null, error, via));
483
+ });
484
+ outgoing.end(body);
485
+ });
486
+ };
487
+ /** RFC 3986's unreserved characters. */
488
+ const UNRESERVED = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~';
489
+ /** The characters a path keeps unescaped (unreserved, sub-delims, `:` `@` `/`), and a query's. */
490
+ const PATH_CHARS = new Set(`${UNRESERVED}!$&'()*+,;=:@/`);
491
+ const QUERY_CHARS = new Set([...PATH_CHARS, '?']);
492
+ /** A string's UTF-8 bytes, a lone surrogate included as itself. */
493
+ function utf8(text) {
494
+ const bytes = [];
495
+ for (const char of text) {
496
+ const point = char.codePointAt(0);
497
+ if (point < 0x80)
498
+ bytes.push(point);
499
+ else if (point < 0x800)
500
+ bytes.push(0xc0 | (point >> 6), 0x80 | (point & 0x3f));
501
+ else if (point < 0x10000)
502
+ bytes.push(0xe0 | (point >> 12), 0x80 | ((point >> 6) & 0x3f), 0x80 | (point & 0x3f));
503
+ else
504
+ bytes.push(0xf0 | (point >> 18), 0x80 | ((point >> 12) & 0x3f), 0x80 | ((point >> 6) & 0x3f), 0x80 | (point & 0x3f));
505
+ }
506
+ return bytes;
507
+ }
508
+ const escaped = (byte) => `%${byte.toString(16).toUpperCase().padStart(2, '0')}`;
509
+ /**
510
+ * Every byte outside `allowed` escaped, and a `%` kept only when EVERY `%` in the component
511
+ * already starts a valid escape.
512
+ */
513
+ function encodeInvalid(component, allowed) {
514
+ let valid = 0;
515
+ const normalised = component.replace(/%[a-fA-F0-9]{2}/gu, (escape) => {
516
+ valid += 1;
517
+ return escape.toUpperCase();
518
+ });
519
+ const bytes = utf8(normalised);
520
+ const alreadyEncoded = valid === bytes.filter((byte) => byte === 0x25).length;
521
+ let out = '';
522
+ for (const byte of bytes) {
523
+ const char = String.fromCharCode(byte);
524
+ out +=
525
+ (alreadyEncoded && byte === 0x25) || (byte < 0x80 && allowed.has(char))
526
+ ? char
527
+ : escaped(byte);
528
+ }
529
+ return out;
530
+ }
531
+ /** Dot segments removed, RFC 3986 5.2.4. */
532
+ function removeDotSegments(path) {
533
+ const output = [];
534
+ for (const segment of path.split('/')) {
535
+ if (segment === '.')
536
+ continue;
537
+ if (segment !== '..')
538
+ output.push(segment);
539
+ else if (output.length > 0)
540
+ output.pop();
541
+ }
542
+ if (path.startsWith('/') && (output.length === 0 || output[0] !== ''))
543
+ output.unshift('');
544
+ if (path.endsWith('/.') || path.endsWith('/..'))
545
+ output.push('');
546
+ return output.join('/');
547
+ }
548
+ /** Percent-encoding of `text`'s UTF-8 bytes, the unreserved characters and `safe` kept. */
549
+ function quote(text, safe) {
550
+ const keep = new Set([...UNRESERVED, ...safe]);
551
+ let out = '';
552
+ for (const byte of utf8(text)) {
553
+ const char = String.fromCharCode(byte);
554
+ out += byte < 0x80 && keep.has(char) ? char : escaped(byte);
555
+ }
556
+ return out;
557
+ }
558
+ /**
559
+ * The URI requoted: unquote the unreserved escapes, then quote what is illegal -- or, where
560
+ * an escape does not parse, quote every `%`.
561
+ */
562
+ function requoteUri(uri) {
563
+ const parts = uri.split('%');
564
+ for (let i = 1; i < parts.length; i += 1) {
565
+ const part = parts[i];
566
+ const head = [...part].slice(0, 2).join('');
567
+ if ([...head].length === 2 && /^[\p{L}\p{N}]+$/u.test(head)) {
568
+ if (!/^[0-9A-Fa-f]{2}$/u.test(head))
569
+ return quote(uri, "!#$&'()*+,/:;=?@[]~");
570
+ const char = String.fromCharCode(parseInt(head, 16));
571
+ parts[i] = UNRESERVED.includes(char) ? `${char}${part.slice(2)}` : `%${part}`;
572
+ }
573
+ else {
574
+ parts[i] = `%${part}`;
575
+ }
576
+ }
577
+ return quote(parts.join(''), "!#$%&'()*+,/:;=?@[]~");
578
+ }
579
+ /** The request target: the prepared URL's path and query, encoded for the request line. */
580
+ function requestTarget(prepared) {
581
+ const rest = prepared.slice(prepared.indexOf('//') + 2);
582
+ const start = rest.search(/[/?#]/u);
583
+ const tail = start < 0 ? '' : rest.slice(start).split('#')[0];
584
+ const mark = tail.indexOf('?');
585
+ const path = (mark < 0 ? tail : tail.slice(0, mark)) || '/';
586
+ const query = mark < 0 ? '' : tail.slice(mark + 1);
587
+ let target = query === '' ? path : `${path}?${query}`;
588
+ // A target that starts `//` keeps one leading slash, so it cannot read as a host.
589
+ if (target.startsWith('//'))
590
+ target = `/${target.replace(/^\/+/u, '')}`;
591
+ const [, head = '', tailQuery] = /^(\/[^?#]*)(?:\?([^#]*))?/su.exec(target) ?? [];
592
+ return tailQuery === undefined
593
+ ? encodeInvalid(head, PATH_CHARS)
594
+ : `${encodeInvalid(head, PATH_CHARS)}?${encodeInvalid(tailQuery, QUERY_CHARS)}`;
595
+ }
596
+ /**
597
+ * The URL as the established client sends it, and the target on its request line.
598
+ *
599
+ * fetch sent a URL as the WHATWG parser rewrites it, and the two disagree about exactly the
600
+ * characters a Rocket.Chat query is made of. The established client escapes `|`, `[`, `]`,
601
+ * `{`, `}` and `"` (parsed, then requoted), where WHATWG leaves them raw; it escapes a
602
+ * stray `%` as `%25`, where WHATWG keeps it; and it sends `\` and a TAB as `%5C` and `%09`,
603
+ * where WHATWG turns the backslash into `/` and drops the TAB -- so
604
+ * `api GET '/api/v1/a\b'` asked Rocket.Chat for `/api/v1/a/b`, another endpoint. So the
605
+ * URL is prepared the established way, and its target goes on the request line verbatim
606
+ * through node's client, where WHATWG would still rewrite one (a `'` in a query, which it
607
+ * escapes).
608
+ *
609
+ * Null for what this does not reproduce -- a scheme other than http(s), no host, userinfo,
610
+ * a host outside `[A-Za-z0-9.-]` or an IPv6 literal, a port past 65535 -- which go out as
611
+ * before, so a failure keeps the words it had.
612
+ */
613
+ function prepareUrl(raw) {
614
+ let start = 0;
615
+ while (start < raw.length && float_text_1.STRIP_CHARS.has(raw[start]))
616
+ start += 1;
617
+ const url = raw.slice(start);
618
+ const parts = /^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?(?:\/\/([^\\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/su.exec(url);
619
+ if (parts === null)
620
+ return null;
621
+ const [, rawScheme, authority, rawPath = '', rawQuery, rawFragment] = parts;
622
+ const scheme = (rawScheme ?? '').toLowerCase();
623
+ if ((scheme !== 'http' && scheme !== 'https') || authority === undefined)
624
+ return null;
625
+ const hostPort = /^([A-Za-z0-9-][A-Za-z0-9.-]*|\[[0-9A-Fa-f:.]+\])(?::0*?(|0|[1-9][0-9]{0,4}))?$/u.exec(authority);
626
+ if (hostPort === null)
627
+ return null;
628
+ const host = hostPort[1].toLowerCase();
629
+ const port = Number(hostPort[2] ?? '');
630
+ if (port > 65535)
631
+ return null;
632
+ const path = rawPath === '' ? '/' : encodeInvalid(removeDotSegments(rawPath), PATH_CHARS);
633
+ const query = rawQuery === undefined ? '' : encodeInvalid(rawQuery, QUERY_CHARS);
634
+ const fragment = rawFragment === undefined ? '' : encodeInvalid(rawFragment, QUERY_CHARS);
635
+ // A port of 0 is left out, as it always has been.
636
+ let joined = `${scheme}://${host}${port === 0 ? '' : `:${String(port)}`}${path}`;
637
+ if (query !== '')
638
+ joined += `?${query}`;
639
+ if (fragment !== '')
640
+ joined += `#${fragment}`;
641
+ const prepared = requoteUri(joined);
642
+ return { url: prepared, target: requestTarget(prepared) };
643
+ }
644
+ /** Where `url` connects, as a refusal names it: `127.0.0.1:3000`, an IPv6 host in brackets. */
645
+ function whereOf(url) {
646
+ const { host, port } = endpoint(url);
647
+ return `${host.includes(':') ? `[${host}]` : host}:${port}`;
648
+ }
649
+ /** glibc's words for the connect errors a refused connection carries, as measured. */
650
+ const CONNECT_ERRORS = Object.freeze({
651
+ ECONNREFUSED: 'Connection refused',
652
+ ENETUNREACH: 'Network is unreachable',
653
+ EHOSTUNREACH: 'No route to host',
654
+ });
655
+ /** getaddrinfo's words for a name that does not resolve. */
656
+ const RESOLVE_ERRORS = Object.freeze({
657
+ ENOTFOUND: 'Name or service not known',
658
+ EAI_AGAIN: 'Temporary failure in name resolution',
659
+ });
660
+ /**
661
+ * The message for a connection that could not be made -- to the host, or to `proxy` -- or
662
+ * null for a failure it does not describe (see `failed`).
663
+ */
664
+ function neverConnected(cause, hop, path, landed, proxy) {
665
+ // Several addresses tried (localhost is ::1 and 127.0.0.1): the error of the last one
666
+ // tried is the one reported.
667
+ const tried = cause.errors;
668
+ const failure = (Array.isArray(tried) && tried.length > 0 ? tried.at(-1) : cause);
669
+ const code = String(failure.code);
670
+ // Only an http:// proxy was measured.
671
+ if (proxy !== null && proxy.protocol !== 'http:')
672
+ return null;
673
+ const words = CONNECT_ERRORS[code];
674
+ const resolve = RESOLVE_ERRORS[code];
675
+ // What was asked for: the request target, or through an http proxy the whole URL without
676
+ // its fragment.
677
+ const asked = proxy !== null && hop.protocol === 'http:' ? landed.split('#')[0] : path;
678
+ if (words !== undefined && failure.syscall === 'connect') {
679
+ return proxy === null
680
+ ? `cannot connect to ${whereOf(hop)} (${asked}): ${words}`
681
+ : `cannot connect to the proxy ${whereOf(proxy)} for ${asked}: ${words}`;
682
+ }
683
+ if (resolve !== undefined && failure.syscall === 'getaddrinfo') {
684
+ const host = endpoint(proxy ?? hop).host.replace(/\.+$/u, '');
685
+ return proxy === null
686
+ ? `cannot resolve ${host} (${asked}): ${resolve}`
687
+ : `cannot resolve the proxy ${host} for ${asked}: ${resolve}`;
688
+ }
689
+ return null;
690
+ }
691
+ /**
692
+ * The message for the failure, where it can be said exactly: what was tried and why it did
693
+ * not work, in the C library's words for the reason.
694
+ *
695
+ * closed before a status line <target>: the connection closed without a response
696
+ * reset before a status line <target>: the connection was reset (Connection reset by peer)
697
+ * a body short of its length <target>: the response ended early (11 bytes read, 89 more
698
+ * expected)
699
+ * reset in the body <target>: the connection was reset mid-response (...)
700
+ * silent until the deadline localhost:3100 did not answer within 30.0s
701
+ * silent in the body localhost:3100 stopped sending before the response ended
702
+ * refused, unreachable cannot connect to 127.0.0.1:1 (/api/v1/login): Connection
703
+ * refused (or Network is unreachable, No route to host)
704
+ * a name that does not resolve cannot resolve rc.invalid (/api/v1/login): Name or service
705
+ * not known
706
+ * a proxy that refuses cannot connect to the proxy <host:port> for <the whole URL>
707
+ * a body that is not its the response said content-encoding gzip but could not be
708
+ * Content-Encoding decoded: incorrect header check
709
+ *
710
+ * They are quoted by config-import, monitor attach and `seed`, and persisted -- a seed's
711
+ * `verification.unreadable[].why` in repro.json. A name that does not resolve is taken as
712
+ * EAI_NONAME, as it nearly always is: node calls EAI_NODATA `ENOTFOUND` too. What cannot be
713
+ * said exactly keeps the seam's own words: any other failure to connect (TLS, a proxy that
714
+ * answers a CONNECT with a refusal) is `could not reach <url>: <node's words>`, and a
715
+ * connect timeout reads as the read timeout does.
716
+ *
717
+ * THE KIND DECIDES: a connection error and a timeout are "not answering yet", and a short
718
+ * body is not one. The deadline is the whole exchange's where a per-read timeout would be
719
+ * each read's (see `request`), so the same words can stand for a different wait.
720
+ */
721
+ function failed(error, hop, path, landed, target, timeoutMs, aborted) {
722
+ const tooLarge = error instanceof TooLarge ? error : error instanceof Broken ? error.cause : undefined;
723
+ if (tooLarge instanceof TooLarge) {
724
+ return new RequestFailed(`${target} answered with ${tooLarge.message}`, target, {
725
+ cause: tooLarge,
726
+ kind: 'other',
727
+ });
728
+ }
729
+ if (error instanceof Undecodable) {
730
+ const zlibError = error.cause;
731
+ return new RequestFailed(zlibError.code !== 'Z_DATA_ERROR'
732
+ ? `${target} answered and then stopped sending`
733
+ : `the response said content-encoding ${error.encoding} but could not be decoded: ${String(zlibError.message)}`, target, { cause: error.cause, kind: 'other' });
734
+ }
735
+ const broken = error instanceof Broken ? error : new Broken('send', 0, null, error);
736
+ const cause = broken.cause;
737
+ // Node's client throws the socket's own error; fetch wrapped it, and no hop is fetch's now.
738
+ const code = cause.code;
739
+ const message = String(cause.message);
740
+ const said = (words, kind) => new RequestFailed(words, target, { cause, kind });
741
+ if (aborted) {
742
+ const where = whereOf(hop);
743
+ return broken.stage === 'send'
744
+ ? said(`${where} did not answer within ${(0, float_text_1.floatString)(timeoutMs / 1000)}s`, 'timeout')
745
+ : said(`${where} stopped sending before the response ended`, 'connection');
746
+ }
747
+ const closed = message === 'socket hang up' || message === 'aborted';
748
+ const wasReset = code === 'ECONNRESET' && !closed;
749
+ if (broken.stage === 'send') {
750
+ if (closed)
751
+ return said(`${target}: the connection closed without a response`, 'connection');
752
+ if (wasReset) {
753
+ return said(`${target}: the connection was reset (Connection reset by peer)`, 'connection');
754
+ }
755
+ const unmade = neverConnected(cause, hop, path, landed, broken.proxy);
756
+ if (unmade !== null)
757
+ return said(unmade, 'connection');
758
+ return said(`could not reach ${target}: ${String(cause.message || cause)}`, 'connection');
759
+ }
760
+ if (wasReset) {
761
+ return said(`${target}: the connection was reset mid-response (Connection reset by peer)`, 'other');
762
+ }
763
+ if (closed && broken.length !== null) {
764
+ const short = `${String(broken.read)} bytes read, ${String(broken.length - broken.read)} more expected`;
765
+ return said(`${target}: the response ended early (${short})`, 'other');
766
+ }
767
+ return said(`${target} answered and then stopped sending`, 'other');
768
+ }
769
+ /**
770
+ * The hops of one request: redirects followed by the established rules, each hop over
771
+ * node's client (`viaNode`).
772
+ *
773
+ * FOLLOWED HERE, not by the client, because the established rules are their own. fetch
774
+ * gave up after 20 with `fetch failed`; the established client follows 30 and refuses the
775
+ * 31st with `Exceeded 30 redirects.` A 302 turns anything but HEAD into GET for it and only
776
+ * a POST for fetch; a 303 does the same; a 301 turns a POST into GET for both. And every
777
+ * redirect but 307 and 308 drops the body, with its Content-Type and Content-Length, even
778
+ * where the method stays -- fetch sent a 301'd PUT's body again.
779
+ *
780
+ * CONNECT IS REFUSED, in the words fetch refused it with, as it always was: node's client
781
+ * reads any answer to a CONNECT as the start of a tunnel, not as a response, where the
782
+ * established client reads it as a response.
783
+ */
784
+ async function resolveRedirects(target, method, headers, body, timeoutMs, interrupted, binary = false, sameOriginRedirects = false, followRedirects = true, loopbackOrigin, maxBytes) {
785
+ const prepared = prepareUrl(target);
786
+ let url;
787
+ try {
788
+ url = new URL(prepared?.url ?? target);
789
+ }
790
+ catch (error) {
791
+ // fetch's own words for the same input, which is what this said before it parsed.
792
+ throw new RequestFailed(`could not reach ${target}: Failed to parse URL from ${target}`, target, {
793
+ cause: error,
794
+ });
795
+ }
796
+ // THE WHOLE EXCHANGE, not just the connect. The established client's timeout is per
797
+ // socket operation and this is a deadline, which is stricter -- a server trickling one
798
+ // byte per second satisfies the first and not the second. Stricter is the right direction
799
+ // for a tool whose callers all sit inside their own retry loop with their own budget.
800
+ const controller = new AbortController();
801
+ const deadline = setTimeout(() => {
802
+ controller.abort();
803
+ }, timeoutMs);
804
+ interrupted?.addEventListener('abort', () => controller.abort(), { once: true });
805
+ let path = prepared?.target ?? `${url.pathname}${url.search}`;
806
+ // The response's URL: the URL as prepared, fragment and all.
807
+ let landed = prepared?.url ?? url.href;
808
+ let verb = method;
809
+ let payload = body;
810
+ let sent = headers;
811
+ try {
812
+ for (let redirects = 0;; redirects += 1) {
813
+ let answer;
814
+ try {
815
+ if (verb === 'CONNECT')
816
+ throw new TypeError("'CONNECT' HTTP method is unsupported.");
817
+ answer = await viaNode(url, path, verb, sent, payload, controller.signal, loopbackOrigin, maxBytes);
818
+ }
819
+ catch (error) {
820
+ throw failed(error, url, path, landed, target, timeoutMs, controller.signal.aborted);
821
+ }
822
+ const location = answer.headers.location;
823
+ if (followRedirects && REDIRECTS.has(answer.status) && location !== undefined) {
824
+ await answer.discard();
825
+ // Thirty redirects followed: the 31st is the one refused.
826
+ if (redirects >= MAX_REDIRECTS)
827
+ throw new RequestFailed(`Exceeded ${String(MAX_REDIRECTS)} redirects.`, target, {
828
+ kind: 'other',
829
+ });
830
+ // The requoted location resolved against the URL, keeping the fragment when the new
831
+ // location has none (RFC 7231 7.1.2).
832
+ try {
833
+ const next = new URL(requoteUri(location), url);
834
+ if (sameOriginRedirects && next.origin !== new URL(target).origin)
835
+ throw new Error('cross-origin download redirect refused');
836
+ if (next.hash === '')
837
+ next.hash = url.hash;
838
+ url = next;
839
+ }
840
+ catch (error) {
841
+ throw new RequestFailed(`could not reach ${target}: ${String(error)}`, target, {
842
+ cause: error,
843
+ });
844
+ }
845
+ landed = url.href;
846
+ path = requestTarget(url.href);
847
+ if (answer.status === 303 && verb !== 'HEAD')
848
+ verb = 'GET';
849
+ if (answer.status === 302 && verb !== 'HEAD')
850
+ verb = 'GET';
851
+ if (answer.status === 301 && verb === 'POST')
852
+ verb = 'GET';
853
+ if (answer.status !== 307 && answer.status !== 308) {
854
+ payload = undefined;
855
+ sent = sent.filter(([name]) => !['content-length', 'content-type', 'transfer-encoding'].includes(name.toLowerCase()));
856
+ }
857
+ continue;
858
+ }
859
+ let text;
860
+ let bytes;
861
+ try {
862
+ if (binary) {
863
+ bytes = await answer.bytes();
864
+ text = new TextDecoder('utf-8').decode(bytes);
865
+ }
866
+ else
867
+ text = await answer.text();
868
+ }
869
+ catch (error) {
870
+ throw failed(error, url, path, landed, target, timeoutMs, controller.signal.aborted);
871
+ }
872
+ return {
873
+ status: answer.status,
874
+ reason: answer.reason,
875
+ ok: answer.status < 400,
876
+ text,
877
+ ...(bytes === undefined ? {} : { bytes }),
878
+ headers: answer.headers,
879
+ url: landed,
880
+ json: () => JSON.parse(text),
881
+ };
882
+ }
883
+ }
884
+ finally {
885
+ clearTimeout(deadline);
886
+ }
887
+ }
888
+ /** Make one HTTP request. The single network call site. */
889
+ async function request(url, options = {}) {
890
+ const target = withParams(url, options.params);
891
+ const method = (options.method ?? 'GET').toUpperCase();
892
+ if (options.body !== undefined && options.json !== undefined) {
893
+ throw new RequestFailed('a request cannot carry both JSON and a raw body', target, {
894
+ kind: 'other',
895
+ });
896
+ }
897
+ const body = options.body ?? jsonBody(options.json, target);
898
+ // The JSON Content-Type only when the caller did not say: an explicit Content-Type wins
899
+ // over the one a JSON body would have set. After the Content-Length, in the established
900
+ // order (see `preparedHeaders`).
901
+ const headers = preparedHeaders(options.headers ?? {}, method, body);
902
+ // A WAIT A CTRL-C REACHES: the exchange is abandoned and the interrupt raised in its
903
+ // place. `seed` restores the two settings it turned off only if its `finally` runs, and a
904
+ // Ctrl-C lands in a request far more often than anywhere else in it.
905
+ return await (0, exec_1.interruptibly)(() => {
906
+ const interrupted = new AbortController();
907
+ return {
908
+ done: resolveRedirects(target, method, headers, body, options.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS, interrupted.signal, options.binary === true, options.sameOriginRedirects === true, options.followRedirects !== false, options.loopbackOrigin, options.maxBytes),
909
+ stop: () => interrupted.abort(),
910
+ };
911
+ });
912
+ }
913
+ /**
914
+ * The seam, as an object.
915
+ *
916
+ * A module-level function binding cannot be replaced from outside under this build --
917
+ * swc emits ES module exports as non-configurable getters, so `jest.spyOn` on one fails
918
+ * with "Cannot redefine property". Hanging the callable off an exported object is what
919
+ * `seams/kubectl.ts` and `core/kube/exec.ts` do, for the same reason.
920
+ */
921
+ exports.rcHttp = { request };