@tonyclaw/llm-inspector 1.10.0 → 1.11.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 (74) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/assets/index-BIZeMR5N.js +105 -0
  3. package/.output/public/assets/index-SmtLx1lM.css +1 -0
  4. package/.output/public/assets/main-QfbQ5oBP.js +17 -0
  5. package/.output/server/_libs/@radix-ui/react-use-controllable-state+[...].mjs +1 -1
  6. package/.output/server/_libs/ajv-formats.mjs +18 -18
  7. package/.output/server/_libs/ajv.mjs +6306 -942
  8. package/.output/server/_libs/cookie-es.mjs +21 -7
  9. package/.output/server/_libs/diff.mjs +320 -0
  10. package/.output/server/_libs/floating-ui__core.mjs +17 -18
  11. package/.output/server/_libs/floating-ui__dom.mjs +20 -24
  12. package/.output/server/_libs/floating-ui__react-dom.mjs +28 -55
  13. package/.output/server/_libs/floating-ui__utils.mjs +36 -36
  14. package/.output/server/_libs/h3-v2.mjs +9 -20
  15. package/.output/server/_libs/isbot.mjs +2 -3
  16. package/.output/server/_libs/json-schema-traverse.mjs +90 -1
  17. package/.output/server/_libs/jszip.mjs +28 -28
  18. package/.output/server/_libs/lucide-react.mjs +103 -80
  19. package/.output/server/_libs/mdast-util-from-markdown.mjs +1 -1
  20. package/.output/server/_libs/pako.mjs +13 -13
  21. package/.output/server/_libs/property-information.mjs +1 -13
  22. package/.output/server/_libs/radix-ui__react-collection.mjs +1 -1
  23. package/.output/server/_libs/radix-ui__react-id.mjs +1 -1
  24. package/.output/server/_libs/react-dom.mjs +10 -10
  25. package/.output/server/_libs/react.mjs +44 -44
  26. package/.output/server/_libs/readable-stream.mjs +15 -15
  27. package/.output/server/_libs/rou3.mjs +7 -1
  28. package/.output/server/_libs/safe-buffer.mjs +3 -3
  29. package/.output/server/_libs/semver.mjs +10 -10
  30. package/.output/server/_libs/seroval-plugins.mjs +5 -5
  31. package/.output/server/_libs/seroval.mjs +596 -606
  32. package/.output/server/_libs/srvx.mjs +245 -10
  33. package/.output/server/_libs/swr.mjs +1 -1
  34. package/.output/server/_libs/tailwind-merge.mjs +41 -286
  35. package/.output/server/_libs/tanstack__history.mjs +44 -31
  36. package/.output/server/_libs/tanstack__react-router.mjs +1089 -780
  37. package/.output/server/_libs/tanstack__react-store.mjs +1 -1
  38. package/.output/server/_libs/tanstack__react-virtual.mjs +7 -82
  39. package/.output/server/_libs/tanstack__router-core.mjs +2331 -2226
  40. package/.output/server/_libs/tanstack__virtual-core.mjs +17 -58
  41. package/.output/server/_libs/tiny-invariant.mjs +12 -0
  42. package/.output/server/_libs/tiny-warning.mjs +5 -0
  43. package/.output/server/_libs/ungap__structured-clone.mjs +2 -14
  44. package/.output/server/_libs/use-sync-external-store.mjs +1 -1
  45. package/.output/server/_libs/zod.mjs +207 -505
  46. package/.output/server/_ssr/{index-XyU4WVWt.mjs → index-I_Nx8QEB.mjs} +532 -79
  47. package/.output/server/_ssr/index.mjs +776 -1098
  48. package/.output/server/_ssr/{router-BR4XO8XJ.mjs → router-BVxfVFsb.mjs} +98 -53
  49. package/.output/server/_tanstack-start-manifest_v-Cm2Owszu.mjs +4 -0
  50. package/.output/server/index.mjs +28 -28
  51. package/README.md +1 -1
  52. package/package.json +2 -1
  53. package/src/components/ProxyViewer.tsx +10 -3
  54. package/src/components/ProxyViewerContainer.tsx +6 -0
  55. package/src/components/proxy-viewer/ConversationGroup.tsx +10 -1
  56. package/src/components/proxy-viewer/LogEntry.tsx +114 -5
  57. package/src/components/proxy-viewer/diff/DiffView.tsx +319 -0
  58. package/src/components/proxy-viewer/diff/computeDiff.ts +178 -0
  59. package/src/components/proxy-viewer/diff/index.ts +3 -0
  60. package/src/components/ui/crab-logo.tsx +45 -0
  61. package/src/proxy/config.ts +3 -17
  62. package/src/proxy/dataDir.ts +56 -0
  63. package/src/proxy/formats/anthropic/stream.ts +5 -2
  64. package/src/proxy/formats/jsonSchema.ts +12 -0
  65. package/src/proxy/formats/openai/stream.ts +21 -16
  66. package/src/proxy/handler.ts +15 -5
  67. package/src/proxy/providers.ts +61 -1
  68. package/src/proxy/schemas.ts +42 -0
  69. package/src/proxy/store.ts +6 -23
  70. package/.output/public/assets/index-BFuUQkWu.js +0 -11
  71. package/.output/public/assets/index-F2ojFPJp.css +0 -1
  72. package/.output/public/assets/index-nKnhyW4Y.js +0 -122
  73. package/.output/server/_ssr/empty-plugin-adapters-BFgPZ6_d.mjs +0 -6
  74. package/.output/server/_tanstack-start-manifest_v-DFoSjBkb.mjs +0 -4
