@slack/radar-mcp 1.20.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +75 -17
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +56 -20
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +138 -36
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/network-detail.d.ts +5 -0
  10. package/dist/mcp/network-detail.js +86 -0
  11. package/dist/mcp/radar-export-get.d.ts +30 -0
  12. package/dist/mcp/radar-export-get.js +49 -0
  13. package/dist/mcp/radar-response.d.ts +11 -1
  14. package/dist/mcp/radar-response.js +23 -3
  15. package/dist/mcp/session-backfill.d.ts +9 -3
  16. package/dist/mcp/session-backfill.js +76 -17
  17. package/dist/mcp/session-detail.js +54 -2
  18. package/dist/mcp/session-enable.d.ts +1 -0
  19. package/dist/mcp/session-enable.js +146 -15
  20. package/dist/mcp/session-query.js +53 -11
  21. package/dist/mcp/snapshot.js +42 -26
  22. package/dist/mcp/sources-gate.js +5 -0
  23. package/dist/mcp/stale-dashboard.d.ts +23 -0
  24. package/dist/mcp/stale-dashboard.js +122 -0
  25. package/dist/mcp/switchboard-spool.d.ts +12 -0
  26. package/dist/mcp/switchboard-spool.js +107 -0
  27. package/dist/mcp/switchboard-tools.d.ts +18 -0
  28. package/dist/mcp/switchboard-tools.js +178 -0
  29. package/dist/mcp/tools.d.ts +4 -1
  30. package/dist/mcp/tools.js +114 -23
  31. package/dist/mcp/web-child-env.d.ts +4 -1
  32. package/dist/mcp/web-child-env.js +4 -1
  33. package/dist/shared/android.d.ts +43 -0
  34. package/dist/shared/android.js +227 -19
  35. package/dist/shared/constants.d.ts +19 -4
  36. package/dist/shared/constants.js +19 -4
  37. package/dist/shared/event-spool.js +3 -2
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/form-body.d.ts +18 -0
  41. package/dist/shared/form-body.js +251 -0
  42. package/dist/shared/ios-logs.d.ts +10 -0
  43. package/dist/shared/ios-logs.js +91 -0
  44. package/dist/shared/ios.d.ts +25 -2
  45. package/dist/shared/ios.js +157 -3
  46. package/dist/{web → shared}/log-session.d.ts +45 -31
  47. package/dist/shared/log-session.js +300 -0
  48. package/dist/shared/radar-request-raw.d.ts +7 -0
  49. package/dist/shared/radar-request-raw.js +89 -0
  50. package/dist/shared/radar-token.d.ts +25 -0
  51. package/dist/shared/radar-token.js +164 -0
  52. package/dist/shared/stream.d.ts +4 -1
  53. package/dist/shared/stream.js +107 -15
  54. package/dist/shared/switchboard-host-store.d.ts +21 -0
  55. package/dist/shared/switchboard-host-store.js +166 -0
  56. package/dist/shared/switchboard-note.d.ts +15 -0
  57. package/dist/shared/switchboard-note.js +92 -0
  58. package/dist/shared/switchboard-report-file.d.ts +5 -0
  59. package/dist/shared/switchboard-report-file.js +26 -0
  60. package/dist/shared/switchboard-report.d.ts +20 -0
  61. package/dist/shared/switchboard-report.js +406 -0
  62. package/dist/shared/switchboard.d.ts +118 -0
  63. package/dist/shared/switchboard.js +487 -0
  64. package/dist/shared/transport.d.ts +43 -3
  65. package/dist/shared/version.d.ts +2 -0
  66. package/dist/shared/version.js +18 -0
  67. package/dist/shared/wire.d.ts +46 -1
  68. package/dist/web/install-app.d.ts +57 -8
  69. package/dist/web/install-app.js +270 -60
  70. package/dist/web/macapp/RadarApp.swift +340 -22
  71. package/dist/web/public/index.html +216 -12
  72. package/dist/web/public/next/app.js +43 -22
  73. package/dist/web/public/next/db.js +4 -1
  74. package/dist/web/public/next/feed.js +604 -59
  75. package/dist/web/public/next/filters.js +158 -40
  76. package/dist/web/public/next/flags.js +3 -0
  77. package/dist/web/public/next/form-body.js +252 -0
  78. package/dist/web/public/next/inspector.js +171 -14
  79. package/dist/web/public/next/prefs.js +5 -2
  80. package/dist/web/public/next/registry.js +35 -3
  81. package/dist/web/public/next/store.js +947 -69
  82. package/dist/web/public/next/switchboard-note.js +93 -0
  83. package/dist/web/public/next/toast.js +9 -5
  84. package/dist/web/public/next/voice-model.js +712 -0
  85. package/dist/web/public/next/voice.js +552 -0
  86. package/dist/web/server.d.ts +20 -9
  87. package/dist/web/server.js +834 -174
  88. package/dist/web/spec.d.ts +11 -6
  89. package/dist/web/spec.js +62 -6
  90. package/package.json +4 -4
  91. package/dist/web/log-session.js +0 -166
