mirror of
https://github.com/JoshiCodes/knock.git
synced 2026-12-04 14:59:41 +01:00
- GraphQL editor with schema introspection, cached schema, autocomplete and explorer - WebSocket: auth and subprotocols in the handshake, text/JSON/hex/file messages, saved messages, live log with filter, search and export, reconnect with backoff - Import from Postman (collections and environments), Bruno, Insomnia, OpenAPI/Swagger and cURL; imported scripts are kept as docs, never run; credentials move to the gitignored secrets file - Code snippets for cURL, fetch, Python, HTTPie, Go, PowerShell; Postman export - Runner for folders and collections with JSON and JUnit reports - knock CLI: send, run, import, auth login/debug/logout - Large JSON responses parsed off the main thread - PKGBUILDs, desktop entry with knock:// handler, CI workflow, README
186 lines
7.3 KiB
Svelte
186 lines
7.3 KiB
Svelte
<script lang="ts">
|
||
import { JSONPath } from 'jsonpath-plus';
|
||
import CodeEditor from '$lib/editor/CodeEditor.svelte';
|
||
import JsonViewer from '$lib/json/JsonViewer.svelte';
|
||
import Icon from '$lib/ui/Icon.svelte';
|
||
import { serialize, toValue, fromValue, type JNode } from '$lib/json/ast';
|
||
import { parseJson } from '$lib/json/parseAsync';
|
||
import { bodyKind } from '$lib/response';
|
||
import { formatBytes } from '$lib/request';
|
||
import type { Tab } from '$lib/state/workspace.svelte';
|
||
import DiffView from './DiffView.svelte';
|
||
import type { Lang } from '$lib/editor/cm';
|
||
|
||
let { tab }: { tab: Tab } = $props();
|
||
let resp = $derived(tab.result!.result.output.response!);
|
||
let text = $derived(tab.result?.bodyText);
|
||
let bytes = $derived(tab.result?.bodyBytes);
|
||
let kind = $derived(bodyKind(resp.content_type, bytes));
|
||
|
||
type Mode = 'pretty' | 'raw' | 'preview' | 'diff';
|
||
let mode = $state<Mode>('pretty');
|
||
let query = $state('');
|
||
let viewer: JsonViewer | undefined = $state();
|
||
let wrap = $state(true);
|
||
|
||
let tree = $state<JNode | null>(null);
|
||
let jsonPretty = $state<string | null>(null);
|
||
let parsing = $state(false);
|
||
$effect(() => {
|
||
const t = text;
|
||
tree = null;
|
||
jsonPretty = null;
|
||
if (kind !== 'json' || t === undefined) return;
|
||
parsing = true;
|
||
let stale = false;
|
||
parseJson(t).then((r) => {
|
||
if (stale) return;
|
||
tree = r.tree;
|
||
jsonPretty = r.tree ? r.pretty : null;
|
||
parsing = false;
|
||
});
|
||
return () => {
|
||
stale = true;
|
||
};
|
||
});
|
||
|
||
let isPath = $derived(query.trim().startsWith('$'));
|
||
let filtered = $derived.by((): { node: JNode | null; error: string | null } => {
|
||
if (!isPath || !tree) return { node: null, error: null };
|
||
try {
|
||
const res = JSONPath({ path: query.trim(), json: toValue(tree) as object, wrap: true });
|
||
return { node: fromValue(res), error: null };
|
||
} catch (e) {
|
||
return { node: null, error: (e as Error).message };
|
||
}
|
||
});
|
||
|
||
let prettyText = $derived.by(() => {
|
||
if (text === undefined) return '';
|
||
if (kind === 'json' && jsonPretty !== null) return jsonPretty;
|
||
if (kind === 'xml' || kind === 'html') return prettyMarkup(text);
|
||
return text;
|
||
});
|
||
|
||
function prettyMarkup(src: string): string {
|
||
if (src.length > 2_000_000 || /\n\s+</.test(src.slice(0, 2000))) return src;
|
||
let depth = 0;
|
||
return src
|
||
.replace(/>\s*</g, '>\n<')
|
||
.split('\n')
|
||
.map((line) => {
|
||
if (/^<\//.test(line)) depth = Math.max(0, depth - 1);
|
||
const out = ' '.repeat(depth) + line;
|
||
if (/^<[^!?/][^>]*[^/]>$/.test(line) && !/^<(br|hr|img|input|meta|link)\b/i.test(line) && !/<\/[^>]+>$/.test(line)) depth++;
|
||
return out;
|
||
})
|
||
.join('\n');
|
||
}
|
||
|
||
let lang = $derived<Lang>(kind === 'json' ? 'json' : kind === 'xml' ? 'xml' : kind === 'html' ? 'html' : 'text');
|
||
let blobUrl = $derived.by(() => {
|
||
if (!bytes || (kind !== 'image' && kind !== 'pdf' && kind !== 'html')) return null;
|
||
return URL.createObjectURL(new Blob([bytes.slice().buffer], { type: resp.content_type ?? 'application/octet-stream' }));
|
||
});
|
||
$effect(() => {
|
||
const u = blobUrl;
|
||
return () => {
|
||
if (u) URL.revokeObjectURL(u);
|
||
};
|
||
});
|
||
|
||
$effect(() => {
|
||
if ((kind === 'image' || kind === 'pdf') && mode === 'pretty') mode = 'preview';
|
||
});
|
||
|
||
function useAsBody(n: JNode) {
|
||
if (!tab.draft) return;
|
||
tab.draft.body = { ...(tab.draft.body ?? { type: 'json' }), type: 'json', content: serialize(n, ' ') };
|
||
tab.preview = false;
|
||
}
|
||
|
||
let hasPrevious = $derived(!!tab.previous);
|
||
let tooLarge = $derived(!!resp.body_file);
|
||
</script>
|
||
|
||
<div class="flex h-full flex-col">
|
||
<div class="flex h-9 shrink-0 items-center gap-1 border-b border-line px-2">
|
||
{#each [['pretty', 'Pretty'], ['raw', 'Raw'], ['preview', 'Preview'], ['diff', 'Diff']] as [id, label]}
|
||
{#if id !== 'preview' || kind === 'html' || kind === 'image' || kind === 'pdf'}
|
||
{#if id !== 'diff' || hasPrevious}
|
||
<button class="rounded px-2 py-0.5 text-[12px] {mode === id ? 'bg-hover text-strong' : 'text-fg-muted hover:text-fg'}" onclick={() => (mode = id as Mode)}>{label}</button>
|
||
{/if}
|
||
{/if}
|
||
{/each}
|
||
<span class="flex-1"></span>
|
||
{#if kind === 'json' && mode === 'pretty' && tree}
|
||
<label class="flex h-6 w-72 items-center gap-1.5 rounded border border-line bg-input px-2 focus-within:border-cyan-deep">
|
||
<Icon name="search" size={11} class="text-fg-subtle" />
|
||
<input
|
||
class="mono min-w-0 flex-1 bg-transparent text-[12px] outline-none placeholder:text-fg-subtle"
|
||
placeholder="Search, or $.path to filter"
|
||
bind:value={query}
|
||
spellcheck="false"
|
||
onkeydown={(e) => {
|
||
if (e.key === 'Enter') viewer?.nextHit(e.shiftKey ? -1 : 1);
|
||
if (e.key === 'Escape') query = '';
|
||
}}
|
||
/>
|
||
{#if query && !isPath && viewer}
|
||
<span class="text-[11px] text-fg-subtle">{viewer.hitCount()}</span>
|
||
{/if}
|
||
</label>
|
||
<button class="rounded px-1.5 py-0.5 text-[12px] text-fg-muted hover:text-fg" onclick={() => viewer?.expandAll(true)} title="Expand all">+</button>
|
||
<button class="rounded px-1.5 py-0.5 text-[12px] text-fg-muted hover:text-fg" onclick={() => viewer?.expandAll(false)} title="Collapse all">−</button>
|
||
{:else if mode === 'raw' || (mode === 'pretty' && kind !== 'json')}
|
||
<button class="rounded px-2 py-0.5 text-[12px] {wrap ? 'text-strong' : 'text-fg-muted'} hover:text-fg" onclick={() => (wrap = !wrap)}>Wrap</button>
|
||
{/if}
|
||
</div>
|
||
|
||
{#if tooLarge}
|
||
<div class="shrink-0 border-b border-line bg-post/8 px-3 py-1.5 text-[12px] text-fg">
|
||
The body is {formatBytes(resp.size)}, more than knock keeps in memory. It was written to <span class="mono selectable">{resp.body_file}</span>; the first megabyte is shown. Use the save button for the full file.
|
||
</div>
|
||
{/if}
|
||
|
||
<div class="min-h-0 flex-1">
|
||
{#if text === undefined || (parsing && kind === 'json' && mode !== 'raw')}
|
||
<p class="p-4 text-fg-subtle">Loading body…</p>
|
||
{:else if resp.size === 0}
|
||
<p class="p-4 text-fg-subtle">The response has no body.</p>
|
||
{:else if mode === 'diff' && tab.previous}
|
||
<DiffView before={tab.previous.bodyText ?? ''} after={text} {kind} />
|
||
{:else if mode === 'preview'}
|
||
{#if kind === 'image' && blobUrl}
|
||
<div class="grid h-full place-items-center overflow-auto bg-[repeating-conic-gradient(var(--k-hover)_0_25%,transparent_0_50%)] bg-[length:16px_16px] p-4">
|
||
<img src={blobUrl} alt="Response" class="max-w-full" />
|
||
</div>
|
||
{:else if kind === 'pdf' && blobUrl}
|
||
<iframe src={blobUrl} title="PDF preview" class="h-full w-full border-0"></iframe>
|
||
{:else if kind === 'html'}
|
||
<!-- No scripts, no same-origin: the page cannot reach knock or the network. -->
|
||
<iframe srcdoc={text} sandbox="" title="HTML preview" class="h-full w-full border-0 bg-white"></iframe>
|
||
{/if}
|
||
{:else if mode === 'pretty' && kind === 'json' && tree}
|
||
{#if isPath}
|
||
{#if filtered.error}
|
||
<p class="p-4 text-delete">{filtered.error}</p>
|
||
{:else if filtered.node}
|
||
<JsonViewer root={filtered.node} onuse={useAsBody} />
|
||
{/if}
|
||
{:else}
|
||
<JsonViewer bind:this={viewer} root={tree} search={query} onuse={useAsBody} />
|
||
{/if}
|
||
{:else if kind === 'binary' && mode !== 'raw'}
|
||
<div class="p-4 text-fg-muted">
|
||
Binary content ({resp.content_type ?? 'unknown type'}, {formatBytes(resp.size)}).
|
||
<button class="text-accent hover:underline" onclick={() => (mode = 'raw')}>Show as text</button>
|
||
</div>
|
||
{:else}
|
||
{#key `${mode}-${wrap}`}
|
||
<CodeEditor value={mode === 'raw' ? text : prettyText} lang={mode === 'raw' ? 'text' : lang} readonly vars={false} />
|
||
{/key}
|
||
{/if}
|
||
</div>
|
||
</div>
|