@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,1320 @@
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.floatString = exports.stripText = void 0;
37
+ exports.formatFixed = formatFixed;
38
+ exports.roundSeconds = roundSeconds;
39
+ exports.roundHalfEven = roundHalfEven;
40
+ exports.parseFloat_ = parseFloat_;
41
+ exports.formatG = formatG;
42
+ exports.formatPercent = formatPercent;
43
+ exports.formatSigned = formatSigned;
44
+ exports.isPrintableText = isPrintableText;
45
+ exports.foldCase = foldCase;
46
+ exports.quotedText = quotedText;
47
+ exports.isTruthy = isTruthy;
48
+ exports.shownValue = shownValue;
49
+ exports.shownSpelled = shownSpelled;
50
+ exports.toTextYaml = toTextYaml;
51
+ exports.toTextAny = toTextAny;
52
+ exports.storedText = storedText;
53
+ exports.splitTextLines = splitTextLines;
54
+ exports.textLines = textLines;
55
+ exports.toText = toText;
56
+ exports.isSpaceText = isSpaceText;
57
+ exports.splitFields = splitFields;
58
+ exports.numberText = numberText;
59
+ exports.toInt = toInt;
60
+ exports.toBigInt = toBigInt;
61
+ exports.intFromText = intFromText;
62
+ exports.compareCodePoints = compareCodePoints;
63
+ exports.decodeUtf8Strict = decodeUtf8Strict;
64
+ exports.namedError = namedError;
65
+ exports.valueKind = valueKind;
66
+ exports.expectedText = expectedText;
67
+ exports.keyRefusal = keyRefusal;
68
+ exports.setItemChecked = setItemChecked;
69
+ exports.dictGetChecked = dictGetChecked;
70
+ exports.orElse = orElse;
71
+ exports.iterateChecked = iterateChecked;
72
+ exports.containsChecked = containsChecked;
73
+ exports.hashableKey = hashableKey;
74
+ exports.fileErrorText = fileErrorText;
75
+ exports.strerrorText = strerrorText;
76
+ exports.fileErrorOf = fileErrorOf;
77
+ exports.socketErrorText = socketErrorText;
78
+ exports.pathExists = pathExists;
79
+ exports.pathIsFile = pathIsFile;
80
+ exports.pathIsDir = pathIsDir;
81
+ exports.urlQuote = urlQuote;
82
+ exports.urlUnquote = urlUnquote;
83
+ /**
84
+ * Number formatting that rounds half to EVEN, because JavaScript's rounds the other way at
85
+ * a tie.
86
+ *
87
+ * MEASURED, NOT ASSUMED. Fixed point with N decimals and rounding to a whole number both
88
+ * round half to EVEN here; `toFixed` and `Math.round` round half AWAY FROM ZERO. They agree
89
+ * on almost every input and disagree on exactly the ones a report is most likely to
90
+ * contain -- a mean that lands on a half, a percentage of a round count:
91
+ *
92
+ * value formatFixed(v, 0) v.toFixed(0) roundHalfEven(v) Math.round(v)
93
+ * 0.5 '0' '1' 0 1
94
+ * 2.5 '2' '3' 2 3
95
+ * -0.5 '-0' '-1' 0 -0
96
+ * 1234.5 '1234' '1235' 1234 1235
97
+ * 0.125 '0.12' (2 places) '0.13' - -
98
+ *
99
+ * That last row is the one worth noticing: 0.125 is EXACTLY representable, so it is a true
100
+ * tie and the two rules genuinely differ. 2.675 is not (it is 2.67499...), so both give
101
+ * '2.67' and a test built only from values like it would find nothing.
102
+ *
103
+ * `perf/` renders these numbers into reports, verdicts and SLO lines that a person reads
104
+ * beside the ones earlier releases wrote, so a one-digit difference is a difference in the
105
+ * product. The helpers here exist so that every format string goes through one
106
+ * implementation rather than each one re-deciding.
107
+ *
108
+ * ## How the tie is detected
109
+ *
110
+ * Not by scaling -- `value * 10 ** digits` introduces the very error being measured. Every
111
+ * double has a FINITE decimal expansion, so the expansion is taken as a string and rounded
112
+ * as a decimal. `toFixed(100)` is the widest Node offers; for the magnitudes this package
113
+ * deals in, the expansion fits, and any digits beyond it are far below the rounding
114
+ * position and cannot manufacture a tie there.
115
+ */
116
+ const unicode_tables_1 = require("./unicode-tables");
117
+ /** The widest fractional expansion `toFixed` will produce. */
118
+ const EXPANSION = 100;
119
+ /**
120
+ * `value` in fixed point with `digits` places, half to EVEN.
121
+ *
122
+ * Keeps the `-0` of a negative value that rounds to zero, because that is the spelling
123
+ * earlier releases printed and reports are compared against.
124
+ */
125
+ function formatFixed(value, digits) {
126
+ if (Number.isNaN(value))
127
+ return 'nan';
128
+ if (!Number.isFinite(value))
129
+ return value > 0 ? 'inf' : '-inf';
130
+ const negative = value < 0 || Object.is(value, -0);
131
+ const abs = Math.abs(value);
132
+ // The exact decimal expansion, wide enough that the digit after the cut and everything
133
+ // behind it are visible.
134
+ const expansion = abs.toFixed(Math.min(EXPANSION, Math.max(digits + 30, digits)));
135
+ const [whole = '0', fraction = ''] = expansion.split('.');
136
+ const kept = fraction.slice(0, digits).padEnd(digits, '0');
137
+ const rest = fraction.slice(digits);
138
+ const rounded = roundDecimal(whole, kept, rest);
139
+ const body = digits > 0 ? `${rounded.whole}.${rounded.kept}` : rounded.whole;
140
+ return negative ? `-${body}` : body;
141
+ }
142
+ /**
143
+ * Seconds to one decimal place, half to EVEN -- the duration shape every service writes.
144
+ *
145
+ * `Math.round` is half AWAY FROM ZERO, so a duration of exactly 1.25s would be `1.3` where
146
+ * the established shape is `1.2`. `formatFixed` already spells the half-even rule, so the
147
+ * number is parsed back out of it rather than re-derived.
148
+ */
149
+ function roundSeconds(milliseconds) {
150
+ return Number(formatFixed(milliseconds / 1000, 1));
151
+ }
152
+ /**
153
+ * Round a decimal split into (whole, kept, rest) with half-to-EVEN, carrying if needed.
154
+ *
155
+ * `rest` is everything after the cut. A tie is `rest` being exactly "5" followed by zeros;
156
+ * anything else decides by its first digit, which is what makes 2.675 round down (its
157
+ * expansion is 2.67499...) while 0.125 is a real tie.
158
+ */
159
+ function roundDecimal(whole, kept, rest) {
160
+ if (rest === '')
161
+ return { whole, kept };
162
+ const first = rest.charCodeAt(0) - 48;
163
+ const tie = first === 5 && /^50*$/u.test(rest);
164
+ let roundUp;
165
+ if (first > 5)
166
+ roundUp = true;
167
+ else if (first < 5)
168
+ roundUp = false;
169
+ else if (!tie)
170
+ roundUp = true;
171
+ else {
172
+ // A true tie: go to the EVEN neighbour.
173
+ const last = kept === '' ? whole.charCodeAt(whole.length - 1) - 48 : kept.charCodeAt(kept.length - 1) - 48;
174
+ roundUp = last % 2 === 1;
175
+ }
176
+ if (!roundUp)
177
+ return { whole, kept };
178
+ // Increment the (whole + kept) digit string by one, carrying across the decimal point.
179
+ const digits = (whole + kept).split('');
180
+ let index = digits.length - 1;
181
+ for (;;) {
182
+ if (index < 0) {
183
+ digits.unshift('1');
184
+ break;
185
+ }
186
+ const next = digits[index].charCodeAt(0) - 48 + 1;
187
+ if (next < 10) {
188
+ digits[index] = String(next);
189
+ break;
190
+ }
191
+ digits[index] = '0';
192
+ index -= 1;
193
+ }
194
+ const keptLength = kept.length;
195
+ const joined = digits.join('');
196
+ return {
197
+ whole: keptLength === 0 ? joined : joined.slice(0, joined.length - keptLength),
198
+ kept: keptLength === 0 ? '' : joined.slice(joined.length - keptLength),
199
+ };
200
+ }
201
+ /**
202
+ * `value` rounded to a whole number, half to EVEN.
203
+ *
204
+ * `Math.round(2.5)` is 3 and this is 2. Used wherever a count or a ratio is rounded to a
205
+ * whole number.
206
+ */
207
+ function roundHalfEven(value) {
208
+ if (!Number.isFinite(value))
209
+ return value;
210
+ const asString = formatFixed(value, 0);
211
+ const parsed = Number(asString);
212
+ // `formatFixed` keeps the `-0`; a whole number rounded from it is a plain 0.
213
+ return Object.is(parsed, -0) ? 0 : parsed;
214
+ }
215
+ /**
216
+ * `text` read as a float -- a decimal with single underscores allowed between digits, or
217
+ * `inf`, `infinity` or `nan` in any case -- which is not `Number(text)`.
218
+ *
219
+ * Measured rather than assumed. The two differ in both directions:
220
+ *
221
+ * text parseFloat_ Number(text)
222
+ * '1_000' 1000 NaN underscores between digits are allowed
223
+ * 'Infinity' Infinity Infinity (agree)
224
+ * '' throws 0 the dangerous one
225
+ * '0x10' throws 16 and so is this
226
+ * ' 42 ' 42 42 (agree)
227
+ *
228
+ * `Number('')` being 0 and `Number('0x10')` being 16 are what make a bare `Number` wrong
229
+ * for parsing something a user typed: an empty SLO threshold would silently become a gate
230
+ * of zero, which every run passes.
231
+ *
232
+ * Throws a `RangeError` named `InvalidValue`, so a caller can tell "not a number" from a
233
+ * number it did not like.
234
+ */
235
+ const FLOAT_GRAMMAR = /^[+-]?(?:(?:\d+(?:_\d+)*)?\.?(?:\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?|inf|infinity|nan)$/iu;
236
+ function parseFloat_(text) {
237
+ // Unicode whitespace and Unicode digits, as `numberText` reads them: `'١'` is 1, where
238
+ // an ASCII `\d` refused it, and `'\x1c2'` is refused, where `stripText` would have made it 2.
239
+ const trimmed = numberText(String(text));
240
+ const refused = () => namedError('InvalidValue', `${quotedText(String(text))} is not a number`);
241
+ if (trimmed === '')
242
+ throw refused();
243
+ if (!FLOAT_GRAMMAR.test(trimmed))
244
+ throw refused();
245
+ const body = trimmed.replace(/_/gu, '');
246
+ // The regex accepts a lone sign or a lone dot; `Number` reports those as NaN, which is
247
+ // indistinguishable from a real 'nan' without this check.
248
+ const bare = body.replace(/^[+-]/u, '');
249
+ if (bare === '' || bare === '.')
250
+ throw refused();
251
+ if (/^(?:inf|infinity)$/iu.test(bare))
252
+ return body.startsWith('-') ? -Infinity : Infinity;
253
+ if (/^nan$/iu.test(bare))
254
+ return NaN;
255
+ const value = Number(body);
256
+ if (Number.isNaN(value))
257
+ throw refused();
258
+ return value;
259
+ }
260
+ /**
261
+ * The general format `g` -- six significant digits, trailing zeros stripped, and an
262
+ * exponent outside `[1e-5, 1e6)`.
263
+ *
264
+ * Measured rather than assumed, because `toPrecision(6)` KEEPS the trailing zeros `g`
265
+ * drops and picks a different exponent boundary:
266
+ *
267
+ * value formatG(v) (v).toPrecision(6)
268
+ * 2.0 '2' '2.00000'
269
+ * 1e-5 '1e-05' '0.0000100000'
270
+ * 1234567.0 '1.23457e+06' '1.23457e+6'
271
+ *
272
+ * The exponent is two digits minimum with a sign, which `toExponential` does not do
273
+ * either. `--cpus` is rendered through this, so a cap of `2` that printed as `2.00000`
274
+ * would be handed to `docker update` verbatim.
275
+ */
276
+ function formatG(value) {
277
+ if (Number.isNaN(value))
278
+ return 'nan';
279
+ if (!Number.isFinite(value))
280
+ return value > 0 ? 'inf' : '-inf';
281
+ if (value === 0)
282
+ return Object.is(value, -0) ? '-0' : '0';
283
+ const exponent = Math.floor(Math.log10(Math.abs(value)));
284
+ // The `g` rule: use the exponential form when the exponent is < -4 or >= the
285
+ // precision (6 by default).
286
+ if (exponent < -4 || exponent >= 6) {
287
+ const [mantissa, exp] = value.toExponential(5).split('e');
288
+ const trimmed = mantissa.includes('.')
289
+ ? mantissa.replace(/0+$/u, '').replace(/\.$/u, '')
290
+ : mantissa;
291
+ const sign = exp.startsWith('-') ? '-' : '+';
292
+ const digits = exp.replace(/^[+-]/u, '').padStart(2, '0');
293
+ return `${trimmed}e${sign}${digits}`;
294
+ }
295
+ const fixed = value.toFixed(Math.max(0, 5 - exponent));
296
+ return fixed.includes('.') ? fixed.replace(/0+$/u, '').replace(/\.$/u, '') : fixed;
297
+ }
298
+ /**
299
+ * A percentage -- multiply by 100, then the same round-half-to-even fixed formatting, then
300
+ * a `%`.
301
+ *
302
+ * Measured: `0.0125` at two places is `'1.25%'` and at one place `'1.2%'`, which is the
303
+ * tie rule again (1.25 -> 1.2, to the even neighbour) and not what `toFixed` gives.
304
+ */
305
+ function formatPercent(value, digits) {
306
+ return `${formatFixed(value * 100, digits)}%`;
307
+ }
308
+ /**
309
+ * Fixed point with a sign ALWAYS shown, including for a value that rounds to zero.
310
+ *
311
+ * `formatSigned(0.4, 0)` is `'+0'` and `formatSigned(-0.4, 0)` is `'-0'`, which is how a
312
+ * baseline delta of "no meaningful change" reads in a report: a bare `0` would look like
313
+ * the metric was not measured.
314
+ */
315
+ function formatSigned(value, digits) {
316
+ const body = formatFixed(value, digits);
317
+ return body.startsWith('-') ? body : `+${body}`;
318
+ }
319
+ /**
320
+ * Whether one character is printable: false for everything Unicode calls Other or
321
+ * Separator, except the ASCII space. `quotedText` escapes exactly those code points, and this is
322
+ * the half an earlier version was missing -- a NUL, a NEL, a DEL, a BOM, an NBSP or a U+2028
323
+ * reached the message raw. The audit log's field sanitiser asks it too (`lib/audit.ts`).
324
+ *
325
+ * Read from the Unicode 15.0 table in `./unicode-tables`, not `/[\p{C}\p{Z}]/u`: that asks
326
+ * Node's Unicode, 17.0 in Node 24. Measured, the two disagree on 10,615 code points, every
327
+ * one assigned in 16.0 or 17.0 and so still `Cn` -- non-printable -- in 15.0. Asking Node,
328
+ * `houston 𑛐` (U+116D0) said `No such command '𑛐'.`, where the message must escape it:
329
+ * `No such command '\u{116d0}'.`.
330
+ */
331
+ function isPrintableText(ch) {
332
+ const point = ch.codePointAt(0);
333
+ let lower = 0;
334
+ let upper = unicode_tables_1.NOT_PRINTABLE.length - 1;
335
+ while (lower <= upper) {
336
+ const middle = (lower + upper) >> 1;
337
+ const [first, last] = unicode_tables_1.NOT_PRINTABLE[middle];
338
+ if (point < first)
339
+ upper = middle - 1;
340
+ else if (point > last)
341
+ lower = middle + 1;
342
+ else
343
+ return false;
344
+ }
345
+ return true;
346
+ }
347
+ let FOLDS;
348
+ /**
349
+ * Unicode full case folding, from the Unicode 15.0 table in `./unicode-tables`.
350
+ *
351
+ * Not `toLowerCase()`, which is a different mapping: `ß` folds to `ss` and lowers to itself,
352
+ * `ς` and `µ` fold to `σ` and `μ`, `Σ` folds to `σ` wherever it stands where lowering makes
353
+ * it `ς` at the end of a word, and a Cherokee small letter folds to its CAPITAL. Lowered,
354
+ * two spellings of one host name were two hosts, so `edge delete STRASSE.example` kept the
355
+ * route, certificate and key of `Straße.example`, which folding makes the same name.
356
+ */
357
+ function foldCase(text) {
358
+ FOLDS ?? (FOLDS = new Map(unicode_tables_1.CASE_FOLDS.map(([point, folded]) => [point, String.fromCodePoint(...folded)])));
359
+ let out = '';
360
+ for (const ch of text)
361
+ out += FOLDS.get(ch.codePointAt(0)) ?? ch;
362
+ return out;
363
+ }
364
+ /**
365
+ * How a non-printable code point is written inside quotes: `\xNN` under 0x100, `\uNNNN`, then
366
+ * `\u{NNNNN}` for an astral one -- JavaScript's own escapes, so a quoted value can be pasted
367
+ * back into a script. `stored` keeps the eight-digit `\UNNNNNNNN` that data files written
368
+ * by earlier releases hold, and that those releases read back.
369
+ */
370
+ function escapeCodePoint(codePoint, dialect) {
371
+ const hex = codePoint.toString(16);
372
+ if (codePoint < 0x100)
373
+ return `\\x${hex.padStart(2, '0')}`;
374
+ if (codePoint < 0x10000)
375
+ return `\\u${hex.padStart(4, '0')}`;
376
+ return dialect === 'stored' ? `\\U${hex.padStart(8, '0')}` : `\\u{${hex}}`;
377
+ }
378
+ /**
379
+ * A string in quotes, which is how a message quotes a value: `'alpha'`.
380
+ *
381
+ * Single quotes unless the value contains one and no double quote. The messages that use
382
+ * it carry wording scripts match on, or are pasted into a ticket, so the rule is kept
383
+ * rather than approximated with a hard-coded pair of quotes. A backslash, the quote, `\n`,
384
+ * `\r` and `\t` are escaped, and a non-printable code point is written as
385
+ * `escapeCodePoint` spells it.
386
+ */
387
+ function quotedText(value) {
388
+ return quotedTop(value, 'shown');
389
+ }
390
+ /** `quotedText`, in a dialect and with a quote character chosen by the caller. */
391
+ function quotedIn(value, dialect, quote) {
392
+ let out = quote;
393
+ for (const ch of value) {
394
+ if (ch === '\\')
395
+ out += '\\\\';
396
+ else if (ch === quote)
397
+ out += `\\${ch}`;
398
+ else if (ch === '\n')
399
+ out += '\\n';
400
+ else if (ch === '\r')
401
+ out += '\\r';
402
+ else if (ch === '\t')
403
+ out += '\\t';
404
+ else if (!isPrintableText(ch))
405
+ out += escapeCodePoint(ch.codePointAt(0), dialect);
406
+ else
407
+ out += ch;
408
+ }
409
+ return out + quote;
410
+ }
411
+ /** A string on its own in `dialect`: the same quote rule in both, only the escapes differ. */
412
+ function quotedTop(value, dialect) {
413
+ return quotedIn(value, dialect, value.includes("'") && !value.includes('"') ? '"' : "'");
414
+ }
415
+ /** A string as a value inside a container is written in `dialect`. */
416
+ function quotedMember(value, dialect) {
417
+ return dialect === 'shown' ? quotedIn(value, 'shown', '"') : quotedTop(value, 'stored');
418
+ }
419
+ /**
420
+ * The established truthiness: false for null, undefined, false, 0, '', [], {} -- and TRUE
421
+ * for a NaN. This said false for NaN, so a NaN a document holds (JSON and YAML both read
422
+ * one) was falsy where earlier releases held it truthy: a sidecar's NaN version read as
423
+ * none, a preset's `requires_license: .nan` as no licence.
424
+ *
425
+ * `toText` handles "the value, or empty"; this is the bare truth test, where JavaScript's
426
+ * truthiness disagrees in the other direction — an empty array and an empty object are
427
+ * BOTH truthy in JavaScript and falsy here. A summary, a detail payload and a config bag
428
+ * are all cases where a JSON `[]` means "nothing was measured" and must not read as `true`.
429
+ */
430
+ function isTruthy(value) {
431
+ if (value === null || value === undefined || value === false)
432
+ return false;
433
+ if (value === true)
434
+ return true;
435
+ if (typeof value === 'number')
436
+ return value !== 0;
437
+ if (typeof value === 'string')
438
+ return value.length > 0;
439
+ if (Array.isArray(value))
440
+ return value.length > 0;
441
+ if (typeof value === 'object')
442
+ return Object.keys(value).length > 0;
443
+ return true;
444
+ }
445
+ /**
446
+ * The text of a float, which is not `String(number)`: `5.0`, `1e-07`, `inf`.
447
+ *
448
+ * Lives in the rank-0 leaf `float-text.ts` because `redact.ts` needs its whitespace set and
449
+ * shares this module's rank; re-exported here so the rest of the code keeps one import.
450
+ */
451
+ const fs = __importStar(require("node:fs"));
452
+ const float_text_1 = require("./float-text");
453
+ Object.defineProperty(exports, "floatString", { enumerable: true, get: function () { return float_text_1.floatString; } });
454
+ Object.defineProperty(exports, "stripText", { enumerable: true, get: function () { return float_text_1.stripText; } });
455
+ /**
456
+ * A value as a person reads it: `null`, `true`, `12`, `1.5`, `'alpha'`, and a container as
457
+ * JSON spells one -- `["a", 1.0]`, `{"k": null}`.
458
+ *
459
+ * `data`'s import plan shows each setting's value this way, and a settings dump holds
460
+ * strings, numbers, booleans, nulls and whole lists and mappings. A string alone is quoted
461
+ * as a message quotes a value (`quotedText`); inside a container it is double-quoted, as JSON is.
462
+ */
463
+ function shownValue(value) {
464
+ return textWithin(value, new Set(), undefined, undefined, 'shown', false);
465
+ }
466
+ /**
467
+ * `shownValue`, with what `spellings` knows of the value. A function of its own rather than a
468
+ * second parameter, because `shownValue` is handed to `.map` as it is, where a second
469
+ * parameter would receive the index.
470
+ */
471
+ function shownSpelled(value, spellings) {
472
+ return textWithin(value, new Set(), spellings, undefined, 'shown', false);
473
+ }
474
+ /** The ISO text (a space between) of the UTC datetime at a Date's instant: what else it can be. */
475
+ function utcDatetimeText(value) {
476
+ const pad = (n, width = 2) => String(n).padStart(width, '0');
477
+ let out = `${pad(value.getUTCFullYear(), 4)}-${pad(value.getUTCMonth() + 1)}-`;
478
+ out += `${pad(value.getUTCDate())} ${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:`;
479
+ out += pad(value.getUTCSeconds());
480
+ const micro = value.getUTCMilliseconds() * 1000;
481
+ if (micro !== 0)
482
+ out += `.${pad(micro, 6)}`;
483
+ return `${out}+00:00`;
484
+ }
485
+ /** An offset of `offset` seconds in the stored spelling, `datetime.timedelta(...)`. */
486
+ function storedOffset(offset) {
487
+ const days = Math.floor(offset / 86400);
488
+ const seconds = offset - days * 86400;
489
+ const parts = [
490
+ ...(days === 0 ? [] : [`days=${String(days)}`]),
491
+ ...(seconds === 0 ? [] : [`seconds=${String(seconds)}`]),
492
+ ];
493
+ return `datetime.timedelta(${parts.join(', ')})`;
494
+ }
495
+ /**
496
+ * A date or a datetime from its ISO text, in the stored spelling earlier releases wrote into
497
+ * a compose environment value: `datetime.date(2026, 1, 1)`, a datetime's second only when it
498
+ * or the microsecond is set, its microsecond only when set, then its tzinfo --
499
+ * `datetime.timezone.utc` for a zero offset, or the fixed offset.
500
+ */
501
+ function storedDate(text) {
502
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?: (\d{2}):(\d{2}):(\d{2})(?:\.(\d{6}))?(?:([-+])(\d{2}):(\d{2}))?)?$/u.exec(text);
503
+ if (match === null)
504
+ return quotedMember(text, 'stored');
505
+ const [, year, month, day, hour, minute, second, micro, sign, tzHour, tzMinute] = match;
506
+ const date = [year, month, day].map(Number);
507
+ if (hour === undefined)
508
+ return `datetime.date(${date.join(', ')})`;
509
+ const fields = [...date, Number(hour), Number(minute)];
510
+ if (Number(second) !== 0 || micro !== undefined)
511
+ fields.push(Number(second));
512
+ if (micro !== undefined)
513
+ fields.push(Number(micro));
514
+ let tz = '';
515
+ if (sign !== undefined) {
516
+ const offset = (Number(tzHour) * 3600 + Number(tzMinute) * 60) * (sign === '-' ? -1 : 1);
517
+ tz =
518
+ offset === 0
519
+ ? ', tzinfo=datetime.timezone.utc'
520
+ : `, tzinfo=datetime.timezone(${storedOffset(offset)})`;
521
+ }
522
+ return `datetime.datetime(${fields.join(', ')}${tz})`;
523
+ }
524
+ /**
525
+ * A value the YAML loader built, as a user preset's environment value is WRITTEN into the
526
+ * generated compose file (and helm values), as config's `safeLoadConstructed` holds it:
527
+ * `storedText`, plus a Date as the date or datetime `dateText` says it stands for -- its ISO
528
+ * text alone, the stored date spelling inside a container.
529
+ *
530
+ * This is data, not a message: the compose file is shared with earlier releases, which
531
+ * regenerate and read it, and Rocket.Chat reads the value. So it keeps the spelling those
532
+ * files have always held -- `True`, `None`, `inf`, `[1, 2]` -- where `String(v)` wrote `true`,
533
+ * `null`, `Infinity` and `1,2`, a mapping as `[object Object]`, an int past 2**53 rounded,
534
+ * and a date as the Date's own text in the box's time zone.
535
+ */
536
+ function toTextYaml(value, dateText) {
537
+ if (typeof value === 'string')
538
+ return value;
539
+ if (value instanceof Date)
540
+ return dateText(value) ?? utcDatetimeText(value);
541
+ return textWithin(value, new Set(), undefined, dateText, 'stored', false);
542
+ }
543
+ /**
544
+ * A value in `dialect`, knowing which containers are being written on the way down to it.
545
+ *
546
+ * A YAML alias can hold itself -- `bind_host: &x [*x]` in `config.yaml` -- and the loader
547
+ * builds the real cycle. A list or a mapping guards it: a container met again while it is
548
+ * still being written is `[...]` or `{...}`, so `config get bind_host` prints `[[...]]`. This
549
+ * recursed until the stack ran out, and the command died with a RangeError and a JavaScript
550
+ * stack. The guard is per PATH: `open` is emptied on the way back up, so an alias shared
551
+ * without a cycle -- `[*s, *s]` -- still prints in full twice. An empty list is `[]` before
552
+ * the guard is consulted; it holds nothing to recurse into.
553
+ */
554
+ function textWithin(value, open, spellings, dateText, dialect, nested) {
555
+ const spelled = spellings?.scalar(value);
556
+ if (spelled !== undefined)
557
+ return spelled;
558
+ const stored = dialect === 'stored';
559
+ const inner = (held) => textWithin(held, open, spellings, dateText, dialect, true);
560
+ if (value === null || value === undefined)
561
+ return stored ? 'None' : 'null';
562
+ if (typeof value === 'boolean') {
563
+ if (stored)
564
+ return value ? 'True' : 'False';
565
+ return value ? 'true' : 'false';
566
+ }
567
+ if (typeof value === 'string')
568
+ return nested ? quotedMember(value, dialect) : quotedTop(value, dialect);
569
+ if (typeof value === 'number') {
570
+ // A JSON integer arrives as an integral number and its text is its digits, so `String`
571
+ // is the right spelling for it -- see the caveat on `floatString` for the `2.0` case
572
+ // that no JavaScript parser can tell apart from `2`.
573
+ return Number.isInteger(value) ? String(value) : (0, float_text_1.floatString)(value);
574
+ }
575
+ // The rest are what a YAML document holds that JSON does not (`safeLoadConstructed`):
576
+ // an int past 2**53, a float a number cannot say is one, a date, a mapping with keys that
577
+ // are not strings, a set. Each was `String(value)` quoted, or `{}`.
578
+ if (typeof value === 'bigint')
579
+ return value.toString();
580
+ if (value instanceof float_text_1.JsonFloat)
581
+ return (0, float_text_1.floatString)(value.value);
582
+ if (value instanceof Date) {
583
+ if (!stored)
584
+ return dateText?.(value) ?? utcDatetimeText(value);
585
+ // Only where the caller says what its Dates stand for: the stored text of config.yaml's
586
+ // plain object still prints `{}` for one.
587
+ if (dateText !== undefined)
588
+ return storedDate(dateText(value) ?? utcDatetimeText(value));
589
+ }
590
+ if (Array.isArray(value)) {
591
+ if (value.length === 0)
592
+ return '[]';
593
+ if (open.has(value))
594
+ return '[...]';
595
+ open.add(value);
596
+ const body = value
597
+ .map((held, index) => spellings?.member(value, String(index), held) ?? inner(held))
598
+ .join(', ');
599
+ open.delete(value);
600
+ return `[${body}]`;
601
+ }
602
+ if (value instanceof Set) {
603
+ // Members in the order the set holds them. A set cannot hold itself -- it is
604
+ // unhashable -- so there is no cycle to guard. Shown, a set reads as the list it is to a
605
+ // person; stored, it keeps the spelling earlier releases wrote.
606
+ const body = [...value].map(inner).join(', ');
607
+ if (!stored)
608
+ return `[${body}]`;
609
+ return value.size === 0 ? 'set()' : `{${body}}`;
610
+ }
611
+ if (typeof value === 'object') {
612
+ if (open.has(value))
613
+ return '{...}';
614
+ open.add(value);
615
+ // A Map is what a YAML document with keys that are not strings builds; a plain object is
616
+ // what JSON built, whose number spellings and key order the caller may hold.
617
+ const bag = value;
618
+ const entries = value instanceof Map
619
+ ? [...value].map(([key, held]) => [key, inner(held)])
620
+ : (spellings === undefined ? Object.keys(bag) : spellings.keys(bag)).map((key) => [
621
+ key,
622
+ spellings?.member(bag, key, bag[key]) ?? inner(bag[key]),
623
+ ]);
624
+ const body = entries.map(([key, text]) => `${inner(key)}: ${text}`).join(', ');
625
+ open.delete(value);
626
+ return `{${body}}`;
627
+ }
628
+ return quotedText(String(value));
629
+ }
630
+ /**
631
+ * A value as a row or a message shows it: `shownValue`, with a string as itself rather than
632
+ * quoted -- `alpha`, `null`, `true`, `["a"]`.
633
+ */
634
+ function toTextAny(value) {
635
+ return typeof value === 'string' ? value : shownValue(value);
636
+ }
637
+ /**
638
+ * A value in the stored spelling earlier releases wrote -- a string as itself, `None`, `True`,
639
+ * `['a']` -- for the few places it becomes DATA another program reads: a Traefik route's port,
640
+ * an env name or value written into a compose file, a kube context passed to kubectl, a
641
+ * field coerced into a record earlier releases also read. Never for a message.
642
+ */
643
+ function storedText(value) {
644
+ return typeof value === 'string'
645
+ ? value
646
+ : textWithin(value, new Set(), undefined, undefined, 'stored', false);
647
+ }
648
+ /**
649
+ * The lines of `text`, each with its ending when `keepends` is set, broken on more than
650
+ * `\n`.
651
+ *
652
+ * It also breaks on CR (a CRLF is one break), VT, FF, the three information separators,
653
+ * NEL and the two Unicode separators. Splitting on `\n` alone read a file holding any of
654
+ * them as ONE line — `migrate` turned the account row `rc-repro-bob` into `houston-bob`
655
+ * that way, because the whole file looked like a comment. A trailing terminator does not
656
+ * add an empty line.
657
+ *
658
+ * Hoisted from `core/migrate.ts` when `data`'s scale-result parser needed the same rule;
659
+ * one implementation rather than two that drift.
660
+ */
661
+ const LINE_BOUNDARY = new Set([
662
+ '\n',
663
+ '\r',
664
+ '\v',
665
+ '\f',
666
+ '\u001c',
667
+ '\u001d',
668
+ '\u001e',
669
+ '\u0085',
670
+ '\u2028',
671
+ '\u2029',
672
+ ]);
673
+ function splitTextLines(text, keepends = false) {
674
+ const out = [];
675
+ let start = 0;
676
+ let at = 0;
677
+ while (at < text.length) {
678
+ const ch = text[at];
679
+ if (!LINE_BOUNDARY.has(ch)) {
680
+ at += 1;
681
+ continue;
682
+ }
683
+ let end = at + 1;
684
+ if (ch === '\r' && text[end] === '\n')
685
+ end += 1;
686
+ out.push(keepends ? text.slice(start, end) : text.slice(start, at));
687
+ at = end;
688
+ start = end;
689
+ }
690
+ if (start < text.length)
691
+ out.push(text.slice(start));
692
+ return out;
693
+ }
694
+ /**
695
+ * A child's output read line by line with UNIVERSAL NEWLINES, fed as the pipe delivers it.
696
+ *
697
+ * `\r\n`, a bare `\r` and `\n` each end a line, and the last line is yielded when the pipe
698
+ * closes even with no newline at all. `onLine` is handed each line without its ending. A
699
+ * `\r` that ends a chunk is held for the next one, since it may be the first half of a
700
+ * `\r\n`, and ends its line if the pipe closes instead. Not `splitTextLines`, which breaks on
701
+ * more characters than universal newlines do.
702
+ */
703
+ function textLines(onLine) {
704
+ let pending = '';
705
+ return {
706
+ push(chunk) {
707
+ pending += chunk;
708
+ const breaks = /\r\n|\r|\n/gu;
709
+ let start = 0;
710
+ for (let found = breaks.exec(pending); found !== null; found = breaks.exec(pending)) {
711
+ if (found[0] === '\r' && found.index === pending.length - 1)
712
+ break;
713
+ onLine(pending.slice(start, found.index));
714
+ start = found.index + found[0].length;
715
+ }
716
+ pending = pending.slice(start);
717
+ },
718
+ end() {
719
+ if (pending === '')
720
+ return;
721
+ const last = pending.endsWith('\r') ? pending.slice(0, -1) : pending;
722
+ pending = '';
723
+ onLine(last);
724
+ },
725
+ };
726
+ }
727
+ /**
728
+ * `String(value)`, with null, undefined, false, 0, NaN, `[]` and `{}` read as the empty
729
+ * string rather than as JavaScript spells them.
730
+ *
731
+ * The distinction that matters: `String(false)`, `String(0)` and `String(NaN)` produce
732
+ * `"false"`, `"0"` and `"NaN"`, which are TRUTHY strings. A config value of `false` for
733
+ * `reg_token` would reach a compose document, and a falsy `acme_email` would satisfy the
734
+ * contact-email refusal -- both cases where a falsy value must read as empty.
735
+ */
736
+ function toText(value) {
737
+ if (value === null || value === undefined || value === false)
738
+ return '';
739
+ if (typeof value === 'string')
740
+ return value;
741
+ if (typeof value === 'number')
742
+ return value === 0 || Number.isNaN(value) ? '' : String(value);
743
+ if (Array.isArray(value))
744
+ return value.length === 0 ? '' : String(value);
745
+ if (typeof value === 'object')
746
+ return Object.keys(value).length === 0 ? '' : String(value);
747
+ return String(value);
748
+ }
749
+ /** Whether one character is whitespace: exactly the set `stripText` removes. */
750
+ function isSpaceText(ch) {
751
+ return float_text_1.STRIP_CHARS.has(ch);
752
+ }
753
+ /**
754
+ * The words between runs of whitespace -- the `STRIP_CHARS` set -- with no empty string
755
+ * at either end.
756
+ *
757
+ * Not `split(/\s+/)`, for the reason `stripText` is not `trim()`: the two whitespace sets
758
+ * disagree in both directions, so folding a YAML description onto one line by joining its
759
+ * words with a space would keep a NEL or a `\x1c` that the established fold removes, and
760
+ * fold a BOM that it keeps.
761
+ */
762
+ function splitFields(text) {
763
+ const words = [];
764
+ let word = '';
765
+ for (const char of text) {
766
+ if (!float_text_1.STRIP_CHARS.has(char))
767
+ word += char;
768
+ else if (word !== '') {
769
+ words.push(word);
770
+ word = '';
771
+ }
772
+ }
773
+ if (word !== '')
774
+ words.push(word);
775
+ return words;
776
+ }
777
+ /** A code point's decimal digit value, or null, from the Unicode 15.0 table in `./unicode-tables`. */
778
+ function decimalText(point) {
779
+ const run = unicode_tables_1.DECIMAL_DIGITS.find(([first, last]) => first <= point && point <= last);
780
+ return run === undefined ? null : run[2] + point - run[0];
781
+ }
782
+ /** The ASCII whitespace stripped at either end after the transform. */
783
+ const ASCII_SPACE = /^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/gu;
784
+ /**
785
+ * The text an integer or a float is parsed from: each code point transformed, then the
786
+ * ASCII whitespace at either end stripped. The transform keeps a code point below 127,
787
+ * turns Unicode whitespace into a space and a decimal digit into its ASCII digit, and turns
788
+ * anything else into `?` and stops there -- which no number's grammar accepts.
789
+ *
790
+ * Reproduced rather than approximated, because each approximation it replaces was measured
791
+ * wrong:
792
+ *
793
+ * - A digit's value is its Unicode decimal value, not its distance from the previous
794
+ * non-digit: the mathematical digits U+1D7CE..U+1D7FF are five ADJACENT runs of ten,
795
+ * so `--tail 𝟙𝟘` (U+1D7D9 U+1D7D8) read 99 where it is 10.
796
+ * - The digits are Unicode 15.0.0's, not Node 24's 17.0: `--tail 𑛐` (U+116D0, assigned
797
+ * in 16.0) read as a digit, where it is refused as `'\U000116d0' is not a valid int.`.
798
+ * - Only ASCII whitespace is stripped at the ends. The four information separators
799
+ * U+001C..U+001F are below 127, so the transform keeps them and the ASCII strip leaves
800
+ * them: `'\x1c7'` is refused although `stripText('\x1c7')` is `'7'`, which is what an
801
+ * earlier version did. A BOM is `?`, where `String#trim` strips it.
802
+ */
803
+ function numberText(value) {
804
+ let out = '';
805
+ for (const ch of value) {
806
+ const point = ch.codePointAt(0);
807
+ if (point < 127) {
808
+ out += ch;
809
+ continue;
810
+ }
811
+ if (isSpaceText(ch)) {
812
+ out += ' ';
813
+ continue;
814
+ }
815
+ const digit = decimalText(point);
816
+ if (digit === null) {
817
+ out += '?';
818
+ break;
819
+ }
820
+ out += String(digit);
821
+ }
822
+ return out.replace(ASCII_SPACE, '');
823
+ }
824
+ /** The base-10 integer grammar on the transformed text: a sign, digits, single underscores. */
825
+ const INT_GRAMMAR = /^[+-]?[0-9](?:_?[0-9])*$/u;
826
+ /**
827
+ * The integer-string digit limit, 4300: a string of more digits than this is refused --
828
+ * measured, leading zeros count and a sign, whitespace and underscores do not -- so
829
+ * `--tail` given 4301 zeros is `... is not a valid int.`, where this build accepted it and
830
+ * left commander to refuse it in other words. The limit is fixed; no environment variable
831
+ * moves it.
832
+ */
833
+ const INT_MAX_STR_DIGITS = 4300;
834
+ /**
835
+ * `value` read by the integer grammar, which is not `Number()` and not `parseInt`.
836
+ *
837
+ * Measured rather than assumed:
838
+ *
839
+ * value toInt(value) Number(value) parseInt(value, 10)
840
+ * '3.7' throws 3.7 3
841
+ * '0x10' throws 16 0
842
+ * '1e3' throws 1000 1
843
+ * '1_000' 1000 NaN NaN
844
+ * ' 42 ' 42 42 42
845
+ * '' throws 0 NaN
846
+ * '12 files' throws NaN 12
847
+ * '70' 70 NaN NaN
848
+ *
849
+ * A caller that wants a fallback catches the throw; a caller that wants the established
850
+ * failure does not. `parseInt`'s trailing-garbage acceptance and `Number`'s empty-string
851
+ * zero are the two shapes that silently produce a wrong pid or level.
852
+ *
853
+ * Any Unicode decimal digit counts: `COLUMNS='70'` (fullwidth) or `'٦٠'` (Arabic-Indic)
854
+ * sizes `houston presets` 70 or 60 wide, where reading only ASCII digits fell back to 90
855
+ * columns, an 84-column box instead of a 66- or 56-column one (t1-presets verifier).
856
+ */
857
+ function toInt(value) {
858
+ if (typeof value === 'boolean')
859
+ return value ? 1 : 0;
860
+ if (typeof value === 'number') {
861
+ // A NaN is not a value at all and an infinity is out of range, spelled `infinity`
862
+ // whatever its sign; a caller tells the two apart by name.
863
+ if (Number.isNaN(value))
864
+ throw namedError('InvalidValue', 'NaN is not an integer');
865
+ if (!Number.isFinite(value))
866
+ throw namedError('OutOfRange', 'infinity is not an integer');
867
+ return Math.trunc(value);
868
+ }
869
+ if (typeof value === 'string') {
870
+ // An integer has no negative zero: `'-0'` reads as 0, where `parseInt` gives -0.
871
+ const parsed = Number.parseInt(intDigits(value), 10);
872
+ return parsed === 0 ? 0 : parsed;
873
+ }
874
+ throw new TypeError(expectedText('an integer', value));
875
+ }
876
+ /**
877
+ * The text the integer grammar reads a string as, or its refusal: the sign and the ASCII digits,
878
+ * underscores gone -- Unicode digits folded and whitespace stripped as `numberText` does.
879
+ */
880
+ function intDigits(value) {
881
+ const text = numberText(value);
882
+ if (!INT_GRAMMAR.test(text)) {
883
+ throw new RangeError(`${quotedText(value)} is not an integer`);
884
+ }
885
+ const digits = text.replace(/[^0-9]/gu, '').length;
886
+ if (digits > INT_MAX_STR_DIGITS)
887
+ throw new RangeError(tooManyDigits(digits));
888
+ return text.replace(/_/gu, '');
889
+ }
890
+ /**
891
+ * A string read by the integer grammar, EXACT: `toInt`'s reading and refusals, as a bigint.
892
+ *
893
+ * An integer read from text has no ceiling, and a double holds one exactly only to 2**53: a
894
+ * `--scale messages=9007199254740993@general` was refused as `9,007,199,254,740,992`
895
+ * exceeding the cap, a number nobody typed. For the caller that compares or
896
+ * quotes what was typed; `toInt` stays the reader for a caller that wants a number.
897
+ */
898
+ function toBigInt(value) {
899
+ return BigInt(intDigits(value));
900
+ }
901
+ /** The refusal of an integer written with more digits than any reader here accepts. */
902
+ function tooManyDigits(digits) {
903
+ return `an integer of ${String(digits)} digits is too long (the limit is ${String(INT_MAX_STR_DIGITS)})`;
904
+ }
905
+ /** The integer grammar's digits for each base given here, a prefix naming the base allowed. */
906
+ const INT_BASE_GRAMMAR = {
907
+ 2: /^[+-]?(?:0[bB]_?)?[01](?:_?[01])*$/u,
908
+ 8: /^[+-]?(?:0[oO]_?)?[0-7](?:_?[0-7])*$/u,
909
+ 10: INT_GRAMMAR,
910
+ 16: /^[+-]?(?:0[xX]_?)?[0-9a-fA-F](?:_?[0-9a-fA-F])*$/u,
911
+ };
912
+ /**
913
+ * A string read by the integer grammar in `base`, refusals in the established class and words.
914
+ *
915
+ * What the YAML 1.1 int constructor spends: base 2 after `0b`, base 8 for a leading zero,
916
+ * base 16 after `0x`, base 10 otherwise. As `toInt` reads a string -- Unicode whitespace
917
+ * and Unicode digits, single underscores between digits -- and with a prefix that names
918
+ * the base allowed (`0o17` in base 8, `0x_1f` in base 16). A refusal names the text, quoted
919
+ * and cut to 200 characters, and the base when it is not 10; base 10 alone has the
920
+ * 4300-digit limit, which applies only to a base that is not a power of two.
921
+ *
922
+ * A JavaScript number, as every integer this code reads is: exact to 2**53, the nearest
923
+ * double beyond it.
924
+ */
925
+ function intFromText(value, base) {
926
+ const text = numberText(value);
927
+ if (!INT_BASE_GRAMMAR[base].test(text)) {
928
+ const shown = Array.from(quotedText(value)).slice(0, 200).join('');
929
+ const kind = base === 10 ? 'an integer' : `a base-${String(base)} integer`;
930
+ throw namedError('InvalidValue', `${shown} is not ${kind}`);
931
+ }
932
+ const negative = text.startsWith('-');
933
+ const named = { 2: /^0[bB]/u, 8: /^0[oO]/u, 10: /^$/u, 16: /^0[xX]/u }[base];
934
+ const body = text.replace(/^[+-]/u, '').replace(named, '').replace(/_/gu, '');
935
+ if (base === 10 && body.length > INT_MAX_STR_DIGITS) {
936
+ throw namedError('InvalidValue', tooManyDigits(body.length));
937
+ }
938
+ const prefix = { 2: '0b', 8: '0o', 10: '', 16: '0x' }[base];
939
+ const magnitude = Number(BigInt(`${prefix}${body}`));
940
+ // An integer has no negative zero.
941
+ return negative && magnitude !== 0 ? -magnitude : magnitude;
942
+ }
943
+ /**
944
+ * String order by code point, where `Array.prototype.sort` compares UTF-16 units and so
945
+ * puts an astral character (`😀`, U+1F600) BELOW a BMP one above the surrogates (`A`,
946
+ * U+FF21).
947
+ */
948
+ function compareCodePoints(left, right) {
949
+ const a = Array.from(left, (char) => char.codePointAt(0));
950
+ const b = Array.from(right, (char) => char.codePointAt(0));
951
+ for (let at = 0; at < Math.min(a.length, b.length); at += 1) {
952
+ if (a[at] !== b[at])
953
+ return a[at] - b[at];
954
+ }
955
+ return a.length - b.length;
956
+ }
957
+ /**
958
+ * Where a strict UTF-8 decode stops, and the reason it gives, so the byte range and the reason
959
+ * a refusal reports are exact. A lead byte with too
960
+ * few bytes after it is "unexpected end of data" over the rest of the input, unless the
961
+ * byte after it already cannot continue it.
962
+ */
963
+ function utf8Failure(bytes) {
964
+ const n = bytes.length;
965
+ const follows = (at) => at < n && bytes[at] >= 0x80 && bytes[at] <= 0xbf;
966
+ const invalid = (start, length) => ({
967
+ start,
968
+ end: start + length,
969
+ reason: 'invalid continuation byte',
970
+ });
971
+ let at = 0;
972
+ while (at < n) {
973
+ const lead = bytes[at];
974
+ if (lead < 0x80) {
975
+ at += 1;
976
+ continue;
977
+ }
978
+ if (lead < 0xc2 || lead > 0xf4)
979
+ return { start: at, end: at + 1, reason: 'invalid start byte' };
980
+ const size = lead < 0xe0 ? 2 : lead < 0xf0 ? 3 : 4;
981
+ const second = bytes[at + 1];
982
+ const secondBad = !follows(at + 1) ||
983
+ (size === 3 && (lead === 0xe0 ? second < 0xa0 : lead === 0xed && second >= 0xa0)) ||
984
+ (size === 4 && (lead === 0xf0 ? second < 0x90 : lead === 0xf4 && second >= 0x90));
985
+ if (n - at < size) {
986
+ if (n - at >= 2 && size > 2 && secondBad)
987
+ return invalid(at, 1);
988
+ if (n - at >= 3 && size === 4 && !follows(at + 2))
989
+ return invalid(at, 2);
990
+ return { start: at, end: n, reason: 'unexpected end of data' };
991
+ }
992
+ if (secondBad)
993
+ return invalid(at, 1);
994
+ for (let next = 2; next < size; next += 1)
995
+ if (!follows(at + next))
996
+ return invalid(at, next);
997
+ at += size;
998
+ }
999
+ return null;
1000
+ }
1001
+ /**
1002
+ * Strict UTF-8 decoding: the text, or a refusal named `NotUtf8` that says where and why --
1003
+ * `/x/users is not valid UTF-8 (byte 0xff at position 21: invalid start byte)` -- where Node's
1004
+ * `toString` would put a U+FFFD in and carry on. `label` names what was read, usually its
1005
+ * path. A BOM is kept. A value error, so a `RangeError` here.
1006
+ */
1007
+ function decodeUtf8Strict(bytes, label = 'the text') {
1008
+ const failure = utf8Failure(bytes);
1009
+ if (failure === null)
1010
+ return new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes);
1011
+ const { start, end, reason } = failure;
1012
+ const where = end === start + 1
1013
+ ? `byte 0x${bytes[start].toString(16).padStart(2, '0')} at position ${String(start)}`
1014
+ : `bytes at positions ${String(start)}-${String(end - 1)}`;
1015
+ throw namedError('NotUtf8', `${label} is not valid UTF-8 (${where}: ${reason})`);
1016
+ }
1017
+ /** A RangeError under a name a caller can test for: a bad value, one out of range, or bad UTF-8. */
1018
+ function namedError(name, message) {
1019
+ const error = new RangeError(message);
1020
+ error.name = name;
1021
+ return error;
1022
+ }
1023
+ /**
1024
+ * What kind of value this is, with its article, for a message that reports what a caller
1025
+ * actually sent: `null`, `a list`, `an object`, `a boolean`, `an integer`, `a number`,
1026
+ * `a string`.
1027
+ *
1028
+ * Not `typeof`: a JSON body's list and null are both `object` to it, and an integer and a
1029
+ * fraction are both `number`.
1030
+ */
1031
+ function valueKind(value) {
1032
+ if (value === null || value === undefined)
1033
+ return 'null';
1034
+ if (Array.isArray(value))
1035
+ return 'a list';
1036
+ if (value instanceof Date)
1037
+ return 'a date';
1038
+ if (typeof value === 'object')
1039
+ return 'an object';
1040
+ if (typeof value === 'boolean')
1041
+ return 'a boolean';
1042
+ if (typeof value === 'number')
1043
+ return Number.isInteger(value) ? 'an integer' : 'a number';
1044
+ if (typeof value === 'bigint')
1045
+ return 'an integer';
1046
+ if (typeof value === 'string')
1047
+ return 'a string';
1048
+ return `a ${typeof value}`;
1049
+ }
1050
+ /** The refusal of a value of the wrong kind: `expected an object, got a list`. */
1051
+ function expectedText(want, value) {
1052
+ return `expected ${want}, got ${valueKind(value)}`;
1053
+ }
1054
+ /** The refusal of a value that cannot be a mapping key or a set member: `a list cannot be a key`. */
1055
+ function keyRefusal(value) {
1056
+ return `${valueKind(value)} cannot be a key`;
1057
+ }
1058
+ /**
1059
+ * `container[key] = value`, a string key, on what a JSON or YAML document can hold.
1060
+ *
1061
+ * NOT JavaScript's `mapping[key] = value`, which assigns through the prototype chain: an env
1062
+ * var called `__proto__` passes the env name rule, and `__proto__` is an ACCESSOR on
1063
+ * `Object.prototype`. A string assigned to it was dropped without a word and a `null`
1064
+ * replaced the object's prototype, so the key never became one of the mapping's own -- not
1065
+ * listed, not written, not counted. Defined, it is an own key like any other:
1066
+ * appended when new, and an existing key keeps its place, as in a mapping. `JSON.parse` and the
1067
+ * YAML reader already make a `__proto__` read from disk an own key this way.
1068
+ *
1069
+ * Anything that is not a mapping is a TypeError that says what it was: a hand-edited
1070
+ * `"extra": null` is `expected an object, got null`. Written into a throwaway bag instead,
1071
+ * the value reached a generated file and never the record it was meant for.
1072
+ */
1073
+ function setItemChecked(container, key, value) {
1074
+ if (Array.isArray(container) || container === null || typeof container !== 'object') {
1075
+ throw new TypeError(expectedText('an object', container));
1076
+ }
1077
+ Object.defineProperty(container, key, {
1078
+ value,
1079
+ enumerable: true,
1080
+ writable: true,
1081
+ configurable: true,
1082
+ });
1083
+ }
1084
+ /**
1085
+ * A member read on what a JSON answer holds: a mapping's own member, `fallback` when it has
1086
+ * none -- and on anything that is not a mapping, a TypeError, `expected an object, got a
1087
+ * list`.
1088
+ *
1089
+ * A missing value is `null`, as a JSON null already is. An index read
1090
+ * (`value.key ?? default`) asked nothing of a list or a string and reached through the
1091
+ * prototype for `constructor`, so a reader that must stop at such a value carried on.
1092
+ *
1093
+ * An integral float, `5.0`, reads as the double 5, so a refusal calls it an integer.
1094
+ */
1095
+ function dictGetChecked(value, key, fallback = null) {
1096
+ if (value === null || value === undefined || typeof value !== 'object' || Array.isArray(value)) {
1097
+ throw new TypeError(expectedText('an object', value));
1098
+ }
1099
+ return Object.hasOwn(value, key) ? value[key] : fallback;
1100
+ }
1101
+ /** `left` when `isTruthy(left)`, otherwise `right`. */
1102
+ function orElse(left, right) {
1103
+ return isTruthy(left) ? left : right;
1104
+ }
1105
+ /**
1106
+ * The items a loop over `value` sees: a list's elements, a string's characters, a
1107
+ * mapping's keys -- and a TypeError for a number or a bool, `expected a list, got an integer`.
1108
+ * Null is not iterable either; every caller here guards it with `orElse(..., [])`.
1109
+ */
1110
+ function iterateChecked(value) {
1111
+ if (Array.isArray(value))
1112
+ return value;
1113
+ if (typeof value === 'string')
1114
+ return Array.from(value);
1115
+ if (value !== null && typeof value === 'object')
1116
+ return Object.keys(value);
1117
+ throw new TypeError(expectedText('a list', value));
1118
+ }
1119
+ /**
1120
+ * Whether `container` holds the string `item`: an element of a list, a substring of a
1121
+ * string, a key of a mapping, and for a number or a bool the TypeError `expected a list, a
1122
+ * string or an object, got an integer`. Only a string equals a string, so an element of any other type
1123
+ * never matches.
1124
+ */
1125
+ function containsChecked(container, item) {
1126
+ if (Array.isArray(container))
1127
+ return container.some((element) => element === item);
1128
+ if (typeof container === 'string')
1129
+ return container.includes(item);
1130
+ if (container !== null && typeof container === 'object')
1131
+ return Object.hasOwn(container, item);
1132
+ throw new TypeError(expectedText('a list, a string or an object', container));
1133
+ }
1134
+ /**
1135
+ * `value` as a set member or mapping key: a list or a mapping cannot be one, and is refused
1136
+ * with `a list cannot be a key` before anything is added.
1137
+ */
1138
+ function hashableKey(value) {
1139
+ if (Array.isArray(value) || (value !== null && typeof value === 'object')) {
1140
+ throw new TypeError(keyRefusal(value));
1141
+ }
1142
+ return value;
1143
+ }
1144
+ /** glibc's `strerror` for the codes a file read can raise. */
1145
+ const STRERROR = Object.freeze({
1146
+ EPERM: 'Operation not permitted',
1147
+ ENOENT: 'No such file or directory',
1148
+ EIO: 'Input/output error',
1149
+ ENXIO: 'No such device or address',
1150
+ EACCES: 'Permission denied',
1151
+ EBUSY: 'Device or resource busy',
1152
+ EEXIST: 'File exists',
1153
+ ENOTDIR: 'Not a directory',
1154
+ EISDIR: 'Is a directory',
1155
+ EINVAL: 'Invalid argument',
1156
+ EMFILE: 'Too many open files',
1157
+ ENOSPC: 'No space left on device',
1158
+ EROFS: 'Read-only file system',
1159
+ ENAMETOOLONG: 'File name too long',
1160
+ ELOOP: 'Too many levels of symbolic links',
1161
+ });
1162
+ /**
1163
+ * The text of a Node filesystem error, as a Unix tool writes one: `/x: Permission denied`.
1164
+ *
1165
+ * Node says `EACCES: permission denied, open '/x'`, which puts the error code and the system
1166
+ * call in front of what an operator needs: the file, and the C library's reason. A code
1167
+ * this table does not know keeps Node's own message rather than a guess.
1168
+ */
1169
+ function fileErrorText(error, filename = '') {
1170
+ const err = error;
1171
+ const code = typeof err.code === 'string' ? err.code : '';
1172
+ const number = typeof err.errno === 'number' ? Math.abs(err.errno) : NaN;
1173
+ const text = STRERROR[code];
1174
+ if (text === undefined || Number.isNaN(number)) {
1175
+ const own = error.message;
1176
+ return typeof own === 'string' ? own : String(error);
1177
+ }
1178
+ // A read that fails after its open (EISDIR comes from `read`, not `open`) carries no path,
1179
+ // and the message names the file either way; the caller's filename stands in.
1180
+ const named = typeof err.path === 'string' ? err.path : filename;
1181
+ return named !== '' ? `${named}: ${text}` : text;
1182
+ }
1183
+ /** The strerror text for a Node filesystem error, else the whole sentence. */
1184
+ function strerrorText(error, filename = '') {
1185
+ return (STRERROR[String(error.code ?? '')] ?? fileErrorText(error, filename));
1186
+ }
1187
+ /**
1188
+ * A Node filesystem error rewritten for a person: named `FileError`, its message
1189
+ * `fileErrorText`'s, its `code` kept for a caller that decides by it. For a failure that is
1190
+ * left unhandled, so the last line of the report names the file and the reason.
1191
+ */
1192
+ function fileErrorOf(error, filename = '') {
1193
+ const out = new Error(fileErrorText(error, filename));
1194
+ out.name = 'FileError';
1195
+ const code = error.code;
1196
+ if (typeof code === 'string')
1197
+ out.code = code;
1198
+ return out;
1199
+ }
1200
+ /** The C library's words for a socket error Node reports by code. */
1201
+ const SOCKET_ERRORS = Object.freeze({
1202
+ ECONNREFUSED: 'Connection refused',
1203
+ ECONNRESET: 'Connection reset by peer',
1204
+ ECONNABORTED: 'Software caused connection abort',
1205
+ EPIPE: 'Broken pipe',
1206
+ ETIMEDOUT: 'Connection timed out',
1207
+ EADDRNOTAVAIL: 'Cannot assign requested address',
1208
+ EHOSTUNREACH: 'No route to host',
1209
+ EHOSTDOWN: 'Host is down',
1210
+ ENETUNREACH: 'Network is unreachable',
1211
+ ENETDOWN: 'Network is down',
1212
+ // getaddrinfo's failures, in its own words.
1213
+ ENOTFOUND: 'Name or service not known',
1214
+ EAI_AGAIN: 'Temporary failure in name resolution',
1215
+ });
1216
+ /**
1217
+ * The reason a connection failed, in the C library's words -- `Connection refused` -- where
1218
+ * Node's `ECONNREFUSED: connect ECONNREFUSED ::1:443` repeats the code and the address the
1219
+ * sentence around it already names. Of several addresses tried at once, the FIRST one's
1220
+ * error is reported. A code this table does not know keeps Node's words.
1221
+ */
1222
+ function socketErrorText(error) {
1223
+ const failure = error;
1224
+ const first = (Array.isArray(failure.errors) && failure.errors.length > 0 ? failure.errors[0] : failure);
1225
+ const known = SOCKET_ERRORS[String(first.code ?? '')];
1226
+ if (known === undefined)
1227
+ return `${failure.code ?? failure.name}: ${failure.message}`;
1228
+ return known;
1229
+ }
1230
+ /**
1231
+ * Whether `target` exists: false only for the errors that mean "not there" -- ENOENT,
1232
+ * ENOTDIR, EBADF, ELOOP -- and the error itself for any other, where `fs.existsSync` answers
1233
+ * false for every failure, a directory it may not enter included.
1234
+ */
1235
+ function pathExists(target) {
1236
+ try {
1237
+ fs.statSync(target);
1238
+ return true;
1239
+ }
1240
+ catch (error) {
1241
+ const code = String(error.code ?? '');
1242
+ if (['ENOENT', 'ENOTDIR', 'EBADF', 'ELOOP'].includes(code))
1243
+ return false;
1244
+ throw fileErrorOf(error, target);
1245
+ }
1246
+ }
1247
+ /**
1248
+ * Whether `target` is a regular file: follows a symlink, is false for a path that is
1249
+ * absent, runs through a file (`ENOTDIR`), or loops -- and RAISES for any other failure, a
1250
+ * parent it may not search among them, as `pathExists` does. `fs.existsSync` answered
1251
+ * false for all of it.
1252
+ */
1253
+ function pathIsFile(target) {
1254
+ try {
1255
+ return fs.statSync(target).isFile();
1256
+ }
1257
+ catch (error) {
1258
+ const code = String(error.code ?? '');
1259
+ if (['ENOENT', 'ENOTDIR', 'EBADF', 'ELOOP'].includes(code))
1260
+ return false;
1261
+ throw fileErrorOf(error, target);
1262
+ }
1263
+ }
1264
+ /**
1265
+ * Whether `target` is a directory: follows a symlink, and is false rather than an error
1266
+ * when it cannot tell.
1267
+ */
1268
+ function pathIsDir(target) {
1269
+ try {
1270
+ return fs.statSync(target).isDirectory();
1271
+ }
1272
+ catch {
1273
+ return false;
1274
+ }
1275
+ }
1276
+ /** The bytes `urlQuote` never escapes, whatever `safe` says: RFC 3986's unreserved set. */
1277
+ const ALWAYS_SAFE = /^[A-Za-z0-9_.~-]$/u;
1278
+ /**
1279
+ * Percent-encoding: the UTF-8 bytes of `text`, each one kept when it is a letter, a digit,
1280
+ * one of `_.-~` or in `safe`, and `%XX` in upper case otherwise. `encodeURIComponent`
1281
+ * keeps `!'()*` and escapes `/`, so it is not this.
1282
+ */
1283
+ function urlQuote(text, safe = '/') {
1284
+ let out = '';
1285
+ for (const byte of Buffer.from(text, 'utf8')) {
1286
+ const ch = String.fromCharCode(byte);
1287
+ out +=
1288
+ byte < 0x80 && (ALWAYS_SAFE.test(ch) || safe.includes(ch))
1289
+ ? ch
1290
+ : `%${byte.toString(16).toUpperCase().padStart(2, '0')}`;
1291
+ }
1292
+ return out;
1293
+ }
1294
+ /**
1295
+ * Percent-decoding: each `%XX` is a byte, and each run of them is decoded as UTF-8, an
1296
+ * invalid sequence becoming U+FFFD; a `%` not followed by two hex digits stays as it is.
1297
+ */
1298
+ function urlUnquote(text) {
1299
+ const decoder = new TextDecoder('utf-8', { fatal: false });
1300
+ let out = '';
1301
+ let bytes = [];
1302
+ const flush = () => {
1303
+ if (bytes.length > 0)
1304
+ out += decoder.decode(Uint8Array.from(bytes));
1305
+ bytes = [];
1306
+ };
1307
+ for (let index = 0; index < text.length; index += 1) {
1308
+ const hex = text.slice(index + 1, index + 3);
1309
+ if (text[index] === '%' && /^[0-9A-Fa-f]{2}$/u.test(hex)) {
1310
+ bytes.push(Number.parseInt(hex, 16));
1311
+ index += 2;
1312
+ }
1313
+ else {
1314
+ flush();
1315
+ out += text[index];
1316
+ }
1317
+ }
1318
+ flush();
1319
+ return out;
1320
+ }