@@ -3,32 +3,113 @@
3
3
  // does not spawn a Custom tab). Ported from vanilla renderChips/renderFilters/applyFilters.
4
4
  import { html } from "./html.js";
5
5
  import { useState, useEffect, useRef } from "preact/hooks";
6
- import { store } from "./store.js";
7
- import { MATCH_FIELDS, FIELD_VALUES, FILTER_SOURCES } from "./registry.js";
6
+ import { store, parseExcludeTerm, isGappedFieldTerm } from "./store.js";
7
+ import { useStorePulse } from "./hooks.js";
8
+ import { MATCH_FIELDS, FIELD_VALUES, FILTER_SOURCES, EXCLUDE_MAX_TERMS, EXCLUDE_MAX_TERM_LENGTH } from "./registry.js";
9
+ // The exclude input holds the terms as one string; commas or newlines separate them (a paste
10
+ // from a log usually brings newlines). Trimmed, empties dropped, deduplicated case-insensitively
11
+ // (the server keeps the first spelling too, so what comes back is what was sent), capped here so
12
+ // a runaway paste is cut before it reaches the server, which enforces the same caps. Both cuts
13
+ // are said under the row rather than made silently: a term over the length is dropped, and past
14
+ // the count the first 20 are kept.
15
+ function splitExclude(raw) {
16
+ const seen = new Set();
17
+ let dropped = 0;
18
+ const terms = raw.split(/[,\n]/).map((t) => t.trim()).filter((t) => {
19
+ if (t.length === 0 || seen.has(t.toLowerCase()))
20
+ return false;
21
+ if (t.length > EXCLUDE_MAX_TERM_LENGTH) {
22
+ dropped++;
23
+ return false;
24
+ }
25
+ seen.add(t.toLowerCase());
26
+ return true;
27
+ });
28
+ return { terms, dropped };
29
+ }
30
+ function parseExclude(raw) {
31
+ return splitExclude(raw).terms.slice(0, EXCLUDE_MAX_TERMS);
32
+ }
33
+ function joinExclude(ex) {
34
+ return Array.isArray(ex) ? ex.map(String).join(", ") : "";
35
+ }
36
+ // The copy for a term isGappedFieldTerm flagged. The term was taken, as text; the hint shows the
37
+ // field form the typist likely meant, built from their own field and value so it never names a
38
+ // field this tab does not have. Shared with the toolbar's exclude box in feed.ts.
39
+ export function gappedFieldHint(term) {
40
+ const m = /^([a-z_][a-z0-9_]*):\s+(\S.*)$/i.exec(term.trim());
41
+ // Lowercased, as the parser reads it, so the hint shows the form that is stored.
42
+ const field = m ? m[1].toLowerCase() : "field";
43
+ const value = m ? m[2].trim() : "value";
44
+ return "added as a text term; to match the " + field + " field write " + field + ":" + value + " (no space)";
45
+ }
8
46
  function Chips({ spec }) {
47
+ // The unknown-field mark below is judged on the fields the tab's rows have carried, and those
48
+ // arrive between spec changes, so the chips follow the store's "fields" event as well as the
49
+ // spec. That event fires only when a row brings a new field name, not on the feed's bump for
50
+ // every row, so the chips stay out of the stream's render path.
51
+ useStorePulse(store, "fields");
9
52
  const m = spec.match && typeof spec.match === "object" ? spec.match : {};
10
53
  const items = Object.entries(m).map(([k, v]) => ({ k, v, kind: "match" }));
11
54
  if (spec.bodyContains)
12
55
  items.push({ k: "body contains", v: spec.bodyContains, kind: "body" });
13
56
  if (typeof spec.minLevel === "string" && spec.minLevel)
14
57
  items.push({ k: "level", v: "≥ " + spec.minLevel, kind: "level" });
58
+ // One chip per exclusion, so a preset's noise list is visible and removable term by term.
59
+ if (Array.isArray(spec.exclude))
60
+ for (const t of spec.exclude)
61
+ items.push({ k: "exclude", v: t, kind: "exclude" });
15
62
  if (!items.length)
16
63
  return null;
64
+ // The ✕ is a link in the store's write chain, built from the spec the store holds when its turn
65
+ // comes: a press while another control's push is in flight drops this term from the acked list
66
+ // rather than posting a copy that lacks the other's edit. A term already gone writes nothing.
17
67
  const clear = (it) => {
18
- const next = JSON.parse(JSON.stringify(spec));
19
- if (it.kind === "body")
20
- delete next.bodyContains;
21
- else if (it.kind === "level")
22
- delete next.minLevel;
23
- else {
24
- if (next.match)
25
- delete next.match[it.k];
26
- if (next.match && !Object.keys(next.match).length)
27
- delete next.match;
28
- }
29
- store.setSpec(next, { local: true });
68
+ void store.updateSpec((base) => {
69
+ const next = JSON.parse(JSON.stringify(base));
70
+ if (it.kind === "body")
71
+ delete next.bodyContains;
72
+ else if (it.kind === "level")
73
+ delete next.minLevel;
74
+ else if (it.kind === "exclude") {
75
+ if (!Array.isArray(next.exclude) || !next.exclude.includes(it.v))
76
+ return null;
77
+ next.exclude = next.exclude.filter((t) => t !== it.v);
78
+ if (!next.exclude.length)
79
+ delete next.exclude;
80
+ }
81
+ else {
82
+ if (next.match)
83
+ delete next.match[it.k];
84
+ if (next.match && !Object.keys(next.match).length)
85
+ delete next.match;
86
+ }
87
+ return next;
88
+ }, { local: true });
89
+ };
90
+ // A field:value exclude term naming a field no row of this tab has carried hides nothing yet (a
91
+ // kind:frame remembered on Switchboard and seen on Logs, say). The verdict comes from the rows
92
+ // seen for this source, not from the offered match list: level:WARN hides log rows though level
93
+ // is not offered, and to:Connected hides state records. No rows seen, no verdict. Harmless, not
94
+ // wrong, so no warning glyph or amber (those are a refused term's, and a timed-out write's): the
95
+ // chip keeps its exclude tint, takes a dashed muted edge, and the title says the term has no
96
+ // effect here yet. It stays removable like any other, and the ✕ carries the reason for a screen
97
+ // reader. Read off the store's per-source field set, so no row is walked here.
98
+ const source = (spec.source ?? "all");
99
+ const unknownField = (it) => {
100
+ if (it.kind !== "exclude" || !store.rowsSeen(source))
101
+ return null;
102
+ const t = parseExcludeTerm(String(it.v));
103
+ return "field" in t && !store.fieldSeen(source, t.field) ? t.field : null;
30
104
  };
31
- return html `<div class="chips">${items.map((it) => html `<span class="chip"><b>${it.k}:</b><span class="v">${String(it.v)}</span><span class="x" onClick=${() => clear(it)}>✕</span></span>`)}</div>`;
105
+ // Exclude chips carry the negation tint of the filter box's -term pills, so a hidden-by chip
106
+ // and a shown-if chip read apart at a glance; the title carries a term the width cuts short.
107
+ return html `<div class="chips">${items.map((it) => {
108
+ const unknown = unknownField(it);
109
+ const reason = unknown ? "no row seen on this tab carries the field " + unknown : null;
110
+ const title = reason ? String(it.v) + "; " + reason + ", so it has no effect here yet" : String(it.v);
111
+ return html `<span class=${"chip chip-" + it.kind + (unknown ? " chip-unknown" : "")} title=${title}><b>${it.k}:</b><span class="v">${String(it.v)}</span><button type="button" class="x" aria-label=${"remove " + it.kind + " " + String(it.v) + (reason ? "; " + reason : "")} onClick=${() => clear(it)}>✕</button></span>`;
112
+ })}</div>`;
32
113
  }