@@ -1,13 +1,13 @@
1
- import { Check, Copy, RotateCcw } from "lucide-react";
1
+ import { Check, Copy, GitCompareArrows, RotateCcw } from "lucide-react";
2
2
  import type { JSX } from "react";
3
3
  import { useMemo, useState, memo } from "react";
4
4
  import { cn } from "../../lib/utils";
5
5
  import { type CapturedLog, parseRequest } from "../../proxy/schemas";
6
6
  import { stripClaudeCodeBillingHeader } from "../../proxy/claudeCodeStrip";
7
- import { useStripConfig } from "../../lib/useStripConfig";
8
7
  import { Button } from "../ui/button";
9
8
  import { JsonViewerFromString } from "../ui/json-viewer";
10
9
  import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
10
+ import { computeHeadersDiff, computeRequestDiff, DiffView } from "./diff";
11
11
  import { LogEntryHeader } from "./LogEntryHeader";
12
12
  import { ReplayDialog } from "./ReplayDialog";
13
13
  import { ResponseView } from "./ResponseView";
@@ -18,6 +18,13 @@ export type LogEntryProps = {
18
18
  viewMode?: "simple" | "full";
19
19
  /** Suppress the API format badge when log is displayed within a group */
20
20
  suppressApiFormatBadge?: boolean;
21
+ /**
22
+ * Live "strip Claude Code billing header" flag, sourced once at the viewer
23
+ * container. Hoisted out of `LogEntry` so a single SWR subscription serves
24
+ * the whole virtualized list (N logs == N subscriptions is the previous
25
+ * cost).
26
+ */
27
+ strip: boolean;
21
28
  };
22
29
 