33
114
  function MatchRow({ field, value, fields, onChange, onRemove }) {
34
115
  const [open, setOpen] = useState(false);
@@ -51,12 +132,15 @@ function MatchRow({ field, value, fields, onChange, onRemove }) {
51
132
  </div>
52
133
  `;
53
134
  }
54
- export function Filters({ spec }) {
135
+ // `remembered` is the store's specMatchesMode(spec) !== null: a Custom view has no tab to come
136
+ // back to, so its label must not promise the memory a preset tab has (the toolbar says the same).
137
+ export function Filters({ spec, remembered = false }) {
55
138
  const [open, setOpen] = useState(false);
56
139
  const fields = MATCH_FIELDS[spec.source] || [];
57
140
  const [rows, setRows] = useState([]);
58
141
  const [source, setSource] = useState(spec.source || "all");
59
142
  const [body, setBody] = useState(spec.bodyContains || "");
143
+ const [excl, setExcl] = useState(joinExclude(spec.exclude));
60
144
  const [hl, setHl] = useState(spec.highlight || {});
61
145
  const [rate, setRate] = useState(spec.rateWindowSec || 10);
62
146
  const [msg, setMsg] = useState("");
@@ -72,35 +156,65 @@ export function Filters({ spec }) {
72
156
  setRows(Object.entries(m).map(([field, value]) => ({ field, value: String(value) })));
73
157
  setSource(spec.source || "all");
74
158
  setBody(spec.bodyContains || "");
159
+ setExcl(joinExclude(spec.exclude));
75
160
  setHl(spec.highlight || {});
76
161
  setRate(spec.rateWindowSec || 10);
77
162
  }, [spec]);
163
+ // Apply is a link in the store's write chain and builds on the spec the store holds when its
164
+ // turn comes, so a chip pressed while the panel was open is not undone by an Apply that posts
165
+ // the list the panel saw before the press. The panel's own edits (source, match, body, exclude
166
+ // when typed in, highlight, rate) land on top of that spec.
78
167
  const apply = async () => {
79
- const next = JSON.parse(JSON.stringify(spec));
80
- next.source = source;
81
- // The level only means something where log rows are; the server rejects it elsewhere, and a
82
- // rejection from this panel is the last thing it needs.
83
- if (source !== "log" && source !== "all")
84
- delete next.minLevel;
85
- const match = {};
86
- for (const r of rows)
87
- if (r.field && r.value.trim())
88
- match[r.field] = r.value.trim();
89
- next.match = match;
90
- if (body.trim())
91
- next.bodyContains = body.trim();
92
- else
93
- delete next.bodyContains;
94
- if (hl.field && hl.value != null && String(hl.value) !== "" && !isNaN(Number(hl.value))) {
95
- next.highlight = { field: hl.field, op: hl.op || ">", value: Number(hl.value), label: (spec.highlight && spec.highlight.label) || hl.field };
96
- }
97
- else {
98
- delete next.highlight;
99
- }
100
- if (Number(rate) > 0)
101
- next.rateWindowSec = Number(rate);
102
168
  setMsg("applying…");
103
- const r = await store.setSpec(next, { local: true });
169
+ const r = await store.updateSpec((base) => {
170
+ const next = JSON.parse(JSON.stringify(base));
171
+ next.source = source;
172
+ // The level only means something where log rows are; the server rejects it elsewhere, and a
173
+ // rejection from this panel is the last thing it needs.
174
+ if (source !== "log" && source !== "all")
175
+ delete next.minLevel;
176
+ // Same for exclusions on the browsers (db/prefs/flags): no rows with text to exclude from.
177
+ if (source === "db" || source === "prefs" || source === "flags")
178
+ delete next.exclude;
179
+ const match = {};
180
+ for (const r of rows)
181
+ if (r.field && r.value.trim())
182
+ match[r.field] = r.value.trim();
183
+ // An empty match is no field, and a rate window is only written where the spec had one or the
184
+ // person set one: writing the defaults turned an untouched Apply on a preset into a spec the
185
+ // mode bar no longer recognised, so the tab went dark.
186
+ if (Object.keys(match).length)
187
+ next.match = match;
188
+ else
189
+ delete next.match;
190
+ if (body.trim())
191
+ next.bodyContains = body.trim();
192
+ else
193
+ delete next.bodyContains;
194
+ // The browsers had their exclude dropped above; everywhere else a typed input is the list. An
195
+ // untouched input keeps the store's list verbatim: the input joins terms with commas and
196
+ // splits on them, so rebuilding from it would cut an agent-set term like "a, b" in two on
197
+ // every Apply, and the store's list, not the panel's copy, carries a chip pressed meanwhile.
198
+ if (!(source === "db" || source === "prefs" || source === "flags") && excl !== joinExclude(spec.exclude)) {
199
+ const terms = parseExclude(excl);
200
+ if (terms.length)
201
+ next.exclude = terms;
202
+ else
203
+ delete next.exclude;
204
+ }
205
+ if (hl.field && hl.value != null && String(hl.value) !== "" && !isNaN(Number(hl.value))) {
206
+ next.highlight = { field: hl.field, op: hl.op || ">", value: Number(hl.value), label: (base.highlight && base.highlight.label) || hl.field };
207
+ }
208
+ else {
209
+ delete next.highlight;
210
+ }
211
+ const rateChanged = Number(rate) !== (spec.rateWindowSec || 10);
212
+ if (Number(rate) > 0 && (base.rateWindowSec != null || rateChanged))
213
+ next.rateWindowSec = Number(rate);
214
+ else if (base.rateWindowSec != null)
215
+ delete next.rateWindowSec; // blanked: the window the spec had is dropped
216
+ return next;
217
+ }, { local: true });
104
218
  setMsg(r.ok ? "applied ✓" : "⚠ " + (r.error || "rejected"));
105
219
  };
106
220
  return html `
@@ -115,6 +229,10 @@ export function Filters({ spec }) {
115
229
  ${rows.map((r, i) => html `<${MatchRow} field=${r.field} value=${r.value} fields=${fields} onChange=${(nx) => setRows(rows.map((x, j) => (j === i ? nx : x)))} onRemove=${() => setRows(rows.filter((_, j) => j !== i))} />`)}
116
230
  <button class="fadd" onClick=${() => setRows([...rows, { field: fields[0] || "", value: "" }])}>+ add match field</button>
117
231
  ${source === "network" || source === "all" ? html `<div class="frow"><label>body contains</label><input value=${body} placeholder="substring in request/response body" onInput=${(e) => setBody(e.currentTarget.value)} /></div>` : null}
232
+ ${source === "db" || source === "prefs" || source === "flags" ? null : html `<div class="frow excluderow"><label title=${"comma separated, so a term cannot contain one; a field:value term (no space after the colon) hides rows whose field equals the value, case-insensitive; up to " + EXCLUDE_MAX_TERMS + " terms of up to " + EXCLUDE_MAX_TERM_LENGTH + " characters; saved with this " + (remembered ? "tab and remembered when you come back" : "view")}>exclude</label><input class="f_excl" value=${excl} placeholder="term, term" aria-label="exclude terms, comma separated" onInput=${(e) => setExcl(e.currentTarget.value)} /></div>
233
+ ${splitExclude(excl).terms.length > EXCLUDE_MAX_TERMS ? html `<div class="fhint fexclhint">up to ${EXCLUDE_MAX_TERMS} terms; the first ${EXCLUDE_MAX_TERMS} are kept</div>` : null}
234
+ ${splitExclude(excl).dropped > 0 ? html `<div class="fhint fexclhint">up to ${EXCLUDE_MAX_TERM_LENGTH} characters; terms over ${EXCLUDE_MAX_TERM_LENGTH} characters are dropped</div>` : null}
235
+ ${(() => { const gapped = splitExclude(excl).terms.find((t) => isGappedFieldTerm(t, (f) => store.fieldSeen(source, f))); return gapped === undefined ? null : html `<div class="fhint fexclhint">${gappedFieldHint(gapped)}</div>`; })()}`}
118
236
  <div class="fsec">highlight (flag rows)</div>
119
237
  <div class="frow">
120
238
  <input value=${hl.field || ""} placeholder="field e.g. duration_ms" style="flex:2" onInput=${(e) => setHl({ ...hl, field: e.currentTarget.value })} />
@@ -33,6 +33,7 @@
33
33
  // is_overridden, else Server.
34
34
  import { html } from "./html.js";
35
35
  import { useState, useEffect, useCallback, useRef } from "preact/hooks";
36
+ import { normalizeStreamType } from "./registry.js";
36
37
  // A row is unique per (scope, org_id, type, key), not by key alone: the device lists each key once
37
38
  // per scope AND once per signed-in org, and a toggle and an experiment could share a name. Leaving
38
39
  // org out collapsed two workspaces onto one row, so whichever wrote last won. `scope` is a
@@ -228,6 +229,8 @@ export function FlagsBrowser() {
228
229
  catch {
229
230
  return;
230
231
  }
232
+ if (f.type)
233
+ f.type = normalizeStreamType(f.type);
231
234
  if (f.type === "_status") {
232
235
  const state = f.event?.state;
233
236
  // The device came back (reinstall, sleep, re-arm): rows it dropped or re-orged while away
@@ -0,0 +1,252 @@
1
+ // GENERATED by scripts/mirror-shared.mjs from src/shared/form-body.ts. Do not edit; edit the source.
2
+ // Decode an application/x-www-form-urlencoded request body into its fields. A record that carries
3
+ // `request_content_type` (the request's Content-Type, read off the OkHttp body by the device
4
+ // interceptor) is a form or not by that field alone. A record without it predates the field, so a
5
+ // form body is recognised by shape: `key=value&key=value` with nothing that would make it JSON or
6
+ // prose. Slack API POSTs routinely tuck JSON inside a field (blocks, types, client_context), so
7
+ // every decoded value that looks like JSON is parsed too. Pure, never throws.
8
+ //
9
+ // The browser build cannot import from src/shared, so scripts/mirror-shared.mjs copies this file
10
+ // to src/web/public/next/form-body.ts at build time (gitignored). This is the one to edit.
11
+ // Every pair is `name=value` with no whitespace; a trailing empty value (`draft_id=`) is fine.
12
+ const FORM_SHAPE = /^[^=&\s]+=[^&\s]*(&[^=&\s]+=[^&\s]*)*$/;
13
+ // A lone pair needs a field-like key: a base64 blob such as `QUJDRA==` otherwise passes the
14
+ // shape as key `QUJDRA` with value `=`. Real field names start with a letter or underscore and
15
+ // stay short; the padding pattern catches the blobs that happen to start with a letter too.
16
+ const KEY_START = /^[A-Za-z_]/;
17
+ const MAX_LONE_KEY = 64;
18
+ const BASE64_BLOB = /^[A-Za-z0-9+/]+=*$/;
19
+ // A lower-case snake_case key is a field name, never base64 padding (`token=`, `_x=1`).
20
+ const PLAIN_FIELD_NAME = /^[a-z_][a-z0-9_]*$/;
21
+ // Bracket nesting past this is not a payload the tool needs to read, and the dashboard's JSON
22
+ // highlighter recurses one frame per level, so a hostile depth stays a string, marked as left
23
+ // unparsed so the reader knows it was a choice. Real bodies sit far under it: the fixture's `blocks` nest 6
24
+ // deep, and rich_text lists carry their indent as a field rather than by nesting.
25
+ const MAX_JSON_DEPTH = 32;
26
+ const DEPTH_UNPARSED = `JSON nested past ${MAX_JSON_DEPTH} levels; left unparsed`;
27
+ // The declared media type, with or without parameters. Anchored on the type itself so a
28
+ // multipart boundary or a suffix that happens to contain the words does not read as a form.
29
+ const FORM_MEDIA_TYPE = /^\s*application\/x-www-form-urlencoded\s*(;|$)/i;
30
+ // application/json, the +json structured-syntax family (application/vnd.api+json) and the
31
+ // unregistered but seen text/json, with or without parameters.
32
+ const JSON_MEDIA_TYPE = /^\s*(application|text)\/([\w.+-]*\+)?json\s*(;|$)/i;
33
+ // The first two characters of a JSON object or array with something (or nothing) inside. A
34
+ // value like `[WIP] fix` or `{fire}` opens with a bracket too, but not like a JSON token.
35
+ const JSON_OPENER = /^(\{"|\{\}|\[\{|\["|\[\[|\[-?\d|\[(true|false|null)|\[\])/;
36
+ // Split off a tail the device cap left without an `=`: the body was cut inside a field name or
37
+ // right after an `&`. Only applies when a complete pair precedes it, so a bare word stays intact.
38
+ function splitCutTail(body) {
39
+ const amp = body.lastIndexOf("&");
40
+ if (amp > 0 && /^[^=&\s]*$/.test(body.slice(amp + 1))) {
41
+ return { body: body.slice(0, amp), truncated: true };
42
+ }
43
+ return { body, truncated: false };
44
+ }
45
+ // The record's own answer when it has one: `request_content_type` settles the form question
46
+ // without the shape rules. undefined means the record carries no verdict (a build that predates
47
+ // the field), so the caller falls back to shape.
48
+ export function formContentType(contentType) {
49
+ if (typeof contentType !== "string" || contentType.trim() === "")
50
+ return undefined;
51
+ return FORM_MEDIA_TYPE.test(contentType);
52
+ }
53
+ // The record's own answer to "is this JSON?", by the same rule: undefined without a verdict.
54
+ function jsonContentType(contentType) {
55
+ if (typeof contentType !== "string" || contentType.trim() === "")
56
+ return undefined;
57
+ return JSON_MEDIA_TYPE.test(contentType);
58
+ }
59
+ // Is this request body a form? The declared Content-Type wins when the record has one; the shape
60
+ // rules stand in when it does not. One shape rule holds either way: a body that opens like a JSON
61
+ // token (`{"`, `[{`, `[1`; not `[WIP]` or `{fire}`) is not a form, whatever the header says,
62
+ // because URLSearchParams would swallow the whole text as a single key and hide a cut. Both the
63
+ // decode and the caller that skips it for an oversized body go through here, so the two paths
64
+ // cannot disagree about what is a form.
65
+ export function isFormBody(text, contentType) {
66
+ if (typeof text !== "string")
67
+ return false;
68
+ const declared = formContentType(contentType);
69
+ if (declared === undefined)
70
+ return looksLikeFormBody(text);
71
+ const trimmed = text.trim();
72
+ return declared && trimmed.length > 0 && !opensLikeJsonToken(trimmed);
73
+ }
74
+ // The whole-body opener: JSON_OPENER after collapsing whitespace behind the bracket, so a
75
+ // pretty-printed body qualifies and bracketed prose does not.
76
+ function opensLikeJsonToken(trimmed) {
77
+ return JSON_OPENER.test(trimmed.replace(/^([[{])\s+/, "$1"));
78
+ }
79
+ // The whole shape verdict without the decode: the pair pattern plus the lone-pair rules, for a
80
+ // record with no Content-Type of its own.
81
+ export function looksLikeFormBody(text) {
82
+ if (typeof text !== "string")
83
+ return false;
84
+ // Surrounding whitespace (a captured trailing newline) is not part of the body shape.
85
+ const trimmed = text.trim();
86
+ if (trimmed.length === 0 || trimmed[0] === "{" || trimmed[0] === "[")
87
+ return false;
88
+ const { body } = splitCutTail(trimmed);
89
+ if (!FORM_SHAPE.test(body))
90
+ return false;
91
+ if (!body.includes("&")) {
92
+ const key = body.slice(0, body.indexOf("="));
93
+ if (key.length > MAX_LONE_KEY || !KEY_START.test(key))
94
+ return false;
95
+ if (!PLAIN_FIELD_NAME.test(key) && BASE64_BLOB.test(body))
96
+ return false;
97
+ }
98
+ return true;
99
+ }
100
+ export function decodeFormBody(text, contentType) {
101
+ if (!isFormBody(text, contentType))
102
+ return null;
103
+ const { body, truncated } = splitCutTail(text.trim());
104
+ let params;
105
+ try {
106
+ params = new URLSearchParams(body);
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ const fields = [];
112
+ params.forEach((value, key) => {
113
+ const field = { key, value };
114
+ if (opensLikeJson(value) && scanJson(value).depth > MAX_JSON_DEPTH) {
115
+ field.unparsedReason = DEPTH_UNPARSED;
116
+ }
117
+ else {
118
+ const json = parseJsonValue(value);
119
+ if (json !== undefined)
120
+ field.json = json;
121
+ }
122
+ fields.push(field);
123
+ });
124
+ return fields.length ? { fields, truncated } : null;
125
+ }
126
+ function opensLikeJson(value) {
127
+ const c = value[0];
128
+ return c === "{" || c === "[";
129
+ }
130
+ function parseJsonValue(value) {
131
+ if (!opensLikeJson(value))
132
+ return undefined;
133
+ if (scanJson(value).depth > MAX_JSON_DEPTH)
134
+ return undefined;
135
+ try {
136
+ return JSON.parse(value);
137
+ }
138
+ catch {
139
+ return undefined;
140
+ }
141
+ }
142
+ // One linear pass over a JSON-looking value: the deepest `{` / `[` nesting, skipping bracket
143
+ // characters inside strings, and whether the text is still open when it ends (a bracket never
144
+ // closed, or a string never terminated). Open at the end is what a cut looks like; a value that
145
+ // merely ends in a letter (`[1] fix typo`) is balanced and is not.
146
+ function scanJson(value) {
147
+ let depth = 0;
148
+ let deepest = 0;
149
+ let inString = false;
150
+ for (let i = 0; i < value.length; i++) {
151
+ const ch = value[i];
152
+ if (inString) {
153
+ if (ch === "\\")
154
+ i++;
155
+ else if (ch === '"')
156
+ inString = false;
157
+ }
158
+ else if (ch === '"') {
159
+ inString = true;
160
+ }
161
+ else if (ch === "{" || ch === "[") {
162
+ depth++;
163
+ if (depth > deepest)
164
+ deepest = depth;
165
+ }
166
+ else if (ch === "}" || ch === "]") {
167
+ depth--;
168
+ }
169
+ }
170
+ return { depth: deepest, open: depth > 0 || inString };
171
+ }
172
+ // The device caps a captured body, so a long form body can end mid-field. Either the tail was
173
+ // cut inside a field name (dropped at decode time), or the last value opens like a JSON token,
174
+ // did not parse, and is still open where the text ends: it was clipped inside its JSON.
175
+ export function formBodyLooksTruncated(body) {
176
+ if (body.truncated)
177
+ return true;
178
+ const last = body.fields[body.fields.length - 1];
179
+ if (!last || last.json !== undefined)
180
+ return false;
181
+ return valueLooksCut(last.value);
182
+ }
183
+ // The same verdict from the raw text, reading only the last pair, for a body too large to decode.
184
+ export function formTextLooksTruncated(text) {
185
+ if (typeof text !== "string")
186
+ return false;
187
+ const { body, truncated } = splitCutTail(text.trim());
188
+ if (truncated)
189
+ return true;
190
+ const last = body.slice(body.lastIndexOf("&") + 1);
191
+ if (!last.includes("="))
192
+ return false;
193
+ // Read the value off the parsed pair rather than by raw key: a `+` or percent escape in the
194
+ // name would make a raw-key lookup miss.
195
+ const value = [...new URLSearchParams(last).values()][0] ?? "";
196
+ return valueLooksCut(value);
197
+ }
198
+ // Bracket balance decides, not the last character: `[1] fix typo` closes its bracket and is a
199
+ // plain value; `[{"a":1}` closes the inner brace and is still a cut.
200
+ function valueLooksCut(value) {
201
+ return JSON_OPENER.test(value) && scanJson(value).open && parseJsonValue(value) === undefined;
202
+ }
203
+ // The same cut verdict for a whole JSON request body (not a form): it opens like a JSON token,
204
+ // does not parse, and the text ends inside an open bracket or string. `{"a":1}trailing` fails to
205
+ // parse but is balanced, so it is malformed rather than cut and stays unflagged; `[draft` opens
206
+ // with a bracket but not like JSON, so a plain-text body is not flagged either. Whitespace after
207
+ // the opening bracket is collapsed first so a pretty-printed body still qualifies. A record that
208
+ // declares a type that is neither JSON nor form (text/plain, multipart) is text whatever it opens
209
+ // with, so it is never flagged. A declared form body is read by shape here like a record with no
210
+ // declared type: the only form-typed body that can be a cut is one that opens like a JSON token,
211
+ // which isFormBody already refused as a mislabel.
212
+ export function jsonTextLooksCut(text, contentType) {
213
+ if (typeof text !== "string")
214
+ return false;
215
+ if (jsonContentType(contentType) === false && formContentType(contentType) !== true)
216
+ return false;
217
+ const s = text.trim();
218
+ if (!opensLikeJsonToken(s) || !scanJson(s).open)
219
+ return false;
220
+ try {
221
+ JSON.parse(s);
222
+ return false;
223
+ }
224
+ catch {
225
+ return true;
226
+ }
227
+ }
228
+ // Collapse the field list into a plain object: the parsed JSON where a value parsed, else the
229
+ // decoded string. A key that repeats becomes an array in wire order.
230
+ export function formBodyToObject(body) {
231
+ // Built without a prototype so a field named toString, constructor or __proto__ is just a key.
232
+ const out = Object.create(null);
233
+ // Keys seen more than once. Needed because a first value can itself be a JSON array
234
+ // (`attachments=[]`), which must not be mistaken for an accumulator on a repeat.
235
+ const repeated = new Set();
236
+ for (const f of body.fields) {
237
+ const v = f.json !== undefined ? f.json : f.value;
238
+ if (!Object.hasOwn(out, f.key)) {
239
+ out[f.key] = v;
240
+ }
241
+ else if (repeated.has(f.key)) {
242
+ out[f.key].push(v);
243
+ }
244
+ else {
245
+ out[f.key] = [out[f.key], v];
246
+ repeated.add(f.key);
247
+ }
248
+ }
249
+ // Hand back an ordinary object; fromEntries defines own properties, so a `__proto__` key
250
+ // stays a key instead of swapping the prototype the way assignment would.
251
+ return Object.fromEntries(Object.entries(out));
252
+ }