23
30
  /**
@@ -33,6 +40,33 @@ export function shouldShowRawRequestTab(
33
40
  return apiFormat === "anthropic" && viewMode === "full" && strip;
34
41
  }
35
42
 
43
+ /**
44
+ * Pure visibility rule for the "Diff with Raw" button in the Headers tab.
45
+ * The button only makes sense when the user is in full mode (where the
46
+ * `Raw Headers` tab is shown) and we actually captured raw headers.
47
+ */
48
+ export function shouldShowHeadersDiffButton(
49
+ viewMode: "simple" | "full",
50
+ hasRawHeaders: boolean,
51
+ ): boolean {
52
+ return viewMode === "full" && hasRawHeaders;
53
+ }
54
+
55
+ /**
56
+ * Pure visibility rule for the "Diff with Raw" button in the Request tab.
57
+ * Mirrors the conditions for the `Raw Request` tab itself: full mode plus
58
+ * the strip toggle being on for an anthropic-format request. We also need
59
+ * an actual raw request body to diff against.
60
+ */
61
+ export function shouldShowRequestDiffButton(
62
+ apiFormat: string,
63
+ viewMode: "simple" | "full",
64
+ strip: boolean,
65
+ hasRawRequest: boolean,
66
+ ): boolean {
67
+ return apiFormat === "anthropic" && viewMode === "full" && strip && hasRawRequest;
68
+ }
69
+
36
70
  function CopyButton({
37
71
  text,
38
72
  label,
@@ -66,17 +100,45 @@ function CopyButton({
66
100
  );
67
101
  }
68
102
 
103
+ function DiffToggleButton({
104
+ active,
105
+ onClick,
106
+ }: {
107
+ active: boolean;
108
+ onClick: (e: React.MouseEvent) => void;
109
+ }): JSX.Element {
110
+ return (
111
+ <button
112
+ type="button"
113
+ onClick={onClick}
114
+ aria-pressed={active}
115
+ className={cn(
116
+ "flex items-center gap-1.5 text-xs px-2 py-1 rounded transition-colors",
117
+ active
118
+ ? "bg-primary/10 text-primary"
119
+ : "text-muted-foreground hover:text-foreground hover:bg-muted",
120
+ )}
121
+ title={active ? "Hide diff with raw" : "Diff this view against the raw version"}
122
+ >
123
+ <GitCompareArrows className="size-3" />
124
+ {active ? "Showing diff" : "Diff with Raw"}
125
+ </button>
126
+ );
127
+ }
128
+
69
129
  export const LogEntry = memo(function ({
70
130
  log,
71
131
  viewMode = "simple",
72
132
  suppressApiFormatBadge = false,
133
+ strip,
73
134
  }: LogEntryProps): JSX.Element {
74
135
  const [expanded, setExpanded] = useState<boolean>(false);
75
136
  const [requestCopied, setRequestCopied] = useState<boolean>(false);
76
137
  const [rawRequestCopied, setRawRequestCopied] = useState<boolean>(false);
77
138
  const [responseCopied, setResponseCopied] = useState<boolean>(false);
78
139
  const [replayOpen, setReplayOpen] = useState<boolean>(false);
79
- const { strip } = useStripConfig();
140
+ const [headersDiff, setHeadersDiff] = useState<boolean>(false);
141
+ const [requestDiff, setRequestDiff] = useState<boolean>(false);
80
142
  const parsedRequest = useMemo(() => parseRequest(log.rawRequestBody), [log.rawRequestBody]);
81
143
  const strippedRequestBody = useMemo(() => {
82
144
  if (!strip || log.apiFormat !== "anthropic" || log.rawRequestBody === null) {
@@ -86,6 +148,15 @@ export const LogEntry = memo(function ({
86
148
  }, [log.rawRequestBody, log.apiFormat, strip]);
87
149
  const displayedRequestBody = strippedRequestBody ?? log.rawRequestBody;
88
150
 
151
+ const headersDiffResult = useMemo(
152
+ () => computeHeadersDiff(log.rawHeaders, log.headers),
153
+ [log.rawHeaders, log.headers],
154
+ );
155
+ const requestDiffResult = useMemo(
156
+ () => computeRequestDiff(log.rawRequestBody, displayedRequestBody),
157
+ [log.rawRequestBody, displayedRequestBody],
158
+ );
159
+
89
160
  function handleCopyRequest(e: React.MouseEvent): void {
90
161
  e.stopPropagation();
91
162
  if (displayedRequestBody === null) return;
@@ -161,6 +232,20 @@ export const LogEntry = memo(function ({
161
232
  <TabsContent value="request">
162
233
  <div className="px-4 py-3">
163
234
  <div className="flex justify-end gap-2 mb-2">
235
+ {shouldShowRequestDiffButton(
236
+ log.apiFormat,
237
+ viewMode,
238
+ strip,
239
+ log.rawRequestBody !== null,
240
+ ) && (
241
+ <DiffToggleButton
242
+ active={requestDiff}
243
+ onClick={(e) => {
244
+ e.stopPropagation();
245
+ setRequestDiff(!requestDiff);
246
+ }}
247
+ />
248
+ )}
164
249
  <Button
165
250
  variant="outline"
166
251
  size="sm"
@@ -180,7 +265,12 @@ export const LogEntry = memo(function ({
180
265
  onCopy={handleCopyRequest}
181
266
  />
182
267
  </div>
183
- {displayedRequestBody !== null ? (
268
+ {requestDiff ? (
269
+ <DiffView
270
+ result={requestDiffResult}
271
+ emptyLabel="No transformation applied — raw and sent request bodies are identical."
272
+ />
273
+ ) : displayedRequestBody !== null ? (
184
274
  <JsonViewerFromString text={displayedRequestBody} defaultExpandDepth={1} />
185
275
  ) : (
186
276
  <p className="text-xs text-muted-foreground italic">No request body</p>
@@ -191,7 +281,26 @@ export const LogEntry = memo(function ({
191
281
  {viewMode === "full" && (
192
282
  <TabsContent value="headers">
193
283
  <div className="px-4 py-3">
194
- {log.headers && Object.keys(log.headers).length > 0 ? (
284
+ <div className="flex justify-end gap-2 mb-2">
285
+ {shouldShowHeadersDiffButton(
286
+ viewMode,
287
+ log.rawHeaders !== undefined && Object.keys(log.rawHeaders).length > 0,
288
+ ) && (
289
+ <DiffToggleButton
290
+ active={headersDiff}
291
+ onClick={(e) => {
292
+ e.stopPropagation();
293
+ setHeadersDiff(!headersDiff);
294
+ }}
295
+ />
296
+ )}
297
+ </div>
298
+ {headersDiff ? (
299
+ <DiffView
300
+ result={headersDiffResult}
301
+ emptyLabel="No transformation applied — raw and processed headers are identical."
302
+ />
303
+ ) : log.headers && Object.keys(log.headers).length > 0 ? (
195
304
  <div className="space-y-1 font-mono text-xs">
196
305
  {Object.entries(log.headers)
197
306
  .sort(([a], [b]) => a.localeCompare(b))
@@ -0,0 +1,319 @@
1
+ import { useVirtualizer } from "@tanstack/react-virtual";
2
+ import { Columns2, Rows3 } from "lucide-react";
3
+ import { useRef, useState, type JSX } from "react";
4
+ import { cn } from "../../../lib/utils";
5
+ import type { DiffLine, DiffResult } from "./computeDiff";
6
+
7
+ type DiffMode = "unified" | "split";
8
+
9
+ /**
10
+ * Approximate line height (px) used for the virtualizer's `estimateSize`.
11
+ * Matches the `py-1` + `text-xs` (12px line-height ~ 18px) row padding so
12
+ * the estimate is close enough that we rarely need to re-measure.
13
+ */
14
+ const ESTIMATED_LINE_HEIGHT = 22;
15
+
16
+ /**
17
+ * Cap on how many diff lines we render. Bodies larger than this still get
18
+ * the diff computed (so the line count is accurate) but only the first
19
+ * `MAX_RENDERED_LINES` are shown, with a notice explaining the truncation.
20
+ * This protects the tab from freezing on accidental large payloads.
21
+ */
22
+ const MAX_RENDERED_LINES = 10_000;
23
+
24
+ type DiffViewProps = {
25
+ result: DiffResult;
26
+ /** Optional caption shown in the empty state. */
27
+ emptyLabel?: string;
28
+ };
29
+
30
+ function kindPrefix(kind: "context" | "added" | "removed"): string {
31
+ if (kind === "added") return "+";
32
+ if (kind === "removed") return "-";
33
+ return " ";
34
+ }
35
+
36
+ function kindClass(kind: "context" | "added" | "removed"): string {
37
+ if (kind === "added") {
38
+ return "bg-green-500/10 text-green-700 dark:text-green-300";
39
+ }
40
+ if (kind === "removed") {
41
+ return "bg-red-500/10 text-red-700 dark:text-red-300";
42
+ }
43
+ return "text-foreground/80";
44
+ }
45
+
46
+ /**
47
+ * Render a `DiffResult` in unified or split mode. The unified view is a
48
+ * single column with `+` / `-` / ` ` prefixes; the split view pairs up
49
+ * consecutive removed+added runs into "changed" rows for side-by-side
50
+ * reading.
51
+ *
52
+ * Virtualized because request bodies with full conversation history can be
53
+ * tens of thousands of lines long.
54
+ */
55
+ export function DiffView({ result, emptyLabel }: DiffViewProps): JSX.Element {
56
+ const [mode, setMode] = useState<DiffMode>("unified");
57
+ const scrollRef = useRef<HTMLDivElement>(null);
58
+
59
+ const virtualizer = useVirtualizer({
60
+ count: result.lines.length,
61
+ getScrollElement: () => scrollRef.current,
62
+ estimateSize: () => ESTIMATED_LINE_HEIGHT,
63
+ overscan: 10,
64
+ });
65
+
66
+ if (result.isEmpty) {
67
+ return (
68
+ <div
69
+ className="rounded border border-dashed border-border bg-muted/30 px-4 py-6 text-center text-xs text-muted-foreground"
70
+ data-testid="diff-empty"
71
+ >
72
+ {emptyLabel ?? "No transformation applied — raw and processed are identical."}
73
+ </div>
74
+ );
75
+ }
76
+
77
+ const totalLines = result.lines.length;
78
+ const truncated = totalLines > MAX_RENDERED_LINES;
79
+ const visibleLines = truncated ? result.lines.slice(0, MAX_RENDERED_LINES) : result.lines;
80
+
81
+ return (
82
+ <div className="space-y-2">
83
+ <div className="flex items-center justify-between text-xs text-muted-foreground">
84
+ <span>
85
+ {totalLines.toLocaleString()} line{totalLines === 1 ? "" : "s"}
86
+ {truncated && ` (showing first ${MAX_RENDERED_LINES.toLocaleString()})`}
87
+ </span>
88
+ <div className="inline-flex rounded-md border border-border overflow-hidden">
89
+ <button
90
+ type="button"
91
+ onClick={() => setMode("unified")}
92
+ aria-pressed={mode === "unified"}
93
+ className={cn(
94
+ "flex items-center gap-1 px-2 py-1 transition-colors",
95
+ mode === "unified" ? "bg-muted text-foreground" : "hover:bg-muted/50",
96
+ )}
97
+ title="Unified diff (single column)"
98
+ >
99
+ <Rows3 className="size-3" />
100
+ Unified
101
+ </button>
102
+ <button
103
+ type="button"
104
+ onClick={() => setMode("split")}
105
+ aria-pressed={mode === "split"}
106
+ className={cn(
107
+ "flex items-center gap-1 px-2 py-1 transition-colors border-l border-border",
108
+ mode === "split" ? "bg-muted text-foreground" : "hover:bg-muted/50",
109
+ )}
110
+ title="Split diff (side by side)"
111
+ >
112
+ <Columns2 className="size-3" />
113
+ Split
114
+ </button>
115
+ </div>
116
+ </div>
117
+ <div
118
+ ref={scrollRef}
119
+ className="max-h-[60vh] overflow-auto rounded border border-border bg-background font-mono text-xs"
120
+ data-testid="diff-viewport"
121
+ >
122
+ {mode === "unified" ? (
123
+ <UnifiedRows virtualizer={virtualizer} lines={visibleLines} />
124
+ ) : (
125
+ <SplitRows lines={visibleLines} />
126
+ )}
127
+ </div>
128
+ </div>
129
+ );
130
+ }
131
+
132
+ function UnifiedRows({
133
+ virtualizer,
134
+ lines,
135
+ }: {
136
+ virtualizer: ReturnType<typeof useVirtualizer<HTMLDivElement, Element>>;
137
+ lines: ReadonlyArray<DiffLine>;
138
+ }): JSX.Element {
139
+ return (
140
+ <div
141
+ style={{
142
+ height: `${virtualizer.getTotalSize()}px`,
143
+ width: "100%",
144
+ position: "relative",
145
+ }}
146
+ >
147
+ {virtualizer.getVirtualItems().map((virtualRow) => {
148
+ const line = lines[virtualRow.index];
149
+ if (line === undefined) return null;
150
+ return (
151
+ <div
152
+ key={virtualRow.key}
153
+ data-index={virtualRow.index}
154
+ ref={virtualizer.measureElement}
155
+ className={cn("flex items-start gap-3 px-2", kindClass(line.kind))}
156
+ style={{
157
+ position: "absolute",
158
+ top: 0,
159
+ left: 0,
160
+ width: "100%",
161
+ transform: `translateY(${virtualRow.start}px)`,
162
+ }}
163
+ >
164
+ <span className="select-none text-muted-foreground/60 w-10 text-right tabular-nums">
165
+ {line.oldLineNumber ?? ""}
166
+ </span>
167
+ <span className="select-none text-muted-foreground/60 w-10 text-right tabular-nums">
168
+ {line.newLineNumber ?? ""}
169
+ </span>
170
+ <span
171
+ className={cn(
172
+ "select-none w-3 text-right font-bold",
173
+ line.kind === "added" && "text-green-600 dark:text-green-400",
174
+ line.kind === "removed" && "text-red-600 dark:text-red-400",
175
+ )}
176
+ >
177
+ {kindPrefix(line.kind)}
178
+ </span>
179
+ <span className="whitespace-pre-wrap break-all flex-1">{line.text}</span>
180
+ </div>
181
+ );
182
+ })}
183
+ </div>
184
+ );
185
+ }
186
+
187
+ /**
188
+ * Convert a stream of context / removed / added lines into "rows" suitable
189
+ * for a split view:
190
+ * - A run of `removed` followed by a run of `added` is paired line-by-line
191
+ * as a "changed" row (the shorter side is padded with blanks).
192
+ * - A `removed`-only run becomes rows marked as deletion-only.
193
+ * - An `added`-only run becomes rows marked as addition-only.
194
+ * - `context` lines become rows where both sides show the same text.
195
+ */
196
+ type SplitRow = {
197
+ left: { text: string; lineNumber: number | null } | null;
198
+ right: { text: string; lineNumber: number | null } | null;
199
+ /** "equal" | "changed" | "removed" | "added" */
200
+ kind: "equal" | "changed" | "removed" | "added";
201
+ };
202
+
203
+ function buildSplitRows(lines: ReadonlyArray<DiffLine>): SplitRow[] {
204
+ const rows: SplitRow[] = [];
205
+ let i = 0;
206
+ while (i < lines.length) {
207
+ const line = lines[i];
208
+ if (line === undefined) break;
209
+ if (line.kind === "context") {
210
+ rows.push({
211
+ left: { text: line.text, lineNumber: line.oldLineNumber },
212
+ right: { text: line.text, lineNumber: line.newLineNumber },
213
+ kind: "equal",
214
+ });
215
+ i += 1;
216
+ continue;
217
+ }
218
+ // Collect a run of removes followed by a run of adds.
219
+ const removes: DiffLine[] = [];
220
+ const adds: DiffLine[] = [];
221
+ while (i < lines.length && lines[i]?.kind === "removed") {
222
+ const removed = lines[i];
223
+ if (removed !== undefined) removes.push(removed);
224
+ i += 1;
225
+ }
226
+ while (i < lines.length && lines[i]?.kind === "added") {
227
+ const added = lines[i];
228
+ if (added !== undefined) adds.push(added);
229
+ i += 1;
230
+ }
231
+ const pairCount = Math.max(removes.length, adds.length);
232
+ for (let p = 0; p < pairCount; p += 1) {
233
+ const r = removes[p];
234
+ const a = adds[p];
235
+ if (r !== undefined && a !== undefined) {
236
+ rows.push({
237
+ left: { text: r.text, lineNumber: r.oldLineNumber },
238
+ right: { text: a.text, lineNumber: a.newLineNumber },
239
+ kind: "changed",
240
+ });
241
+ } else if (r !== undefined) {
242
+ rows.push({
243
+ left: { text: r.text, lineNumber: r.oldLineNumber },
244
+ right: null,
245
+ kind: "removed",
246
+ });
247
+ } else if (a !== undefined) {
248
+ rows.push({
249
+ left: null,
250
+ right: { text: a.text, lineNumber: a.newLineNumber },
251
+ kind: "added",
252
+ });
253
+ }
254
+ }
255
+ }
256
+ return rows;
257
+ }
258
+
259
+ function SplitRowClass(kind: SplitRow["kind"]): string {
260
+ switch (kind) {
261
+ case "changed":
262
+ return "bg-amber-500/10";
263
+ case "removed":
264
+ return "bg-red-500/10";
265
+ case "added":
266
+ return "bg-green-500/10";
267
+ case "equal":
268
+ return "";
269
+ }
270
+ }
271
+
272
+ function SplitRows({ lines }: { lines: ReadonlyArray<DiffLine> }): JSX.Element {
273
+ const rows = buildSplitRows(lines);
274
+ return (
275
+ <div data-testid="diff-split">
276
+ {rows.map((row, idx) => (
277
+ <div
278
+ // idx is stable for a given diff result; the rows array is rebuilt
279
+ // when the input `lines` change, so React's reconciliation handles
280
+ // re-renders correctly.
281
+ // biome-ignore lint/suspicious/noArrayIndexKey: see above
282
+ key={idx}
283
+ className={cn("grid grid-cols-2 font-mono text-xs", SplitRowClass(row.kind))}
284
+ >
285
+ <div className="flex items-start gap-2 px-2 border-r border-border/50">
286
+ <span className="select-none text-muted-foreground/60 w-8 text-right tabular-nums">
287
+ {row.left?.lineNumber ?? ""}
288
+ </span>
289
+ <span
290
+ className={cn(
291
+ "select-none w-3 text-right font-bold",
292
+ (row.kind === "removed" || row.kind === "changed") &&
293
+ "text-red-600 dark:text-red-400",
294
+ )}
295
+ >
296
+ {row.left !== null ? "-" : " "}
297
+ </span>
298
+ <span className="whitespace-pre-wrap break-all flex-1">{row.left?.text ?? ""}</span>
299
+ </div>
300
+ <div className="flex items-start gap-2 px-2">
301
+ <span className="select-none text-muted-foreground/60 w-8 text-right tabular-nums">
302
+ {row.right?.lineNumber ?? ""}
303
+ </span>
304
+ <span
305
+ className={cn(
306
+ "select-none w-3 text-right font-bold",
307
+ (row.kind === "added" || row.kind === "changed") &&
308
+ "text-green-600 dark:text-green-400",
309
+ )}
310
+ >
311
+ {row.right !== null ? "+" : " "}
312
+ </span>
313
+ <span className="whitespace-pre-wrap break-all flex-1">{row.right?.text ?? ""}</span>
314
+ </div>
315
+ </div>
316
+ ))}
317
+ </div>
318
+ );
319
+ }
@@ -0,0 +1,178 @@
1
+ import { diffJson, diffLines, type Change } from "diff";
2
+
3
+ /**
4
+ * A single line in a unified diff view.
5
+ *
6
+ * - `kind: "context"` — line present in both sides
7
+ * - `kind: "removed"` — line only in the left (raw) side
8
+ * - `kind: "added"` — line only in the right (processed) side
9
+ *
10
+ * `oldLineNumber` / `newLineNumber` are 1-based and `null` for the side the
11
+ * line is not on. `text` always includes the trailing newline-free content
12
+ * for that line.
13
+ */
14
+ export type DiffLine = {
15
+ kind: "context" | "removed" | "added";
16
+ text: string;
17
+ oldLineNumber: number | null;
18
+ newLineNumber: number | null;
19
+ };
20
+
21
+ /** Result of computing a diff: the normalized lines plus a quick "no change" flag. */
22
+ export type DiffResult = {
23
+ lines: DiffLine[];
24
+ /** True when the two inputs are byte-equal (or semantically equal for JSON). */
25
+ isEmpty: boolean;
26
+ };
27
+
28
+ /**
29
+ * Normalize an HTTP-header record into a deterministic `[lowercaseKey, value]`
30
+ * tuple. Lowercasing the key matches how `buildProxyHeaders` stores raw
31
+ * headers in `handler.ts`, and sorting by key gives stable diffs across
32
+ * different client header orders.
33
+ */
34
+ function normalizeHeaders(headers: Record<string, string> | undefined): Array<[string, string]> {
35
+ if (headers === undefined) return [];
36
+ return Object.entries(headers)
37
+ .map((entry): [string, string] => [entry[0].toLowerCase(), entry[1]])
38
+ .sort(([a], [b]) => a.localeCompare(b));
39
+ }
40
+
41
+ /**
42
+ * Render a header entry as a single line in the form `key: value`. Mirrors
43
+ * the layout used by the existing Headers / Raw Headers tabs in
44
+ * `LogEntry.tsx` so the diff view looks like the same data, just with
45
+ * add/remove highlights.
46
+ */
47
+ function headerLine([key, value]: [string, string]): string {
48
+ return `${key}: ${value}`;
49
+ }
50
+
51
+ /**
52
+ * Convert a list of `diff` library `Change` objects into `DiffLine` records
53
+ * with stable 1-based line numbers on each side. Each change's value is
54
+ * split on `\n` so we can produce per-line rows (the `diff` library groups
55
+ * runs of consecutive equal/added/removed lines into one Change).
56
+ */
57
+ function changesToLines(changes: Change[]): DiffLine[] {
58
+ const lines: DiffLine[] = [];
59
+ let oldNum = 0;
60
+ let newNum = 0;
61
+ for (const change of changes) {
62
+ // Trailing newlines are part of the change's value; dropping the empty
63
+ // string after the final `\n` keeps the line count correct.
64
+ const parts = change.value.split("\n");
65
+ if (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();
66
+ for (const text of parts) {
67
+ if (change.added) {
68
+ newNum += 1;
69
+ lines.push({ kind: "added", text, oldLineNumber: null, newLineNumber: newNum });
70
+ } else if (change.removed) {
71
+ oldNum += 1;
72
+ lines.push({ kind: "removed", text, oldLineNumber: oldNum, newLineNumber: null });
73
+ } else {
74
+ oldNum += 1;
75
+ newNum += 1;
76
+ lines.push({
77
+ kind: "context",
78
+ text,
79
+ oldLineNumber: oldNum,
80
+ newLineNumber: newNum,
81
+ });
82
+ }
83
+ }
84
+ }
85
+ return lines;
86
+ }
87
+
88
+ /**
89
+ * Compute a diff between two HTTP-header records. Headers are normalized
90
+ * (lower-cased keys, sorted) before comparison so that key reordering or
91
+ * case differences don't show as spurious changes.
92
+ *
93
+ * Returns `{ lines, isEmpty: true }` when the two records contain the same
94
+ * key/value pairs, which the UI uses to show a "No transformation applied"
95
+ * placeholder instead of an empty diff.
96
+ */
97
+ export function computeHeadersDiff(
98
+ rawHeaders: Record<string, string> | undefined,
99
+ processedHeaders: Record<string, string> | undefined,
100
+ ): DiffResult {
101
+ const left = normalizeHeaders(rawHeaders).map(headerLine).join("\n");
102
+ const right = normalizeHeaders(processedHeaders).map(headerLine).join("\n");
103
+
104
+ if (left === right) {
105
+ return { lines: [], isEmpty: true };
106
+ }
107
+ const changes = diffLines(left, right);
108
+ return { lines: changesToLines(changes), isEmpty: false };
109
+ }
110
+
111
+ /**
112
+ * Try to parse a string as JSON. Returns the parsed value on success, or
113
+ * `null` on failure. We use this to decide between semantic (`diffJson`) and
114
+ * line-level (`diffLines`) diffs for request bodies. The return type is a
115
+ * union of `null` and the input types `diffJson` accepts, so the call site
116
+ * can pass the result directly without re-narrowing.
117
+ */
118
+ function tryParseJson(text: string): null | string | object {
119
+ try {
120
+ const parsed: unknown = JSON.parse(text);
121
+ if (parsed === null) return parsed;
122
+ if (typeof parsed === "string" || typeof parsed === "object") return parsed;
123
+ // Numbers, booleans, etc. — also valid JSON, but the diffJson overloads
124
+ // only accept string | object, so we surface these as line-diff by
125
+ // returning null.
126
+ return null;
127
+ } catch {
128
+ return null;
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Compute a diff between two request bodies.
134
+ *
135
+ * - If both sides parse as JSON, use `diffJson` for a semantic key-level
136
+ * comparison. Reordering fields, or adding/removing a key inside an
137
+ * object, produces cleaner output than a raw text diff.
138
+ * - If either side is not valid JSON, fall back to `diffLines` of the raw
139
+ * strings. This keeps the diff working for non-JSON bodies (rare in this
140
+ * proxy, but possible) and for partial / truncated bodies.
141
+ *
142
+ * The two inputs are compared as-is. Whitespace and key order in JSON are
143
+ * normalized by the parser, so two semantically-equal bodies will report
144
+ * `isEmpty: true` even if their textual forms differ.
145
+ */
146
+ export function computeRequestDiff(
147
+ rawBody: string | null,
148
+ processedBody: string | null,
149
+ ): DiffResult {
150
+ const left = rawBody ?? "";
151
+ const right = processedBody ?? "";
152
+
153
+ if (left === right) {
154
+ return { lines: [], isEmpty: true };
155
+ }
156
+
157
+ const leftJson = tryParseJson(left);
158
+ const rightJson = tryParseJson(right);
159
+ if (leftJson !== null && rightJson !== null) {
160
+ // diffJson runs canonicalize() on both sides, so key order / whitespace
161
+ // differences are handled before the line diff is built. Two JSON values
162
+ // that are deep-equal produce an empty change set. The overload set
163
+ // includes some signatures that return `undefined` (abortable modes);
164
+ // since we pass no options, the result is always defined in practice,
165
+ // but we guard with a fallback to the line diff for type-safety.
166
+ const changes = diffJson(leftJson, rightJson) ?? [];
167
+ if (changes.length === 1) {
168
+ const first = changes[0];
169
+ if (first !== undefined && !first.added && !first.removed) {
170
+ return { lines: [], isEmpty: true };
171
+ }
172
+ }
173
+ return { lines: changesToLines(changes), isEmpty: false };
174
+ }
175
+
176
+ const changes = diffLines(left, right);
177
+ return { lines: changesToLines(changes), isEmpty: false };
178
+ }
@@ -0,0 +1,3 @@
1
+ export { computeHeadersDiff, computeRequestDiff } from "./computeDiff";
2
+ export type { DiffLine, DiffResult } from "./computeDiff";
3
+ export { DiffView } from "./DiffView";