Skeleton, REST core, variables and JSON editor (M0–M2)
- knock-core: YAML collection format with unknown-field round trip, variable resolution across scopes with secrets and dynamic values, HTTP engine with manual redirects, cookie jar and large-body spill, basic/bearer/API key auth with debug output, assertions and extracts - Tauri app: collection commands, file watcher, SQLite history, keyring-backed secrets - Svelte UI: sidebar tree, tabs, request editor, response viewer, JSON form/code editor with schema hints, environments, settings
@@ -0,0 +1,7 @@
|
|||||||
|
/target
|
||||||
|
/node_modules
|
||||||
|
/dist
|
||||||
|
/src-tauri/gen
|
||||||
|
/src-tauri/target
|
||||||
|
*.secrets.yaml
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
[workspace]
|
||||||
|
resolver = "2"
|
||||||
|
members = ["crates/knock-core", "src-tauri"]
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
license = "MIT"
|
||||||
|
authors = ["Joshua"]
|
||||||
|
|
||||||
|
[workspace.dependencies]
|
||||||
|
knock-core = { path = "crates/knock-core" }
|
||||||
|
anyhow = "1"
|
||||||
|
thiserror = "2"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = { version = "1", features = ["preserve_order"] }
|
||||||
|
serde_yaml_ng = "0.10"
|
||||||
|
indexmap = { version = "2", features = ["serde"] }
|
||||||
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
reqwest = { version = "0.13", default-features = false, features = ["rustls", "http2", "charset", "multipart", "stream", "gzip", "brotli", "deflate", "zstd", "socks", "system-proxy"] }
|
||||||
|
url = "2"
|
||||||
|
base64 = "0.22"
|
||||||
|
uuid = { version = "1", features = ["v4"] }
|
||||||
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
|
rand = "0.8"
|
||||||
|
sha2 = "0.10"
|
||||||
|
tracing = "0.1"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
lto = true
|
||||||
|
codegen-units = 1
|
||||||
|
strip = true
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# Knock — Design Guidelines
|
||||||
|
|
||||||
|
Brand basics for Knock: logo usage, color, and type. Assets live in `logo/`.
|
||||||
|
|
||||||
|
## Concept
|
||||||
|
|
||||||
|
Knock is a peephole with a prompt for a pupil. You knock on an API, look through the door, and see what comes back. The ring is the door and the `>` is the terminal. The same shape is the app icon and the **o** in the wordmark, so icon and wordmark always read as one system.
|
||||||
|
|
||||||
|
## Logo
|
||||||
|
|
||||||
|
### Assets
|
||||||
|
|
||||||
|
| File | Use |
|
||||||
|
| --- | --- |
|
||||||
|
| `logo/knock-app-icon.svg` | App icon (512×512 tile). Source for `.desktop`, `.png`, `.ico` and `.icns` exports. |
|
||||||
|
| `logo/knock-favicon.svg` | 16–24 px only (favicon, tray). Heavier strokes so it doesn't fall apart at small sizes. |
|
||||||
|
| `logo/knock-mark.svg` | Mark on dark backgrounds, transparent, Knock Cyan. |
|
||||||
|
| `logo/knock-mark-on-light.svg` | Mark on light backgrounds, Cyan Deep. |
|
||||||
|
| `logo/knock-mark-mono.svg` | Mark in `currentColor`, for UI, monochrome and print. |
|
||||||
|
| `logo/knock-wordmark-on-dark.svg` | Wordmark on dark backgrounds. |
|
||||||
|
| `logo/knock-wordmark-on-light.svg` | Wordmark on light backgrounds. |
|
||||||
|
| `logo/knock-wordmark-mono.svg` | Wordmark in `currentColor`. |
|
||||||
|
|
||||||
|
The wordmark is fully outlined (Space Grotesk Bold). It doesn't need the font installed.
|
||||||
|
|
||||||
|
### Construction (mark)
|
||||||
|
|
||||||
|
Drawn on a 100×100 grid. All strokes have round caps and joins.
|
||||||
|
|
||||||
|
- Ring: center `50,50`, radius `36`, stroke `12`, so the outer edge is 42 and the inner edge is 30.
|
||||||
|
- Chevron: `M45 40 L55 50 L45 60`, stroke `10`. It sits optically centered and keeps clear air to the ring on every side.
|
||||||
|
- Favicon variant: ring stroke `16`, chevron `M46 40 L55 50 L46 60` with stroke `15`, on a 16 px tile with a 3.5 px radius.
|
||||||
|
- App icon: tile `#101318`, corner radius ≈ 22 % (114 / 512). The mark takes 58 % of the tile width and is centered.
|
||||||
|
|
||||||
|
### Where to use what
|
||||||
|
|
||||||
|
- **In the app**, the icon does the work: dock or taskbar, start menu entry, window icon. The titlebar shows the 18 px mark and the word "knock" set in Space Grotesk Bold, not the outlined wordmark.
|
||||||
|
- The **wordmark** is for About, the splash screen, the website, the README header and social images.
|
||||||
|
- Below 24 px, always use `knock-favicon.svg`.
|
||||||
|
|
||||||
|
### Clear space and minimum size
|
||||||
|
|
||||||
|
- Clear space around the mark: at least ¼ of its width on every side. Around the wordmark: at least the height of the **o**.
|
||||||
|
- Minimum sizes: mark 16 px (favicon variant), app icon 32 px, wordmark 64 px wide on screen.
|
||||||
|
|
||||||
|
### Don'ts
|
||||||
|
|
||||||
|
- Don't recolor the letters of the wordmark in the accent. Only the **o** carries color.
|
||||||
|
- Don't put the mark in a plain circle or anything other than the defined tile.
|
||||||
|
- Don't stretch, rotate or outline it, and don't add shadows or gradients.
|
||||||
|
- Don't use Knock Cyan on light backgrounds (2.0:1). Use Cyan Deep there.
|
||||||
|
- Don't rebuild the wordmark from live text with a fallback font.
|
||||||
|
|
||||||
|
## Color
|
||||||
|
|
||||||
|
Dark-first, matching how the app is used. One accent, everything else neutral. Contrast is WCAG 2 relative to the background in the "on" column.
|
||||||
|
|
||||||
|
### Brand
|
||||||
|
|
||||||
|
| Token | Hex | Role | Contrast |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `knock-cyan` | `#2EC4F1` | Accent: logo, primary buttons, active state, `GET` | 9.1:1 on `ink-900` |
|
||||||
|
| `knock-cyan-deep` | `#0B7FAD` | Accent on light backgrounds (logo, links) | 4.5:1 on white, 4.1:1 on `paper-100` (logo only, no body text) |
|
||||||
|
| `on-accent` | `#101318` | Text and icons on Knock Cyan | 9.1:1 on `knock-cyan` |
|
||||||
|
|
||||||
|
### Neutrals: dark (app)
|
||||||
|
|
||||||
|
| Token | Hex | Role |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `ink-950` | `#0E1014` | Titlebar, deepest layer |
|
||||||
|
| `ink-900` | `#101318` | App icon tile, base background |
|
||||||
|
| `ink-850` | `#111419` | Sidebar |
|
||||||
|
| `ink-800` | `#15181E` | Main panel |
|
||||||
|
| `ink-700` | `#1E222A` | Inputs, URL bar, code blocks |
|
||||||
|
| `ink-600` | `#232833` | Active tab, hover, skeletons |
|
||||||
|
| `text-strong` | `#F4F6F8` | Headings, wordmark letters (17.2:1 on `ink-900`) |
|
||||||
|
| `text` | `#E3E7EC` | Body text (14.3:1 on `ink-800`) |
|
||||||
|
| `text-soft` | `#C9CED6` | Secondary text (11.7:1 on `ink-850`) |
|
||||||
|
| `text-muted` | `#A9B0BC` | Meta info, inactive tabs (8.2:1 on `ink-800`) |
|
||||||
|
| `text-subtle` | `#8A93A2` | Section labels such as COLLECTIONS (5.7:1 on `ink-800`) |
|
||||||
|
|
||||||
|
### Neutrals: light (website, docs)
|
||||||
|
|
||||||
|
| Token | Hex | Role |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `paper` | `#FFFFFF` | Background |
|
||||||
|
| `paper-100` | `#F2F3F5` | Cards, surfaces |
|
||||||
|
| `ink-900` | `#101318` | Text, wordmark letters |
|
||||||
|
| `slate-500` | `#5B6270` | Secondary text (6.1:1 on white, 5.5:1 on `paper-100`) |
|
||||||
|
|
||||||
|
### Status and HTTP methods
|
||||||
|
|
||||||
|
All values are checked against `ink-800` and are meant for the dark UI.
|
||||||
|
|
||||||
|
| Token | Hex | Use | Contrast |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `method-get` | `#2EC4F1` | GET (same as the accent) | 8.7:1 |
|
||||||
|
| `method-post` | `#F5B85C` | POST, warnings | 10.5:1 on `ink-850` |
|
||||||
|
| `method-put` | `#B8A1FF` | PUT | 8.1:1 |
|
||||||
|
| `method-patch` | `#F59FD0` | PATCH | 9.1:1 |
|
||||||
|
| `method-delete` | `#FF5C5C` | DELETE, errors, 4xx/5xx | 5.9:1 |
|
||||||
|
| `status-ok` | `#7CF29A` | 2xx, success | 12.7:1 |
|
||||||
|
|
||||||
|
Method colors are always paired with the method name. Color never carries meaning on its own.
|
||||||
|
|
||||||
|
## Typography
|
||||||
|
|
||||||
|
| Role | Font | Weights |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| UI, headings, wordmark | Space Grotesk | 500, 700 |
|
||||||
|
| URLs, headers, bodies, code | JetBrains Mono | 500 |
|
||||||
|
|
||||||
|
Both fonts are under the SIL Open Font License and can be bundled with the app.
|
||||||
|
|
||||||
|
## CSS tokens
|
||||||
|
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
--knock-cyan: #2EC4F1;
|
||||||
|
--knock-cyan-deep: #0B7FAD;
|
||||||
|
--on-accent: #101318;
|
||||||
|
|
||||||
|
--ink-950: #0E1014;
|
||||||
|
--ink-900: #101318;
|
||||||
|
--ink-850: #111419;
|
||||||
|
--ink-800: #15181E;
|
||||||
|
--ink-700: #1E222A;
|
||||||
|
--ink-600: #232833;
|
||||||
|
|
||||||
|
--text-strong: #F4F6F8;
|
||||||
|
--text: #E3E7EC;
|
||||||
|
--text-soft: #C9CED6;
|
||||||
|
--text-muted: #A9B0BC;
|
||||||
|
--text-subtle: #8A93A2;
|
||||||
|
|
||||||
|
--paper: #FFFFFF;
|
||||||
|
--paper-100: #F2F3F5;
|
||||||
|
--slate-500: #5B6270;
|
||||||
|
|
||||||
|
--method-get: #2EC4F1;
|
||||||
|
--method-post: #F5B85C;
|
||||||
|
--method-put: #B8A1FF;
|
||||||
|
--method-patch: #F59FD0;
|
||||||
|
--method-delete: #FF5C5C;
|
||||||
|
--status-ok: #7CF29A;
|
||||||
|
|
||||||
|
--font-sans: "Space Grotesk", system-ui, sans-serif;
|
||||||
|
--font-mono: "JetBrains Mono", ui-monospace, monospace;
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Joshua
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,497 @@
|
|||||||
|
# Knock – Spec Sheet v1
|
||||||
|
|
||||||
|
Nov 27, 2026 · @Joshua
|
||||||
|
|
||||||
|
## 1. Überblick
|
||||||
|
|
||||||
|
Knock ist ein Desktop-API-Client für REST, GraphQL und WebSocket, der auf Linux (KDE/Arch) zuhause ist, offline und ohne Account läuft und seine Collections als Plain Files im Git ablegt. Zwei Dinge sind der Grund, warum es Knock gibt: ein JSON-Body-Editor, in dem man nicht ständig Klammern tippt, und ein OAuth2/OIDC-Flow, der sich selbst um Tokens kümmert und dabei nichts versteckt (vor allem nicht die Redirect URI).
|
||||||
|
|
||||||
|
**Ziele für v1**
|
||||||
|
|
||||||
|
- Voller Alltags-Ersatz für Postman/Bruno bei REST, GraphQL und WebSocket
|
||||||
|
- Auth für praktisch alles, was einem begegnet (Basic bis OIDC, mTLS, AWS SigV4)
|
||||||
|
- JSON-Body per Form/Tree-UI bearbeitbar, verlustfrei umschaltbar auf Code
|
||||||
|
- OAuth2/OIDC komplett automatisiert: Login einmal, danach Auto-Refresh und Auto-Attach
|
||||||
|
- Collections als diff-bare Textdateien, Secrets nie im Repo
|
||||||
|
- Linux als Primärplattform: nativer Startmenü-Eintrag, Wayland und X11, Arch-Paket
|
||||||
|
|
||||||
|
**Nicht-Ziele für v1**
|
||||||
|
|
||||||
|
- Cloud-Sync, Accounts, Teams, Kommentare, Workspaces
|
||||||
|
- Mock-Server, Monitore, API-Doku-Hosting
|
||||||
|
- gRPC, MQTT, SOAP-Wizard (kommt eventuell später)
|
||||||
|
- KI-Features
|
||||||
|
|
||||||
|
**Prioritäten in diesem Dokument**
|
||||||
|
|
||||||
|
| Tag | Bedeutung |
|
||||||
|
| --- | --- |
|
||||||
|
| P0 | Muss in v1, ohne das ist es kein Client |
|
||||||
|
| P1 | Soll in v1, fliegt notfalls in v1.1 |
|
||||||
|
| P2 | Nach v1 |
|
||||||
|
|
||||||
|
**Plattformen**
|
||||||
|
|
||||||
|
- Linux (x86\_64): Primärziel, wird zuerst gebaut und getestet (KDE Plasma, Wayland und X11)
|
||||||
|
- Windows und macOS: Best Effort über den Tauri-Bundler, kein Blocker für v1 (Annahme, siehe offene Fragen)
|
||||||
|
|
||||||
|
## 2. Tech Stack und Architektur
|
||||||
|
|
||||||
|
Tauri 2 mit Rust-Core und Svelte-5-Frontend, weil das zu deinem bestehenden Stack passt (Svelte 5, Tailwind 4, Cock-Komponenten) und ein kleines, schnelles Binary liefert. Der gesamte Netzwerkverkehr läuft im Rust-Core, nicht im WebView, damit CORS, TLS-Optionen, Redirect-Kontrolle und Timing-Daten voll in deiner Hand sind.
|
||||||
|
|
||||||
|
| Schicht | Wahl | Grund |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| App-Shell | Tauri 2 | Kleines Binary, Bundler für deb/rpm/AppImage/Windows/macOS |
|
||||||
|
| UI | Svelte 5, Tailwind 4, Cock | Bestehender Stack und Komponentenkit |
|
||||||
|
| Code-Editor | CodeMirror 6 | Leichtgewichtig, gut erweiterbar (Variablen-Chips, JSON-Lint) |
|
||||||
|
| HTTP | Rust: `reqwest` (rustls) oder `hyper`, HTTP/1.1 und HTTP/2 | Volle Kontrolle über TLS, Proxy, Redirects, Timing |
|
||||||
|
| WebSocket | `tokio-tungstenite` | Async, Subprotocols, eigene Header |
|
||||||
|
| GraphQL | Eigener Client auf HTTP plus Introspection | Schema für Autocomplete |
|
||||||
|
| OAuth/OIDC | Eigener Flow-Code im Core (`oauth2`/`openidconnect`-Crates prüfen) | Flow-Log und Fehlertexte selbst steuern |
|
||||||
|
| Secrets | Secret Service via `keyring` (libsecret/KWallet) | Kein Klartext im Repo |
|
||||||
|
| Lokale Daten | SQLite (History, Cookies, Token-Metadaten) | Durchsuchbar, robust |
|
||||||
|
| Scripting | `rquickjs` (QuickJS) in Sandbox | Klein, ohne Node-Abhängigkeit (P1) |
|
||||||
|
|
||||||
|
**Aufteilung**
|
||||||
|
|
||||||
|
- `knock-core` (Rust-Crate): Request-Engine, Auth, OAuth, Variablen, Collection-Parser, Runner. Kein UI-Bezug.
|
||||||
|
- `knock-app` (Tauri): Commands/Events zwischen Core und UI, Dateisystem-Watcher, Keyring.
|
||||||
|
- `knock-cli` (Rust-Binary, nutzt `knock-core`): `knock send` und `knock run` für CI und Terminal.
|
||||||
|
- Frontend: reine Darstellung und Editoren, kein eigener Netzwerkcode.
|
||||||
|
|
||||||
|
**Warum Core getrennt**
|
||||||
|
|
||||||
|
CLI und App teilen sich damit exakt dieselbe Logik. Ein Request verhält sich im Runner genauso wie in der GUI.
|
||||||
|
|
||||||
|
**UI-Kit: Cock**
|
||||||
|
|
||||||
|
Das Frontend baut auf [Cock](https://cock.joshicodes.de) (`@joshicodes/cock`, Svelte 5 und Tailwind 4, ca. 90 Komponenten, Dark Mode, Theming über Farbvariablen). Für die Umsetzung (auch durch Coding-Agents) gelten diese Quellen: [llms.txt](https://cock.joshicodes.de/llms.txt) als Index und [llms-full.txt](https://cock.joshicodes.de/llms-full.txt) mit der vollständigen Doku. Was Cock nicht hat (z. B. Code-Editor, virtualisierte Tree-Ansicht, Split-Panes), wird in Knock gebaut und bei Bedarf zurück in Cock gespielt.
|
||||||
|
|
||||||
|
## 3. Datenmodell und Dateiformat
|
||||||
|
|
||||||
|
Eine Collection ist ein Ordner mit YAML-Dateien: eine Datei pro Request, Unterordner sind Folders. Das ist diff-bar, merge-bar und lässt sich ohne Knock lesen. Der JSON-Body bleibt dabei echter JSON-Text, damit Tree-Editor und Code-Ansicht verlustfrei dasselbe Ding bearbeiten.
|
||||||
|
|
||||||
|
```
|
||||||
|
my-api/
|
||||||
|
knock.yaml # collection manifest: name, base settings, collection auth
|
||||||
|
environments/
|
||||||
|
local.yaml
|
||||||
|
prod.yaml
|
||||||
|
prod.secrets.yaml # gitignored by default, or stored in keyring
|
||||||
|
users/
|
||||||
|
folder.yaml # folder-level auth, headers, variables
|
||||||
|
create-user.yaml
|
||||||
|
list-users.yaml
|
||||||
|
realtime/
|
||||||
|
events.ws.yaml # WebSocket request
|
||||||
|
```
|
||||||
|
|
||||||
|
**Beispiel: Request-Datei**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
name: Create user
|
||||||
|
type: http
|
||||||
|
method: POST
|
||||||
|
url: "{{baseUrl}}/users"
|
||||||
|
params:
|
||||||
|
query: []
|
||||||
|
path: {}
|
||||||
|
headers:
|
||||||
|
- { name: Accept, value: application/json }
|
||||||
|
auth: inherit # none | inherit | basic | bearer | oauth2 | ...
|
||||||
|
body:
|
||||||
|
type: json
|
||||||
|
content: |
|
||||||
|
{
|
||||||
|
"name": "{{userName}}",
|
||||||
|
"roles": ["admin"]
|
||||||
|
}
|
||||||
|
extract:
|
||||||
|
- { var: userId, from: json, path: $.id }
|
||||||
|
assert:
|
||||||
|
- { on: status, equals: 201 }
|
||||||
|
```
|
||||||
|
|
||||||
|
**Regeln**
|
||||||
|
|
||||||
|
- IDs sind Dateipfade, kein UUID-Zwang. Umbenennen im Dateisystem funktioniert.
|
||||||
|
- Reihenfolge der Requests in der Sidebar steht in `folder.yaml` (`order: [...]`), nicht im Dateinamen.
|
||||||
|
- Unbekannte Felder werden beim Speichern erhalten (Vorwärtskompatibilität).
|
||||||
|
- Dateien werden bei Änderungen von außen (Git-Pull, Editor) live neu geladen.
|
||||||
|
- Secrets (Passwörter, Client Secrets, Tokens) stehen nie in Request-Dateien. Dort steht nur `{{secret.name}}`, der Wert kommt aus Keyring oder `*.secrets.yaml`.
|
||||||
|
- Format ist versioniert (`version: 1` im Manifest), mit Migrationspfad.
|
||||||
|
|
||||||
|
## 4. Request-Editor und Response-Viewer
|
||||||
|
|
||||||
|
**HTTP-Requests (REST)**
|
||||||
|
|
||||||
|
| Feature | Prio | Details |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Methoden | P0 | GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, plus freie Methode |
|
||||||
|
| URL-Leiste | P0 | Variablen-Highlighting, Query-Params bidirektional mit Params-Tabelle synchron |
|
||||||
|
| Path-Params | P0 | `:id` in der URL wird zur editierbaren Zeile |
|
||||||
|
| Headers | P0 | Tabelle mit Enable-Checkbox, Autocomplete für Namen und gängige Werte, Bulk-Edit als Text |
|
||||||
|
| Body-Typen | P0 | none, JSON, raw (text, XML, HTML), `x-www-form-urlencoded`, multipart (Dateien), binary |
|
||||||
|
| Request-Settings | P0 | Timeout, Redirects folgen (max N), TLS-Verify an/aus, HTTP-Version (1.1, 2, auto) |
|
||||||
|
| Client-Zertifikate | P1 | mTLS pro Host, PEM oder PKCS#12 |
|
||||||
|
| Proxy | P1 | `HTTP(S)_PROXY`/`NO_PROXY` respektieren, pro Collection überschreibbar, eigene CA-Bundles |
|
||||||
|
| Cookie-Jar | P1 | Pro Collection, einsehbar und löschbar, pro Request abschaltbar |
|
||||||
|
| Docs pro Request | P1 | Markdown-Notizfeld |
|
||||||
|
|
||||||
|
**GraphQL**
|
||||||
|
|
||||||
|
- P0: Query-Editor mit Syntax-Highlighting, Variables als JSON (nutzt den JSON-Editor aus Abschnitt 5), Operation-Name, Header.
|
||||||
|
- P0: Introspection per Knopfdruck, Schema wird gecacht.
|
||||||
|
- P1: Autocomplete und Validierung gegen das Schema, Schema-Explorer als Seitenleiste.
|
||||||
|
- P2: Subscriptions über `graphql-transport-ws`.
|
||||||
|
|
||||||
|
**WebSocket**
|
||||||
|
|
||||||
|
- P0: URL, eigene Header, Subprotocols, Auth wie bei HTTP (Bearer, OAuth-Token wird im Handshake mitgeschickt).
|
||||||
|
- P0: Message-Composer (Text, JSON mit dem JSON-Editor, Binary als Hex oder Datei), Senden per Strg+Enter.
|
||||||
|
- P0: Live-Log mit Richtung (gesendet/empfangen), Zeitstempel, Größe; Filter und Suche; JSON-Nachrichten klappbar.
|
||||||
|
- P1: Gespeicherte Nachrichten pro Request, Auto-Reconnect mit Backoff, Ping/Pong-Anzeige, Log als Datei exportieren.
|
||||||
|
- P2: SSE als eigener Request-Typ (technisch wenig Aufwand, deshalb direkt nach v1).
|
||||||
|
|
||||||
|
**Response-Viewer**
|
||||||
|
|
||||||
|
- P0: Status, Zeit, Größe; Body mit Pretty-Print und Syntax-Highlighting (JSON, XML, HTML, Text); Raw-Ansicht; Header-Tab; Cookie-Tab.
|
||||||
|
- P0: Große Bodies (bis 50 MB) ohne UI-Freeze durch virtualisierte Anzeige; darüber Streaming auf Platte mit Hinweis.
|
||||||
|
- P0: JSON-Ansicht mit Klappen, Suche und Filter per JSONPath; Pfad eines Knotens per Klick kopieren.
|
||||||
|
- P1: Timeline-Tab: DNS, TCP, TLS, TTFB, Download, Redirect-Kette, genutzte HTTP-Version und Cipher.
|
||||||
|
- P1: Preview für Bilder, PDF, HTML (sandboxed); Response als Datei speichern.
|
||||||
|
- P1: Response-Vergleich mit der letzten Antwort desselben Requests (Diff).
|
||||||
|
|
||||||
|
## 5. JSON-Body-Editor (Form/Tree)
|
||||||
|
|
||||||
|
Der Body-Tab für JSON hat zwei gleichberechtigte Ansichten auf denselben Text: **Form** (Tree mit Eingabefeldern) und **Code** (CodeMirror). Umschalten per Toggle oder Strg+Shift+J, ohne Verlust von Key-Reihenfolge oder Variablen.
|
||||||
|
|
||||||
|
**Form-Ansicht (P0)**
|
||||||
|
|
||||||
|
- Jede Zeile: Key, Typ-Dropdown (string, number, boolean, null, object, array), Wert-Feld.
|
||||||
|
- Objekte und Arrays klappbar, Kinder eingerückt. Zeile hinzufügen, duplizieren, löschen, per Drag-and-drop umsortieren (Arrays und Object-Keys).
|
||||||
|
- Typwechsel versucht den Wert zu konvertieren (`"5"` zu `5`), sonst Warnung statt stiller Datenverlust.
|
||||||
|
- Wert-Feld je Typ: Textfeld, Number-Input, Toggle, `null`-Badge; mehrzeiliger String öffnet ein Popover.
|
||||||
|
- Variablen `{{var}}` sind in jedem String-Feld als Chip dargestellt, mit Autocomplete beim Tippen von `{{`. Hover zeigt aufgelösten Wert und Quelle (siehe Abschnitt 8).
|
||||||
|
- Variable als ganzer Wert (z. B. Zahl): Typ "variable" erzeugt `{{count}}` ohne Anführungszeichen, die Code-Ansicht bleibt dadurch gültiges Template.
|
||||||
|
- Große Zahlen (>2^53) bleiben als Text erhalten, werden nie als Float zerrundet.
|
||||||
|
|
||||||
|
**Code-Ansicht (P0)**
|
||||||
|
|
||||||
|
- JSON-Lint inline, Auto-Closing von Klammern, Format und Minify per Shortcut, Kommentare nur optional (JSONC-Toggle, wird beim Senden entfernt).
|
||||||
|
- Fehler zeigen Zeile und Spalte; bei ungültigem JSON ist die Form-Ansicht ausgegraut mit Hinweis statt leerer Tree.
|
||||||
|
|
||||||
|
**Komfort**
|
||||||
|
|
||||||
|
- P0: Einfügen von JSON aus der Zwischenablage in die Form-Ansicht (Rechtsklick auf Knoten: "Einfügen als Kind").
|
||||||
|
- P0: "Von Response übernehmen": Teil der letzten Antwort per Klick als Body-Vorlage übernehmen.
|
||||||
|
- P1: JSON Schema oder OpenAPI-Schema pro Request anhängen: Form schlägt Felder vor, markiert Pflichtfelder, zeigt Enums als Dropdown und validiert live.
|
||||||
|
- P1: Body aus OpenAPI-Operation generieren (Beispielwerte aus dem Schema).
|
||||||
|
- P2: Generatoren für Testdaten (`{{$randomEmail}}` u. ä.) mit Vorschau.
|
||||||
|
|
||||||
|
**Wiederverwendbar**
|
||||||
|
|
||||||
|
Derselbe Editor wird für GraphQL-Variables, WebSocket-Nachrichten und Token-Request-Zusatzparameter genutzt, damit es nur einen JSON-Editor gibt.
|
||||||
|
|
||||||
|
## 6. Authentication
|
||||||
|
|
||||||
|
Auth lässt sich auf Collection-, Folder- und Request-Ebene setzen und wird nach unten vererbt (`inherit`). Ein Tab "Vorschau" zeigt, welche Header, Query-Params oder Body-Felder die Auth am Ende erzeugt, mit maskierten Secrets.
|
||||||
|
|
||||||
|
| Typ | Prio | Hinweise |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| None / Inherit | P0 | Vererbung Collection → Folder → Request |
|
||||||
|
| Basic | P0 | Base64 live in der Vorschau |
|
||||||
|
| Bearer | P0 | Prefix konfigurierbar (`Bearer`, `Token`, ...) |
|
||||||
|
| API Key | P0 | Header, Query oder Cookie |
|
||||||
|
| OAuth 2.0 | P0 | Alle Flows, siehe Abschnitt 7 |
|
||||||
|
| OpenID Connect | P0 | Discovery, ID-Token, UserInfo, siehe Abschnitt 7 |
|
||||||
|
| Digest | P1 | MD5 und SHA-256, qop auth/auth-int |
|
||||||
|
| JWT-Bearer (selbst signiert) | P1 | Claims-Builder, HS256/384/512, RS256/384/512, ES256/384, EdDSA; Key aus Datei oder Secret |
|
||||||
|
| AWS Signature v4 | P1 | Region, Service, Session-Token, Signatur über Header oder Query |
|
||||||
|
| mTLS (Client-Zertifikat) | P1 | PEM oder PKCS#12, Passphrase aus Keyring |
|
||||||
|
| OAuth 1.0a | P1 | HMAC-SHA1/256, RSA-SHA1/256, PLAINTEXT |
|
||||||
|
| Hawk | P2 | |
|
||||||
|
| NTLM / Negotiate | P2 | Kerberos nur falls Bedarf |
|
||||||
|
| Custom (Script) | P2 | Auth als Pre-Request-Script, siehe Abschnitt 9 |
|
||||||
|
|
||||||
|
**Regeln**
|
||||||
|
|
||||||
|
- Werte kommen aus Variablen und Secrets, nie hart in der Request-Datei.
|
||||||
|
- Pro Request lässt sich eine geerbte Auth gezielt überschreiben oder abschalten.
|
||||||
|
- Auth-Fehler (401/403) zeigen im Response-Viewer einen Hinweis, welche Auth tatsächlich gesendet wurde und woher sie kam (Request, Folder oder Collection).
|
||||||
|
- Dieselbe Auth-Konfiguration gilt für HTTP, GraphQL und den WebSocket-Handshake.
|
||||||
|
|
||||||
|
**Debugbarkeit gilt für jeden Auth-Typ (P0)**
|
||||||
|
|
||||||
|
Egal ob Basic, Digest, SigV4 oder OAuth: Auth ist nie eine Black Box. Jeder Request hat einen Auth-Debug-Tab (Details in Abschnitt 7, "Auth-Debugger"), der zeigt, was berechnet und gesendet wurde und warum es ggf. abgelehnt wurde.
|
||||||
|
|
||||||
|
## 7. OAuth 2.0 und OIDC (automatisiert und transparent)
|
||||||
|
|
||||||
|
Das Kernversprechen: einmal einloggen, danach holt Knock Tokens selbst, erneuert sie und hängt sie an, und bei jedem Schritt kann man sehen, was passiert. Alles, was bei Bruno "undurchsichtig" war, wird hier sichtbar gemacht.
|
||||||
|
|
||||||
|
**Setup**
|
||||||
|
|
||||||
|
- P0: **Issuer-URL eingeben, Discovery läuft** (`/.well-known/openid-configuration`, Fallback `oauth-authorization-server`): Authorize-, Token-, UserInfo-, JWKS-, Revocation- und End-Session-Endpoint, unterstützte Scopes, Grants und PKCE-Methoden werden automatisch gefüllt. Manuelle Eingabe bleibt möglich.
|
||||||
|
- P0: **Redirect URI steht ganz oben im Config-Panel**, mit Copy-Button und Hinweis: "Genau diese URL beim Provider als erlaubte Redirect URI eintragen." Standard ist `http://127.0.0.1:<port>/callback` mit konfigurierbarem festem Port (Default z. B. 53127). Warnung bei `localhost` vs. `127.0.0.1`, denn viele Provider matchen exakt.
|
||||||
|
- P0: Client ID, Client Secret (aus Secrets), Scopes (Chips mit Vorschlägen aus Discovery), Audience/Resource und beliebige Zusatzparameter für Authorize- und Token-Request (`prompt`, `login_hint`, `acr_values`, ...).
|
||||||
|
- P0: Client-Authentifizierung: `client_secret_basic`, `client_secret_post`, none (Public Client). P1: `private_key_jwt`. P2: mTLS-Client-Auth.
|
||||||
|
|
||||||
|
**Grant Types**
|
||||||
|
|
||||||
|
| Grant | Prio | Verhalten |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Authorization Code + PKCE (S256) | P0 | Standard. Browser öffnet sich, Loopback-Listener fängt den Code ab, `state` und `nonce` werden geprüft |
|
||||||
|
| Client Credentials | P0 | Komplett headless, kein Browser |
|
||||||
|
| Refresh Token | P0 | Automatisch, siehe unten |
|
||||||
|
| Device Code | P1 | Zeigt User-Code und URL groß, pollt im Hintergrund |
|
||||||
|
| Password (ROPC) | P1 | Mit Deprecation-Hinweis |
|
||||||
|
| Implicit | P2 | Nur mit Deprecation-Warnung |
|
||||||
|
| JWT-Bearer / Token Exchange | P2 | |
|
||||||
|
|
||||||
|
**Alternative Redirect-Modi (P1)**
|
||||||
|
|
||||||
|
- Custom Scheme (`knock://callback`), falls der Provider keine Loopback-URLs erlaubt (registriert einen Deep-Link-Handler im `.desktop`-File)
|
||||||
|
- Manuelles Einfügen: Provider leitet auf eine feste HTTPS-Seite, der Nutzer kopiert die URL oder den Code in ein Feld in Knock
|
||||||
|
|
||||||
|
**Automatisierung**
|
||||||
|
|
||||||
|
- P0: Vor jedem Request prüft Knock das Token. Fehlt es oder läuft es in weniger als 30 s ab, wird es per Refresh Token erneuert. Ist das nicht möglich, startet der Login-Flow (bei Client Credentials einfach ein neuer Token-Request).
|
||||||
|
- P0: Bei 401 mit abgelaufenem Token: einmal refreshen und den Request genau einmal wiederholen (abschaltbar).
|
||||||
|
- P0: Token-Ablage pro Kombination aus Issuer, Client ID, Scopes und Environment. Mehrere Environments dürfen eigene Logins haben, ohne sich zu überschreiben.
|
||||||
|
- P0: Token wird als Header (`Authorization: Bearer ...`), Query-Param oder Body-Feld angehängt. Zur Auswahl: Access Token oder ID Token.
|
||||||
|
- P1: Token mit einem Klick teilen: Variable `{{oauth.<name>.access_token}}` für Requests, die ihn manuell brauchen.
|
||||||
|
|
||||||
|
**Transparenz und Debugging (der eigentliche Mehrwert, Details im Auth-Debugger unten)**
|
||||||
|
|
||||||
|
- P0: **Flow-Log**: jeder Schritt als Eintrag (Discovery, gebaute Authorize-URL mit allen Parametern, eingegangener Redirect roh, Token-Request und -Response, Refresh). Tokens sind im Klartext lesbar, Maskierung per Schalter (siehe Auth-Debugger).
|
||||||
|
- P0: **Fehler im Klartext**: Felder `error` und `error_description` des Providers prominent, dazu Hinweise für häufige Fälle (`redirect_uri_mismatch` → zeigt gesendete und vermutlich registrierte URI nebeneinander; `invalid_scope`, `invalid_client`, PKCE erforderlich, `state`-Mismatch).
|
||||||
|
- P0: **Token-Inspector**: JWT dekodiert (Header, Claims, `exp`/`iat` als Countdown und Datum), Scopes, Audience, Aussteller.
|
||||||
|
- P1: Signaturprüfung per JWKS, ID-Token-Validierung (`nonce`, `at_hash`, `aud`, `iss`, `exp`).
|
||||||
|
- P1: Buttons für UserInfo-Abfrage, Token Introspection (RFC 7662), Revoke (RFC 7009) und RP-Initiated Logout (`end_session_endpoint`).
|
||||||
|
|
||||||
|
**Auth-Debugger (P0)**
|
||||||
|
|
||||||
|
Bei Bruno kommt bei einem fehlgeschlagenen Login fast nichts zurück. Knock hat dafür ein eigenes Debug-Panel, das den gesamten Flow Schritt für Schritt zeigt und bei einem Fehler genau markiert, wo und warum er passiert ist.
|
||||||
|
|
||||||
|
**1. Schritt-Timeline**
|
||||||
|
|
||||||
|
- Das Panel öffnet sich automatisch bei jedem Fehler im Auth-Flow und ist jederzeit manuell öffnbar (Tab neben der Response, auch als abdockbares Fenster).
|
||||||
|
- Jeder Schritt hat Status (ok, Fehler, übersprungen), Dauer und Zeitstempel.
|
||||||
|
- Schritte beim Authorization-Code-Flow: Config prüfen → Discovery → Authorize-URL bauen → Browser öffnen → Auf Callback warten (Listener-Status mit Port live) → Callback empfangen → `state` prüfen → Token-Request → Token-Response parsen → ID-Token validieren → Token speichern → Token an Request anhängen → Request senden.
|
||||||
|
- Der erste fehlgeschlagene Schritt ist rot markiert und trägt eine Zeile "Hier ist es gescheitert" mit Ursache und konkretem Hinweis, was zu tun ist.
|
||||||
|
- Steps, die wegen eines gültigen Tokens übersprungen wurden, werden trotzdem angezeigt ("Token noch 12 min gültig, kein Refresh nötig").
|
||||||
|
|
||||||
|
**2. Jeder Schritt aufklappbar, mit Rohdaten**
|
||||||
|
|
||||||
|
- HTTP-Austausch vollständig: URL, Methode, Header, Body des Requests und Status, Header, Body der Response, jeweils roh und formatiert.
|
||||||
|
- Authorize-URL zerlegt in ihre Parameter (`client_id`, `redirect_uri`, `scope`, `state`, `code_challenge`, ...), jeder Wert einzeln kopierbar.
|
||||||
|
- Der eingegangene Callback wird roh angezeigt (komplette URL mit Query), auch wenn der Provider nur einen Fehler zurückschickt.
|
||||||
|
- Button "Als cURL kopieren" für jeden ausgehenden Request (Token-Request, Refresh, UserInfo), um ihn außerhalb von Knock nachzustellen.
|
||||||
|
|
||||||
|
**3. Tokens lesbar**
|
||||||
|
|
||||||
|
- Access-, Refresh- und ID-Token werden als Baum dargestellt: JWT-Header, Payload, Signaturstatus. Claims mit Kurz-Erklärung (`iss`, `aud`, `sub`, `exp`, `iat`, `nbf`, `scope`, `azp`, `nonce`).
|
||||||
|
- Zeiten als Datum und relativ ("läuft in 4 min ab"), dazu Abweichung zwischen lokaler Uhr und `Date`-Header des Servers.
|
||||||
|
- Warnungen direkt am Token: abgelaufen, `nbf` in der Zukunft, `aud` passt nicht zur Ziel-API, erwarteter Scope fehlt.
|
||||||
|
- Nicht-JWT-Tokens (opak) werden als solche gekennzeichnet, mit Button für Introspection.
|
||||||
|
- Tokens sind im Debug-Panel standardmäßig **im Klartext** sichtbar (lokal, nur auf deinem Rechner). Ein globaler Schalter "Secrets maskieren" schaltet auf Maskierung um. Exporte und geteilte Logs sind immer maskiert, außer man deaktiviert das explizit pro Export.
|
||||||
|
|
||||||
|
**4. Diagnosen mit Klartext**
|
||||||
|
|
||||||
|
Regelbasierte Erkennung der häufigsten Fehler, jeweils mit "Warum" und "Was tun":
|
||||||
|
|
||||||
|
| Fehler | Was Knock zeigt |
|
||||||
|
| --- | --- |
|
||||||
|
| `redirect_uri_mismatch` | Gesendete Redirect URI, Hinweis auf exakten Vergleich (Port, `localhost` vs. `127.0.0.1`, Slash am Ende), Copy-Button zum Eintragen beim Provider |
|
||||||
|
| `state`-Mismatch oder fehlender `state` | Erwartet vs. empfangen; Hinweis auf zwei parallele Logins oder wiederverwendeten Tab |
|
||||||
|
| `invalid_grant` | Code bereits benutzt oder abgelaufen, Refresh Token rotiert oder widerrufen, PKCE-Verifier passt nicht |
|
||||||
|
| `invalid_client` / `unauthorized_client` | Falsche Client-Auth-Methode (Basic vs. Post), Secret leer, Grant für diesen Client nicht erlaubt |
|
||||||
|
| `invalid_scope` | Angefragte Scopes gegen die in Discovery gemeldeten gehalten |
|
||||||
|
| PKCE-Fehler | Ob der Provider PKCE verlangt und welche Methode er unterstützt |
|
||||||
|
| Callback-Timeout | Browser nicht gestartet, Port belegt, Firewall, falscher Redirect-Modus |
|
||||||
|
| TLS-/Zertifikatsfehler bei Discovery | Kette und Fehlerursache, Hinweis auf eigene CA |
|
||||||
|
| 401/403 trotz gültigem Token | Welcher Token mit welchem Prefix gesendet wurde, `aud`- und Scope-Prüfung gegen die API |
|
||||||
|
|
||||||
|
**5. Einzelne Schritte wiederholen**
|
||||||
|
|
||||||
|
- Token-Request, Refresh, Discovery, UserInfo und Introspection lassen sich einzeln erneut auslösen, ohne den Browser-Login zu wiederholen.
|
||||||
|
- Parameter vor dem Wiederholen editierbar ("was passiert, wenn ich den Scope ändere oder den Client-Auth-Mode wechsle?"). Hinweis, dass Authorization Codes nur einmal gültig sind.
|
||||||
|
- "Test connection" ohne echten Request: prüft Discovery, Erreichbarkeit von Token-Endpoint und JWKS und bei Client Credentials einen kompletten Token-Abruf.
|
||||||
|
|
||||||
|
**6. Verlauf und Teilen**
|
||||||
|
|
||||||
|
- Die letzten 20 Flows pro Config bleiben im Debug-Verlauf erhalten, auch erfolgreiche, zum Vergleichen mit einem fehlgeschlagenen.
|
||||||
|
- Export eines Flows als JSON oder Markdown (maskiert), damit man ihn im Ticket oder beim Provider-Support posten kann.
|
||||||
|
|
||||||
|
**7. Debug für alle anderen Auth-Typen (P1)**
|
||||||
|
|
||||||
|
- Digest: Challenge vom Server, berechnete Response, verwendeter `nonce` und `qop`.
|
||||||
|
- AWS SigV4: Canonical Request, String to Sign, Signing Key-Ableitung und Signatur Schritt für Schritt.
|
||||||
|
- JWT (selbst signiert): Header, Claims und Signatur im Klartext, plus Prüfung mit dem hinterlegten Schlüssel.
|
||||||
|
- mTLS: Handshake-Verlauf, gesendete Zertifikatskette, Fehlergrund bei Ablehnung.
|
||||||
|
- Basic, Bearer, API Key: der exakt gesendete Header, mit Hinweis, falls ein Variablen-Platzhalter leer aufgelöst wurde.
|
||||||
|
|
||||||
|
**8. CLI**
|
||||||
|
|
||||||
|
- `knock auth debug <config>` gibt dieselbe Schrittfolge im Terminal aus, `--verbose` zeigt Roh-HTTP, `--reveal` zeigt Tokens im Klartext (Default maskiert, weil Terminal-Output oft in CI-Logs landet).
|
||||||
|
|
||||||
|
**Sicherheit**
|
||||||
|
|
||||||
|
- Access-, Refresh- und ID-Tokens liegen im Keyring, nicht in Dateien und nicht im Git.
|
||||||
|
- Der Loopback-Listener bindet nur an `127.0.0.1`, akzeptiert genau einen passenden Callback und schaltet sich danach ab (Timeout 5 Minuten).
|
||||||
|
- Der Browser-Login nutzt den System-Browser (Passkeys, SSO, Passwortmanager funktionieren), kein eingebettetes WebView.
|
||||||
|
|
||||||
|
**Abnahme**
|
||||||
|
|
||||||
|
Flow gegen Keycloak und gegen einen eigenen OIDC-Server (z. B. Sigil) funktioniert inklusive Auto-Refresh, plus ein Provider mit strikter Redirect-URI-Prüfung (GitHub oder Google).
|
||||||
|
|
||||||
|
## 8. Environments, Variablen, Secrets
|
||||||
|
|
||||||
|
Variablen nutzen die Syntax `{{name}}` überall: URL, Header, Body, Auth-Felder, Scripts. Auflösung von eng nach weit, der engste Scope gewinnt.
|
||||||
|
|
||||||
|
| Scope (eng → weit) | Prio | Quelle |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Runtime | P0 | Per Extract oder Script gesetzt, nur während der Session (optional persistent) |
|
||||||
|
| Request | P0 | In der Request-Datei |
|
||||||
|
| Folder | P0 | `folder.yaml` |
|
||||||
|
| Environment | P0 | `environments/<name>.yaml`, per Dropdown oben rechts wechselbar |
|
||||||
|
| Collection | P0 | `knock.yaml` |
|
||||||
|
| Global | P1 | App-weit, nicht im Repo |
|
||||||
|
|
||||||
|
**Features**
|
||||||
|
|
||||||
|
- P0: Hover über eine Variable zeigt aufgelösten Wert und Scope. Undefinierte Variablen werden rot markiert, Senden warnt davor.
|
||||||
|
- P0: Secrets: Variablen mit Flag `secret` landen im Keyring (oder in einer gitignorten `*.secrets.yaml`) und werden in UI, Logs und History maskiert. Zugriff als `{{secret.name}}` oder normal als Variable.
|
||||||
|
- P0: Dynamische Variablen: `{{$uuid}}`, `{{$timestamp}}`, `{{$isoDate}}`, `{{$randomInt}}`, `{{$base64(...)}}`.
|
||||||
|
- P0: Extract-Regeln pro Request: Wert aus Response per JSONPath, Header, Cookie oder Regex in eine Runtime-Variable schreiben (für Chaining).
|
||||||
|
- P1: Verschachtelte Variablen (`{{base}}/{{version}}`), Zyklen werden erkannt und gemeldet.
|
||||||
|
- P1: Environment-Farbe und Warnbanner für Prod ("Du sendest gegen prod") mit optionaler Bestätigung bei DELETE und PUT.
|
||||||
|
|
||||||
|
## 9. Assertions, Scripting, Runner
|
||||||
|
|
||||||
|
Erst deklarativ, Scripts nur als Power-Option. So bleibt der Alltag klickbar und diff-bar.
|
||||||
|
|
||||||
|
**Assertions (P0)**
|
||||||
|
|
||||||
|
- Pro Request als UI-Zeilen: Status, Header, Response-Zeit, JSON-Pfad (`equals`, `contains`, `exists`, `type`, `matches`, `gt`/`lt`), Body-Größe.
|
||||||
|
- Ergebnis als grün/rot im Response-Viewer, mit Soll- und Ist-Wert.
|
||||||
|
|
||||||
|
**Scripting (P1)**
|
||||||
|
|
||||||
|
- Pre-Request- und Post-Response-Script in JavaScript, ausgeführt in QuickJS-Sandbox: kein Dateisystem, kein Netzwerk außer über `knock.send()`, Timeout pro Script.
|
||||||
|
- API: `knock.request` (lesen/ändern), `knock.response`, `knock.vars.get/set`, `knock.env`, `knock.send(...)`, `knock.test(name, fn)`, `knock.assert(...)`.
|
||||||
|
- Importierte Scripts (z. B. aus Postman) werden nie automatisch ausgeführt, erst nach Bestätigung.
|
||||||
|
|
||||||
|
**Runner (P1)**
|
||||||
|
|
||||||
|
- Ordner oder ganze Collection der Reihe nach ausführen, mit gewähltem Environment, Abbruch bei erstem Fehler optional, Verzögerung zwischen Requests.
|
||||||
|
- Ergebnisliste mit Assertions pro Request und Gesamtzeit, Export als JSON und JUnit-XML.
|
||||||
|
- P2: Datengetriebene Läufe mit CSV/JSON (eine Iteration pro Zeile), paralleles Ausführen.
|
||||||
|
|
||||||
|
## 10. Import, Export, CLI, History
|
||||||
|
|
||||||
|
**Import (P0 zuerst die Umzugshelfer)**
|
||||||
|
|
||||||
|
| Quelle | Prio |
|
||||||
|
| --- | --- |
|
||||||
|
| cURL (Einfügen in die URL-Leiste oder Strg+V in die Sidebar) | P0 |
|
||||||
|
| Postman Collection v2.1 und Environments | P0 |
|
||||||
|
| Bruno Collections (`.bru`) | P0 |
|
||||||
|
| OpenAPI 3.x / Swagger 2 (Requests plus Schemas für den JSON-Editor) | P1 |
|
||||||
|
| Insomnia Export | P1 |
|
||||||
|
| HAR | P2 |
|
||||||
|
|
||||||
|
**Export (P1)**
|
||||||
|
|
||||||
|
- Code-Snippets pro Request: cURL, `fetch`, Python (`requests`, `httpx`), HTTPie, Go, PowerShell; Variablen aufgelöst oder als Platzhalter.
|
||||||
|
- Collection als Postman v2.1 und als OpenAPI (best effort).
|
||||||
|
|
||||||
|
**CLI (`knock`)**
|
||||||
|
|
||||||
|
- P1: `knock send <file> --env prod` schickt einen Request, `knock run <folder> --env prod` führt einen Ordner aus; Exit-Code ungleich 0 bei fehlgeschlagener Assertion.
|
||||||
|
- P1: Reporter: pretty, JSON, JUnit. Secrets aus Keyring oder ENV-Variablen (`KNOCK_SECRET_<NAME>`), damit es in CI läuft.
|
||||||
|
- P1: OAuth: nutzt gespeicherte Tokens inklusive Refresh. `knock auth login <config>` startet den Browser-Flow auch ohne GUI.
|
||||||
|
|
||||||
|
**History**
|
||||||
|
|
||||||
|
- P0: Lokale History in SQLite (Request, Status, Zeit), durchsuchbar, erneut sendbar. Secrets maskiert.
|
||||||
|
- P1: Responses in der History speicherbar mit Größenlimit (Default 1 MB pro Eintrag, 500 MB gesamt), Aufbewahrung konfigurierbar.
|
||||||
|
- P1: "Als Request speichern" aus einem History-Eintrag.
|
||||||
|
|
||||||
|
## 11. UI/UX, Nicht-funktionales, Sicherheit
|
||||||
|
|
||||||
|
**Layout und Bedienung**
|
||||||
|
|
||||||
|
- P0: Sidebar mit Collection-Baum (Drag-and-drop, Umbenennen, Duplizieren, Suche mit Fuzzy-Match), Tabs mit Vorschau-Tab (Einfachklick öffnet ersetzbar, Doppelklick pinnt), Request- und Response-Pane nebeneinander oder übereinander umschaltbar.
|
||||||
|
- P0: Kommandopalette (Strg+K): Requests, Environments, Aktionen.
|
||||||
|
- P0: Shortcuts: Strg+Enter senden, Strg+S speichern, Strg+T neuer Tab, Strg+W Tab schließen, Strg+L URL fokussieren, Strg+E Environment wechseln, Strg+Shift+J JSON Form/Code.
|
||||||
|
- P0: Dark, Light, System, auf Basis der Cock-Design-Tokens. Logo, Farben und weitere visuelle Vorgaben stehen in DESIGN.md im Repo und sind für die UI verbindlich.
|
||||||
|
- P1: Tastaturbedienung für alles Wichtige, sichtbare Fokus-Zustände, skalierbare Schrift.
|
||||||
|
|
||||||
|
**Linux-Integration (P0)**
|
||||||
|
|
||||||
|
- `.desktop`-Datei mit Icon und MIME-Handler, taucht im KDE-Startmenü auf.
|
||||||
|
- Native Datei-Dialoge über XDG-Portal, Wayland und X11 getestet, HiDPI.
|
||||||
|
- Pakete: `PKGBUILD` (AUR `knock-bin`), AppImage, deb, rpm. P1: Flatpak. Windows (MSI/NSIS) und macOS (DMG) als Best Effort.
|
||||||
|
|
||||||
|
**Linux-Zielplattformen**
|
||||||
|
|
||||||
|
| Distro | Prio | Umsetzung |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Arch Linux (inkl. CachyOS) | P0 | Primärziel. `PKGBUILD` für AUR (`knock-bin` und `knock`), Abhängigkeit `webkit2gtk-4.1`. Getestet auf CachyOS mit KDE Plasma (Wayland und X11) |
|
||||||
|
| Ubuntu (22.04 LTS und neuer) | P1 | Optionales Ziel. `.deb`, gebaut in einem Ubuntu-22.04-Container (ältestes Ziel, damit das Paket auch auf neueren Versionen läuft), damit glibc und `libwebkit2gtk-4.1` zur Zielversion passen. CI-Smoke-Test: installieren, starten, einen Request senden |
|
||||||
|
| Sonstige (Fedora, Debian, ...) | P2 | `.rpm`, AppImage und später Flatpak als distro-unabhängiger Weg |
|
||||||
|
|
||||||
|
Beide Ziele bekommen dieselben Features, nur die Pakete unterscheiden sich. Ubuntu-spezifische Probleme (z. B. ältere WebKitGTK-Versionen) blockieren kein Arch-Release.
|
||||||
|
|
||||||
|
**Nicht-funktionale Anforderungen**
|
||||||
|
|
||||||
|
| Thema | Ziel |
|
||||||
|
| --- | --- |
|
||||||
|
| Kaltstart bis bedienbar | unter 1,5 s auf aktueller Hardware |
|
||||||
|
| RAM im Leerlauf | unter 250 MB |
|
||||||
|
| Große Collections | 5.000 Requests ohne spürbares Laggen in der Sidebar |
|
||||||
|
| Große Responses | 50 MB ohne UI-Freeze |
|
||||||
|
| Offline | Alles außer den Requests selbst funktioniert ohne Netz |
|
||||||
|
| Telemetrie | Keine. Kein Account, keine Update-Pings ohne Opt-in |
|
||||||
|
| Lizenz | MIT |
|
||||||
|
| UI-Sprache | Nur Englisch: App-UI, Fehlermeldungen, Auth-Diagnosen, CLI-Ausgaben, Code, Kommentare, Docs. Deutsche UI-Texte in diesem Spec sind nur Beschreibung und werden auf Englisch umgesetzt. Strings liegen zentral, damit spätere Übersetzungen möglich wären (nicht geplant). |
|
||||||
|
|
||||||
|
**Sicherheit**
|
||||||
|
|
||||||
|
- TLS-Verifikation standardmäßig an; Abschalten ist pro Request sichtbar markiert.
|
||||||
|
- Secrets nur im Keyring oder gitignorter Datei, in Logs und History maskiert; Export ohne Secrets als Default.
|
||||||
|
- Scripts laufen sandboxed, Importe führen nie automatisch Code aus.
|
||||||
|
- WebView lädt keine Remote-Inhalte; HTML-Preview läuft in einem iframe mit `sandbox`.
|
||||||
|
- Updates: nur über Paketmanager oder manuelle Downloads in v1, kein Auto-Updater.
|
||||||
|
|
||||||
|
## 12. Milestones, Definition of Done, offene Fragen
|
||||||
|
|
||||||
|
v1 ist fertig, wenn alle P0-Punkte stehen und du Knock eine Woche lang statt Bruno benutzt hast, ohne zurückzuwechseln. P1-Punkte, die nicht fertig werden, rutschen nach v1.1.
|
||||||
|
|
||||||
|
| Milestone | Inhalt | Fertig, wenn |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| M0 Skeleton | Tauri-App, Core-Crate, Collection-Parser, Sidebar, Tabs | Collection aus Dateien lädt, Request wird gespeichert |
|
||||||
|
| M1 REST-Kern | Request-Editor, Response-Viewer, Settings, Cookies, History | Alltags-Requests laufen, große Bodies freezen nicht |
|
||||||
|
| M2 Variablen und JSON-Editor | Environments, Secrets, Extract, Form/Tree-Editor | JSON-Body komplett ohne Tippen von Klammern baubar |
|
||||||
|
| M3 Auth-Basis | None, Basic, Bearer, API Key, Digest, JWT, AWS SigV4, mTLS, OAuth 1.0a | Jeder Typ gegen einen Testserver verifiziert |
|
||||||
|
| M4 OAuth/OIDC | Alle P0/P1-Flows, Auto-Refresh, Flow-Log, Token-Inspector | Abnahme aus Abschnitt 7 bestanden, Auth-Debugger zeigt jeden Schritt und jeden Fehler |
|
||||||
|
| M5 GraphQL und WebSocket | Query-Editor, Introspection, WS-Composer und -Log | Gegen echten GraphQL-Server und WS-Echo getestet |
|
||||||
|
| M6 Import, CLI, Runner | Postman/Bruno/cURL-Import, `knock run`, Assertions, Scripts | Eigene Bruno-Collection lässt sich importieren und läuft |
|
||||||
|
| M7 Packaging und Polish | PKGBUILD, AppImage, deb, rpm, Shortcuts, Dark/Light, Doku | Installation über Pacman/AUR und Startmenü-Eintrag funktionieren; .deb installiert und startet auf Ubuntu 22.04 und 24.04 |
|
||||||
|
|
||||||
|
**Risiken**
|
||||||
|
|
||||||
|
- WebKitGTK unter Wayland ist die größte technische Unbekannte. Bei Yaak (ebenfalls Tauri) tauchen auf Arch Fehlermeldungen zu WebKit und explicit sync auf, siehe die Kommentare beim [AUR-Paket yaak-bin](https://aur.archlinux.org/packages/yaak-bin). Plan: in M0 auf deinem Setup (CachyOS, KDE, Wayland) testen. Wenn es hakt, ist Electron die Ausweichlösung, der Rust-Core wird dann zu einem Node-/Sidecar-Prozess.
|
||||||
|
- OAuth-Provider verhalten sich uneinheitlich (Redirect-Matching, PKCE-Pflicht, Scope-Namen). Deshalb das Flow-Log und die Abnahme gegen mehrere Provider.
|
||||||
|
- Scope: das hier ist ein großer v1-Umfang. Die P1-Markierungen sind das Sicherheitsventil.
|
||||||
|
|
||||||
|
**Offene Fragen**
|
||||||
|
|
||||||
|
- [ ] Windows und macOS: "auch Desktop-App" so gemeint, dass beide Plattformen Best Effort mitlaufen sollen? (Annahme in diesem Dokument: ja, nicht blockierend)
|
||||||
|
- [ ] Tauri (Standard) oder Electron, falls WebKitGTK in M0 Probleme macht?
|
||||||
|
- [ ] Scripting schon in v1 (aktuell P1) oder erst v1.1?
|
||||||
|
- [ ] JSON-Schema/OpenAPI-gestützte Formulare in v1 (aktuell P1)?
|
||||||
|
- [ ] SSE als Request-Typ schon in v1 (aktuell P2)?
|
||||||
|
- [ ] Lizenz: MIT passt, oder lieber AGPL, damit niemand einen bezahlten Fork daraus macht?
|
||||||
|
- [ ] Format: YAML wie hier, oder lieber ein eigenes Dateiformat wie `.bru`?
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
[package]
|
||||||
|
name = "knock-core"
|
||||||
|
description = "Request engine, auth, variables and collection format for knock"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
serde_yaml_ng.workspace = true
|
||||||
|
indexmap.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
reqwest.workspace = true
|
||||||
|
url.workspace = true
|
||||||
|
base64.workspace = true
|
||||||
|
uuid.workspace = true
|
||||||
|
chrono.workspace = true
|
||||||
|
rand.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
regex = "1"
|
||||||
|
serde_json_path = "0.7"
|
||||||
|
percent-encoding = "2"
|
||||||
|
cookie_store = { version = "0.22", features = ["serde_json"] }
|
||||||
|
bytes = "1"
|
||||||
|
futures-util = "0.3"
|
||||||
|
http = "1"
|
||||||
|
keyring = { version = "3.6", features = ["sync-secret-service", "crypto-rust", "apple-native", "windows-native"] }
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
//! Auth is never a black box: every auth type returns an [`AuthDebug`] that
|
||||||
|
//! says what was computed, what was attached and where it came from.
|
||||||
|
|
||||||
|
mod simple;
|
||||||
|
|
||||||
|
use crate::model::{Auth, AuthConfig};
|
||||||
|
use crate::prepare::{EffectiveAuth, Prepared};
|
||||||
|
use crate::vars::Resolver;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum StepStatus {
|
||||||
|
Ok,
|
||||||
|
Error,
|
||||||
|
Skipped,
|
||||||
|
Pending,
|
||||||
|
Warning,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One HTTP exchange made as part of an auth flow, in full.
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
|
pub struct Exchange {
|
||||||
|
pub method: String,
|
||||||
|
pub url: String,
|
||||||
|
pub request_headers: Vec<(String, String)>,
|
||||||
|
pub request_body: String,
|
||||||
|
pub status: Option<u16>,
|
||||||
|
pub response_headers: Vec<(String, String)>,
|
||||||
|
pub response_body: String,
|
||||||
|
pub curl: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Step {
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
pub status: StepStatus,
|
||||||
|
pub at: chrono::DateTime<chrono::Utc>,
|
||||||
|
pub duration_ms: f64,
|
||||||
|
/// One line shown next to the title.
|
||||||
|
pub summary: String,
|
||||||
|
/// What went wrong and what to do about it.
|
||||||
|
pub hint: Option<String>,
|
||||||
|
pub exchange: Option<Exchange>,
|
||||||
|
/// Free-form structured data (parsed URL params, decoded token, …).
|
||||||
|
pub data: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Step {
|
||||||
|
pub fn new(id: &str, title: &str, status: StepStatus, summary: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
id: id.into(),
|
||||||
|
title: title.into(),
|
||||||
|
status,
|
||||||
|
at: chrono::Utc::now(),
|
||||||
|
duration_ms: 0.0,
|
||||||
|
summary: summary.into(),
|
||||||
|
hint: None,
|
||||||
|
exchange: None,
|
||||||
|
data: serde_json::Value::Null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn hint(mut self, h: impl Into<String>) -> Self {
|
||||||
|
self.hint = Some(h.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
pub fn data(mut self, d: serde_json::Value) -> Self {
|
||||||
|
self.data = d;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
pub fn took(mut self, since: std::time::Instant) -> Self {
|
||||||
|
self.duration_ms = since.elapsed().as_secs_f64() * 1000.0;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Sent {
|
||||||
|
/// header, query, cookie or body
|
||||||
|
pub location: String,
|
||||||
|
pub name: String,
|
||||||
|
pub value: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
|
pub struct AuthDebug {
|
||||||
|
pub kind: String,
|
||||||
|
pub origin: Option<String>,
|
||||||
|
pub source: Option<String>,
|
||||||
|
pub steps: Vec<Step>,
|
||||||
|
pub sent: Vec<Sent>,
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
/// Id of the OAuth flow log entry, if a flow ran.
|
||||||
|
pub flow_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthDebug {
|
||||||
|
pub fn failed(&self) -> bool {
|
||||||
|
self.steps.iter().any(|s| s.status == StepStatus::Error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hooks for auth types that need more than the request itself (OAuth token
|
||||||
|
/// store and browser, signing keys from the keyring, …). Implemented by the
|
||||||
|
/// app and the CLI.
|
||||||
|
#[allow(async_fn_in_trait)]
|
||||||
|
pub trait AuthHost: Send + Sync {
|
||||||
|
/// Returns an access token for an OAuth2 config, refreshing or logging in
|
||||||
|
/// as needed, plus the steps it took.
|
||||||
|
fn oauth2_token(
|
||||||
|
&self,
|
||||||
|
cfg: &AuthConfig,
|
||||||
|
resolver: &Resolver,
|
||||||
|
force_refresh: bool,
|
||||||
|
) -> futures_util::future::BoxFuture<'_, OauthResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct OauthResult {
|
||||||
|
pub token: Option<String>,
|
||||||
|
pub steps: Vec<Step>,
|
||||||
|
pub flow_id: Option<String>,
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attaches the effective auth to a prepared request. Errors are reported as
|
||||||
|
/// failed steps inside the returned debug info, not as `Err`, so the UI can
|
||||||
|
/// show where it broke.
|
||||||
|
pub async fn apply(
|
||||||
|
eff: &EffectiveAuth,
|
||||||
|
p: &mut Prepared,
|
||||||
|
resolver: &Resolver,
|
||||||
|
host: Option<&dyn AuthHost>,
|
||||||
|
force_refresh: bool,
|
||||||
|
) -> AuthDebug {
|
||||||
|
let mut dbg = AuthDebug {
|
||||||
|
origin: Some(format!("{:?}", eff.origin).to_lowercase()),
|
||||||
|
source: Some(eff.source.clone()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let cfg = match &eff.auth {
|
||||||
|
Auth::Inherit | Auth::None => {
|
||||||
|
dbg.kind = "none".into();
|
||||||
|
return dbg;
|
||||||
|
}
|
||||||
|
Auth::Config(c) => c,
|
||||||
|
};
|
||||||
|
dbg.kind = cfg.kind.clone();
|
||||||
|
let res = |key: &str| -> (String, Vec<String>) {
|
||||||
|
let r = resolver.resolve(cfg.str(key).unwrap_or_default());
|
||||||
|
(r.value, r.missing)
|
||||||
|
};
|
||||||
|
match cfg.kind.as_str() {
|
||||||
|
"basic" => simple::basic(cfg, p, &res, &mut dbg),
|
||||||
|
"bearer" => simple::bearer(cfg, p, &res, &mut dbg),
|
||||||
|
"apikey" => simple::apikey(cfg, p, &res, &mut dbg),
|
||||||
|
"oauth2" | "oidc" => {
|
||||||
|
let Some(host) = host else {
|
||||||
|
dbg.steps.push(Step::new("token", "Get token", StepStatus::Error, "OAuth is not available here"));
|
||||||
|
return dbg;
|
||||||
|
};
|
||||||
|
let out = host.oauth2_token(cfg, resolver, force_refresh).await;
|
||||||
|
dbg.steps.extend(out.steps);
|
||||||
|
dbg.warnings.extend(out.warnings);
|
||||||
|
dbg.flow_id = out.flow_id;
|
||||||
|
if let Some(token) = out.token {
|
||||||
|
simple::attach_token(cfg, p, &token, &mut dbg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => {
|
||||||
|
dbg.steps.push(Step::new(
|
||||||
|
"apply",
|
||||||
|
"Apply auth",
|
||||||
|
StepStatus::Error,
|
||||||
|
format!("auth type '{other}' is not supported"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for s in &dbg.sent {
|
||||||
|
resolver.note_secret(&s.value);
|
||||||
|
}
|
||||||
|
dbg
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
use super::{AuthDebug, Sent, Step, StepStatus};
|
||||||
|
use crate::model::AuthConfig;
|
||||||
|
use crate::prepare::Prepared;
|
||||||
|
use base64::Engine;
|
||||||
|
|
||||||
|
type Res<'a> = dyn Fn(&str) -> (String, Vec<String>) + 'a;
|
||||||
|
|
||||||
|
fn check(dbg: &mut AuthDebug, field: &str, value: &str, missing: &[String]) {
|
||||||
|
if !missing.is_empty() {
|
||||||
|
dbg.warnings.push(format!(
|
||||||
|
"{field}: variable {} is not defined, sent as literal text",
|
||||||
|
missing.iter().map(|m| format!("{{{{{m}}}}}")).collect::<Vec<_>>().join(", ")
|
||||||
|
));
|
||||||
|
} else if value.is_empty() {
|
||||||
|
dbg.warnings.push(format!("{field} resolved to an empty value"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn basic(cfg: &AuthConfig, p: &mut Prepared, res: &Res<'_>, dbg: &mut AuthDebug) {
|
||||||
|
let (user, m1) = res("username");
|
||||||
|
let (pass, m2) = res("password");
|
||||||
|
check(dbg, "username", &user, &m1);
|
||||||
|
check(dbg, "password", &pass, &m2);
|
||||||
|
let _ = cfg;
|
||||||
|
let encoded = base64::engine::general_purpose::STANDARD.encode(format!("{user}:{pass}"));
|
||||||
|
let value = format!("Basic {encoded}");
|
||||||
|
p.set_header("Authorization", &value);
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("encode", "Encode credentials", StepStatus::Ok, format!("base64(\"{user}:•••\")"))
|
||||||
|
.data(serde_json::json!({ "username": user, "encoded": encoded })),
|
||||||
|
);
|
||||||
|
dbg.sent.push(Sent { location: "header".into(), name: "Authorization".into(), value });
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn bearer(cfg: &AuthConfig, p: &mut Prepared, res: &Res<'_>, dbg: &mut AuthDebug) {
|
||||||
|
let (token, m) = res("token");
|
||||||
|
check(dbg, "token", &token, &m);
|
||||||
|
let prefix = cfg.str("prefix").unwrap_or("Bearer");
|
||||||
|
let value = if prefix.is_empty() { token.clone() } else { format!("{prefix} {token}") };
|
||||||
|
p.set_header("Authorization", &value);
|
||||||
|
dbg.steps.push(Step::new("attach", "Attach token", StepStatus::Ok, format!("Authorization: {prefix} …")));
|
||||||
|
dbg.sent.push(Sent { location: "header".into(), name: "Authorization".into(), value });
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn apikey(cfg: &AuthConfig, p: &mut Prepared, res: &Res<'_>, dbg: &mut AuthDebug) {
|
||||||
|
let (key, m1) = res("key");
|
||||||
|
let (value, m2) = res("value");
|
||||||
|
check(dbg, "key", &key, &m1);
|
||||||
|
check(dbg, "value", &value, &m2);
|
||||||
|
let location = cfg.str("in").unwrap_or("header").to_string();
|
||||||
|
match location.as_str() {
|
||||||
|
"query" => {
|
||||||
|
if let Err(e) = p.add_query(&key, &value) {
|
||||||
|
dbg.steps.push(Step::new("attach", "Attach key", StepStatus::Error, e.to_string()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"cookie" => {
|
||||||
|
let existing = p.header("Cookie").map(str::to_string);
|
||||||
|
let c = format!("{key}={value}");
|
||||||
|
p.set_header("Cookie", existing.map(|e| format!("{e}; {c}")).unwrap_or(c));
|
||||||
|
}
|
||||||
|
_ => p.set_header(&key, &value),
|
||||||
|
}
|
||||||
|
dbg.steps.push(Step::new("attach", "Attach key", StepStatus::Ok, format!("{key} as {location}")));
|
||||||
|
dbg.sent.push(Sent { location, name: key, value });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attaches an OAuth token the way the config asks for (header, query or body
|
||||||
|
/// field; access or id token is chosen by the host).
|
||||||
|
pub(crate) fn attach_token(cfg: &AuthConfig, p: &mut Prepared, token: &str, dbg: &mut AuthDebug) {
|
||||||
|
let place = cfg.str("token_placement").unwrap_or("header");
|
||||||
|
let name = cfg.str("token_name").filter(|s| !s.is_empty());
|
||||||
|
match place {
|
||||||
|
"query" => {
|
||||||
|
let n = name.unwrap_or("access_token");
|
||||||
|
if let Err(e) = p.add_query(n, token) {
|
||||||
|
dbg.steps.push(Step::new("attach", "Attach token", StepStatus::Error, e.to_string()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dbg.sent.push(Sent { location: "query".into(), name: n.into(), value: token.into() });
|
||||||
|
}
|
||||||
|
"body" => {
|
||||||
|
let n = name.unwrap_or("access_token");
|
||||||
|
let mut body = String::from_utf8_lossy(p.body_bytes()).into_owned();
|
||||||
|
if !body.is_empty() {
|
||||||
|
body.push('&');
|
||||||
|
}
|
||||||
|
body.push_str(&url::form_urlencoded::Serializer::new(String::new()).append_pair(n, token).finish());
|
||||||
|
p.body = crate::prepare::PreparedBody::Bytes { preview: body.clone(), data: body.into_bytes() };
|
||||||
|
dbg.sent.push(Sent { location: "body".into(), name: n.into(), value: token.into() });
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let prefix = cfg.str("token_prefix").unwrap_or("Bearer");
|
||||||
|
let header = name.unwrap_or("Authorization");
|
||||||
|
let value = if prefix.is_empty() { token.to_string() } else { format!("{prefix} {token}") };
|
||||||
|
p.set_header(header, &value);
|
||||||
|
dbg.sent.push(Sent { location: "header".into(), name: header.into(), value });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dbg.steps.push(Step::new("attach", "Attach token to request", StepStatus::Ok, format!("as {place}")));
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
//! Declarative assertions and extract rules.
|
||||||
|
|
||||||
|
use crate::http::Response;
|
||||||
|
use crate::model::*;
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct AssertResult {
|
||||||
|
pub index: usize,
|
||||||
|
pub label: String,
|
||||||
|
pub passed: bool,
|
||||||
|
pub expected: String,
|
||||||
|
pub actual: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Extracted {
|
||||||
|
pub var: String,
|
||||||
|
pub value: Option<String>,
|
||||||
|
pub persist: bool,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn json_path(doc: &Value, path: &str) -> Result<Vec<Value>, String> {
|
||||||
|
let path = path.trim();
|
||||||
|
let path = if path.starts_with('$') { path.to_string() } else { format!("$.{path}") };
|
||||||
|
let p = serde_json_path::JsonPath::parse(&path).map_err(|e| format!("invalid JSONPath: {e}"))?;
|
||||||
|
Ok(p.query(doc).all().into_iter().cloned().collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn target_value(rule: &AssertRule, resp: &Response) -> (Option<Value>, String) {
|
||||||
|
let path = rule.path.clone().unwrap_or_default();
|
||||||
|
match rule.on {
|
||||||
|
AssertTarget::Status => (Some(Value::from(resp.status)), "status".into()),
|
||||||
|
AssertTarget::Time => (
|
||||||
|
Some(Value::from((resp.timings.total_ms).round() as u64)),
|
||||||
|
"response time (ms)".into(),
|
||||||
|
),
|
||||||
|
AssertTarget::Size => (Some(Value::from(resp.size)), "body size (bytes)".into()),
|
||||||
|
AssertTarget::Body => (Some(Value::String(resp.text())), "body".into()),
|
||||||
|
AssertTarget::Header => (
|
||||||
|
resp.header(&path).map(|v| Value::String(v.to_string())),
|
||||||
|
format!("header {path}"),
|
||||||
|
),
|
||||||
|
AssertTarget::Json => {
|
||||||
|
let label = format!("json {path}");
|
||||||
|
let Some(doc) = resp.json() else { return (None, label) };
|
||||||
|
match json_path(&doc, &path) {
|
||||||
|
Ok(mut v) if v.len() == 1 => (v.pop(), label),
|
||||||
|
Ok(v) if v.is_empty() => (None, label),
|
||||||
|
Ok(v) => (Some(Value::Array(v)), label),
|
||||||
|
Err(_) => (None, label),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show(v: &Option<Value>) -> String {
|
||||||
|
match v {
|
||||||
|
None => "(missing)".into(),
|
||||||
|
Some(Value::String(s)) => {
|
||||||
|
if s.chars().count() > 200 {
|
||||||
|
format!("\"{}…\"", s.chars().take(200).collect::<String>())
|
||||||
|
} else {
|
||||||
|
format!("\"{s}\"")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(v) => v.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loose equality: `201` equals `"201"`, so YAML authors need not care about quoting.
|
||||||
|
fn loose_eq(a: &Value, b: &Value) -> bool {
|
||||||
|
if a == b {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
match (a, b) {
|
||||||
|
(Value::String(s), other) | (other, Value::String(s)) if !other.is_string() => {
|
||||||
|
let o = match other {
|
||||||
|
Value::Null => "null".to_string(),
|
||||||
|
v => v.to_string(),
|
||||||
|
};
|
||||||
|
*s == o
|
||||||
|
}
|
||||||
|
(Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn type_name(v: &Value) -> &'static str {
|
||||||
|
match v {
|
||||||
|
Value::Null => "null",
|
||||||
|
Value::Bool(_) => "boolean",
|
||||||
|
Value::Number(_) => "number",
|
||||||
|
Value::String(_) => "string",
|
||||||
|
Value::Array(_) => "array",
|
||||||
|
Value::Object(_) => "object",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn as_number(v: &Value) -> Option<f64> {
|
||||||
|
match v {
|
||||||
|
Value::Number(n) => n.as_f64(),
|
||||||
|
Value::String(s) => s.trim().parse().ok(),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run_asserts(rules: &[AssertRule], resp: &Response) -> Vec<AssertResult> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (index, rule) in rules.iter().enumerate().filter(|(_, r)| r.enabled) {
|
||||||
|
let (actual, label) = target_value(rule, resp);
|
||||||
|
let mut push = |op: &str, expected: String, passed: bool| {
|
||||||
|
out.push(AssertResult {
|
||||||
|
index,
|
||||||
|
label: format!("{label} {op}"),
|
||||||
|
passed,
|
||||||
|
expected,
|
||||||
|
actual: show(&actual),
|
||||||
|
})
|
||||||
|
};
|
||||||
|
if let Some(e) = &rule.equals {
|
||||||
|
push("equals", e.to_string(), actual.as_ref().is_some_and(|a| loose_eq(a, e)));
|
||||||
|
}
|
||||||
|
if let Some(e) = &rule.not_equals {
|
||||||
|
push("not equals", e.to_string(), !actual.as_ref().is_some_and(|a| loose_eq(a, e)));
|
||||||
|
}
|
||||||
|
if let Some(e) = &rule.contains {
|
||||||
|
let ok = match (&actual, e) {
|
||||||
|
(Some(Value::String(a)), Value::String(s)) => a.contains(s.as_str()),
|
||||||
|
(Some(Value::String(a)), other) => a.contains(&other.to_string()),
|
||||||
|
(Some(Value::Array(a)), e) => a.iter().any(|x| loose_eq(x, e)),
|
||||||
|
(Some(Value::Object(o)), Value::String(k)) => o.contains_key(k),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
push("contains", e.to_string(), ok);
|
||||||
|
}
|
||||||
|
if let Some(e) = rule.exists {
|
||||||
|
push(if e { "exists" } else { "does not exist" }, e.to_string(), actual.is_some() == e);
|
||||||
|
}
|
||||||
|
if let Some(t) = &rule.type_is {
|
||||||
|
let ok = actual.as_ref().is_some_and(|a| {
|
||||||
|
type_name(a) == t || (t == "integer" && a.as_i64().is_some())
|
||||||
|
});
|
||||||
|
push("type", t.clone(), ok);
|
||||||
|
}
|
||||||
|
if let Some(re) = &rule.matches {
|
||||||
|
let ok = match regex::Regex::new(re) {
|
||||||
|
Ok(r) => actual.as_ref().is_some_and(|a| match a {
|
||||||
|
Value::String(s) => r.is_match(s),
|
||||||
|
v => r.is_match(&v.to_string()),
|
||||||
|
}),
|
||||||
|
Err(_) => false,
|
||||||
|
};
|
||||||
|
push("matches", format!("/{re}/"), ok);
|
||||||
|
}
|
||||||
|
if let Some(n) = rule.gt {
|
||||||
|
push(">", n.to_string(), actual.as_ref().and_then(as_number).is_some_and(|a| a > n));
|
||||||
|
}
|
||||||
|
if let Some(n) = rule.lt {
|
||||||
|
push("<", n.to_string(), actual.as_ref().and_then(as_number).is_some_and(|a| a < n));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run_extracts(rules: &[ExtractRule], resp: &Response) -> Vec<Extracted> {
|
||||||
|
rules
|
||||||
|
.iter()
|
||||||
|
.filter(|r| r.enabled && !r.var.is_empty())
|
||||||
|
.map(|r| {
|
||||||
|
let (value, error) = match extract_one(r, resp) {
|
||||||
|
Ok(v) => (v, None),
|
||||||
|
Err(e) => (None, Some(e)),
|
||||||
|
};
|
||||||
|
Extracted { var: r.var.clone(), value, persist: r.persist, error }
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_one(r: &ExtractRule, resp: &Response) -> Result<Option<String>, String> {
|
||||||
|
Ok(match r.from {
|
||||||
|
ExtractSource::Status => Some(resp.status.to_string()),
|
||||||
|
ExtractSource::Header => resp.header(&r.path).map(str::to_string),
|
||||||
|
ExtractSource::Cookie => resp.cookies.iter().find(|c| c.name == r.path).map(|c| c.value.clone()),
|
||||||
|
ExtractSource::Regex => {
|
||||||
|
let re = regex::Regex::new(&r.path).map_err(|e| format!("invalid regex: {e}"))?;
|
||||||
|
let text = resp.text();
|
||||||
|
re.captures(&text)
|
||||||
|
.map(|c| c.get(1).or_else(|| c.get(0)).unwrap().as_str().to_string())
|
||||||
|
}
|
||||||
|
ExtractSource::Json => {
|
||||||
|
let doc = resp.json().ok_or("response body is not JSON")?;
|
||||||
|
let mut v = json_path(&doc, &r.path)?;
|
||||||
|
match v.len() {
|
||||||
|
0 => None,
|
||||||
|
1 => Some(scalar_to_string(&v.pop().unwrap())),
|
||||||
|
_ => Some(Value::Array(v).to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::http::Timings;
|
||||||
|
|
||||||
|
fn resp(body: &str) -> Response {
|
||||||
|
Response {
|
||||||
|
status: 201,
|
||||||
|
status_text: "Created".into(),
|
||||||
|
http_version: "1.1".into(),
|
||||||
|
url: "http://x".into(),
|
||||||
|
headers: vec![("Content-Type".into(), "application/json".into())],
|
||||||
|
cookies: vec![],
|
||||||
|
size: body.len() as u64,
|
||||||
|
header_size: 0,
|
||||||
|
content_type: Some("application/json".into()),
|
||||||
|
timings: Timings { total_ms: 12.0, ..Default::default() },
|
||||||
|
redirects: vec![],
|
||||||
|
remote_addr: None,
|
||||||
|
body_file: None,
|
||||||
|
body: body.as_bytes().to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn asserts() {
|
||||||
|
let r = resp(r#"{"id": 7, "tags": ["a","b"], "name": "Ann"}"#);
|
||||||
|
let rules: Vec<AssertRule> = serde_yaml_ng::from_str(
|
||||||
|
r#"
|
||||||
|
- { on: status, equals: 201 }
|
||||||
|
- { on: json, path: $.id, equals: "7", type: number }
|
||||||
|
- { on: json, path: tags, contains: b }
|
||||||
|
- { on: json, path: $.missing, exists: false }
|
||||||
|
- { on: header, path: content-type, matches: "json$" }
|
||||||
|
- { on: time, lt: 1000 }
|
||||||
|
- { on: status, equals: 200 }
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let res = run_asserts(&rules, &r);
|
||||||
|
let failed: Vec<_> = res.iter().filter(|r| !r.passed).collect();
|
||||||
|
assert_eq!(failed.len(), 1, "{res:#?}");
|
||||||
|
assert_eq!(failed[0].index, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn extracts() {
|
||||||
|
let r = resp(r#"{"data": {"id": "abc"}}"#);
|
||||||
|
let rules = vec![
|
||||||
|
ExtractRule { var: "id".into(), from: ExtractSource::Json, path: "$.data.id".into(), enabled: true, persist: false },
|
||||||
|
ExtractRule { var: "ct".into(), from: ExtractSource::Header, path: "content-type".into(), enabled: true, persist: false },
|
||||||
|
ExtractRule { var: "re".into(), from: ExtractSource::Regex, path: r#""id": "(\w+)""#.into(), enabled: true, persist: false },
|
||||||
|
];
|
||||||
|
let out = run_extracts(&rules, &r);
|
||||||
|
assert_eq!(out[0].value.as_deref(), Some("abc"));
|
||||||
|
assert_eq!(out[1].value.as_deref(), Some("application/json"));
|
||||||
|
assert_eq!(out[2].value.as_deref(), Some("abc"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,766 @@
|
|||||||
|
//! A collection is a directory of YAML files. Ids are paths relative to the
|
||||||
|
//! collection root, always with forward slashes.
|
||||||
|
|
||||||
|
use crate::model::*;
|
||||||
|
use anyhow::{anyhow, bail, Context, Result};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Component, Path, PathBuf};
|
||||||
|
|
||||||
|
pub const MANIFEST: &str = "knock.yaml";
|
||||||
|
pub const FOLDER_META: &str = "folder.yaml";
|
||||||
|
pub const ENV_DIR: &str = "environments";
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Collection {
|
||||||
|
pub root: PathBuf,
|
||||||
|
pub manifest: Manifest,
|
||||||
|
pub tree: FolderNode,
|
||||||
|
pub environments: Vec<EnvEntry>,
|
||||||
|
/// Files that failed to parse, with the error. They stay on disk untouched.
|
||||||
|
pub problems: Vec<Problem>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Problem {
|
||||||
|
pub path: String,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct EnvEntry {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub color: Option<String>,
|
||||||
|
pub protected: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
#[serde(tag = "node", rename_all = "lowercase")]
|
||||||
|
pub enum Node {
|
||||||
|
Folder(FolderNode),
|
||||||
|
Request(RequestHead),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Node {
|
||||||
|
pub fn id(&self) -> &str {
|
||||||
|
match self {
|
||||||
|
Node::Folder(f) => &f.id,
|
||||||
|
Node::Request(r) => &r.id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct FolderNode {
|
||||||
|
/// "" for the collection root.
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub children: Vec<Node>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RequestHead {
|
||||||
|
#[serde(default)]
|
||||||
|
pub id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub kind: RequestKind,
|
||||||
|
#[serde(default)]
|
||||||
|
pub method: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Collection {
|
||||||
|
pub fn open(root: impl AsRef<Path>) -> Result<Self> {
|
||||||
|
let root = root.as_ref().canonicalize().with_context(|| {
|
||||||
|
format!("collection folder {} not found", root.as_ref().display())
|
||||||
|
})?;
|
||||||
|
let manifest_path = root.join(MANIFEST);
|
||||||
|
let mut manifest: Manifest = read_yaml(&manifest_path)
|
||||||
|
.with_context(|| format!("{} is not a knock collection", root.display()))?;
|
||||||
|
if manifest.version > FORMAT_VERSION {
|
||||||
|
bail!(
|
||||||
|
"collection format v{} is newer than this knock (v{FORMAT_VERSION}); update knock",
|
||||||
|
manifest.version
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if manifest.id.is_empty() {
|
||||||
|
manifest.id = uuid::Uuid::new_v4().to_string();
|
||||||
|
write_yaml(&manifest_path, &manifest)?;
|
||||||
|
}
|
||||||
|
let mut problems = Vec::new();
|
||||||
|
let tree = load_folder(&root, "", &manifest.name, &manifest.order, &mut problems)?;
|
||||||
|
let environments = load_env_list(&root)?;
|
||||||
|
Ok(Self {
|
||||||
|
root,
|
||||||
|
manifest,
|
||||||
|
tree,
|
||||||
|
environments,
|
||||||
|
problems,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a new collection in an empty (or not yet existing) folder.
|
||||||
|
pub fn create(root: impl AsRef<Path>, name: &str) -> Result<Self> {
|
||||||
|
let root = root.as_ref();
|
||||||
|
fs::create_dir_all(root.join(ENV_DIR))?;
|
||||||
|
if root.join(MANIFEST).exists() {
|
||||||
|
bail!("{} already contains a collection", root.display());
|
||||||
|
}
|
||||||
|
let manifest = Manifest {
|
||||||
|
version: FORMAT_VERSION,
|
||||||
|
name: name.to_string(),
|
||||||
|
id: uuid::Uuid::new_v4().to_string(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
write_yaml(&root.join(MANIFEST), &manifest)?;
|
||||||
|
let env = Environment {
|
||||||
|
vars: [(
|
||||||
|
"baseUrl".to_string(),
|
||||||
|
EnvVar {
|
||||||
|
value: "http://localhost:8080".into(),
|
||||||
|
secret: false,
|
||||||
|
description: None,
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
write_yaml(&root.join(ENV_DIR).join("local.yaml"), &env)?;
|
||||||
|
ensure_gitignore(root)?;
|
||||||
|
Self::open(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reload(&mut self) -> Result<()> {
|
||||||
|
*self = Self::open(&self.root)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn abs(&self, id: &str) -> Result<PathBuf> {
|
||||||
|
resolve_inside(&self.root, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ reading
|
||||||
|
|
||||||
|
pub fn request(&self, id: &str) -> Result<Request> {
|
||||||
|
read_yaml(&self.abs(id)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn folder_meta(&self, id: &str) -> Result<FolderMeta> {
|
||||||
|
let p = self.abs(id)?.join(FOLDER_META);
|
||||||
|
if p.exists() {
|
||||||
|
read_yaml(&p)
|
||||||
|
} else {
|
||||||
|
Ok(FolderMeta::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn environment(&self, id: &str) -> Result<Environment> {
|
||||||
|
read_yaml(&self.root.join(ENV_DIR).join(format!("{id}.yaml")))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn secrets_file(&self, env: &str) -> Result<SecretsFile> {
|
||||||
|
let p = self.root.join(ENV_DIR).join(format!("{env}.secrets.yaml"));
|
||||||
|
if p.exists() {
|
||||||
|
read_yaml(&p)
|
||||||
|
} else {
|
||||||
|
Ok(SecretsFile::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Folder chain from the root down to the folder that contains `id`,
|
||||||
|
/// root first. Used for auth, header and variable inheritance.
|
||||||
|
pub fn ancestors(&self, id: &str) -> Result<Vec<(String, FolderMeta)>> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let parts: Vec<&str> = id.split('/').collect();
|
||||||
|
let mut cur = String::new();
|
||||||
|
for part in &parts[..parts.len().saturating_sub(1)] {
|
||||||
|
if !cur.is_empty() {
|
||||||
|
cur.push('/');
|
||||||
|
}
|
||||||
|
cur.push_str(part);
|
||||||
|
out.push((cur.clone(), self.folder_meta(&cur)?));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find(&self, id: &str) -> Option<&Node> {
|
||||||
|
fn walk<'a>(f: &'a FolderNode, id: &str) -> Option<&'a Node> {
|
||||||
|
for c in &f.children {
|
||||||
|
if c.id() == id {
|
||||||
|
return Some(c);
|
||||||
|
}
|
||||||
|
if let Node::Folder(sub) = c {
|
||||||
|
if id.starts_with(&format!("{}/", sub.id)) {
|
||||||
|
return walk(sub, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
walk(&self.tree, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All request ids below `folder` ("" = whole collection) in sidebar order.
|
||||||
|
pub fn requests_in(&self, folder: &str) -> Vec<String> {
|
||||||
|
fn walk(f: &FolderNode, out: &mut Vec<String>) {
|
||||||
|
for c in &f.children {
|
||||||
|
match c {
|
||||||
|
Node::Request(r) => out.push(r.id.clone()),
|
||||||
|
Node::Folder(sub) => walk(sub, out),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if folder.is_empty() {
|
||||||
|
walk(&self.tree, &mut out);
|
||||||
|
} else if let Some(Node::Folder(f)) = self.find(folder) {
|
||||||
|
walk(f, &mut out);
|
||||||
|
} else if let Some(Node::Request(r)) = self.find(folder) {
|
||||||
|
out.push(r.id.clone());
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ writing
|
||||||
|
|
||||||
|
pub fn save_request(&self, id: &str, req: &Request) -> Result<()> {
|
||||||
|
write_yaml(&self.abs(id)?, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_folder_meta(&self, id: &str, meta: &FolderMeta) -> Result<()> {
|
||||||
|
if id.is_empty() {
|
||||||
|
bail!("the collection root has no folder.yaml; edit the manifest instead");
|
||||||
|
}
|
||||||
|
write_yaml(&self.abs(id)?.join(FOLDER_META), meta)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_manifest(&self, m: &Manifest) -> Result<()> {
|
||||||
|
write_yaml(&self.root.join(MANIFEST), m)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_environment(&self, id: &str, env: &Environment) -> Result<()> {
|
||||||
|
check_slug(id)?;
|
||||||
|
write_yaml(&self.root.join(ENV_DIR).join(format!("{id}.yaml")), env)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_secrets_file(&self, env: &str, s: &SecretsFile) -> Result<()> {
|
||||||
|
check_slug(env)?;
|
||||||
|
ensure_gitignore(&self.root)?;
|
||||||
|
write_yaml(&self.root.join(ENV_DIR).join(format!("{env}.secrets.yaml")), s)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_environment(&self, id: &str) -> Result<()> {
|
||||||
|
check_slug(id)?;
|
||||||
|
let dir = self.root.join(ENV_DIR);
|
||||||
|
fs::remove_file(dir.join(format!("{id}.yaml")))?;
|
||||||
|
let _ = fs::remove_file(dir.join(format!("{id}.secrets.yaml")));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a request file in `folder` and returns its id.
|
||||||
|
pub fn create_request(&self, folder: &str, req: &Request) -> Result<String> {
|
||||||
|
let dir = self.abs(folder)?;
|
||||||
|
let suffix = match req.kind {
|
||||||
|
RequestKind::Ws => ".ws.yaml",
|
||||||
|
RequestKind::Graphql => ".gql.yaml",
|
||||||
|
RequestKind::Http => ".yaml",
|
||||||
|
};
|
||||||
|
let file = unique_name(&dir, &slugify(&req.name), suffix);
|
||||||
|
let id = join_id(folder, &file);
|
||||||
|
self.save_request(&id, req)?;
|
||||||
|
self.append_order(folder, &file)?;
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_folder(&self, parent: &str, name: &str) -> Result<String> {
|
||||||
|
let dir = self.abs(parent)?;
|
||||||
|
let slug = unique_name(&dir, &slugify(name), "");
|
||||||
|
fs::create_dir_all(dir.join(&slug))?;
|
||||||
|
let id = join_id(parent, &slug);
|
||||||
|
let meta = FolderMeta {
|
||||||
|
name: Some(name.to_string()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
self.save_folder_meta(&id, &meta)?;
|
||||||
|
self.append_order(parent, &slug)?;
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renames the display name and the file or folder on disk. Returns the new id.
|
||||||
|
pub fn rename(&self, id: &str, new_name: &str) -> Result<String> {
|
||||||
|
let path = self.abs(id)?;
|
||||||
|
let (parent, old_file) = split_id(id);
|
||||||
|
let new_file;
|
||||||
|
if path.is_dir() {
|
||||||
|
let mut meta = self.folder_meta(id)?;
|
||||||
|
meta.name = Some(new_name.to_string());
|
||||||
|
self.save_folder_meta(id, &meta)?;
|
||||||
|
new_file = unique_name(&self.abs(parent)?, &slugify(new_name), "");
|
||||||
|
} else {
|
||||||
|
let mut req = self.request(id)?;
|
||||||
|
req.name = new_name.to_string();
|
||||||
|
self.save_request(id, &req)?;
|
||||||
|
let suffix = request_suffix(old_file);
|
||||||
|
let base = slugify(new_name);
|
||||||
|
if format!("{base}{suffix}") == old_file {
|
||||||
|
return Ok(id.to_string());
|
||||||
|
}
|
||||||
|
new_file = unique_name(&self.abs(parent)?, &base, suffix);
|
||||||
|
}
|
||||||
|
if new_file == old_file {
|
||||||
|
return Ok(id.to_string());
|
||||||
|
}
|
||||||
|
fs::rename(&path, self.abs(parent)?.join(&new_file))?;
|
||||||
|
self.replace_in_order(parent, old_file, &new_file)?;
|
||||||
|
Ok(join_id(parent, &new_file))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn duplicate(&self, id: &str) -> Result<String> {
|
||||||
|
let mut req = self.request(id)?;
|
||||||
|
req.name = format!("{} copy", req.name);
|
||||||
|
let (parent, _) = split_id(id);
|
||||||
|
let dir = self.abs(parent)?;
|
||||||
|
let suffix = request_suffix(split_id(id).1);
|
||||||
|
let file = unique_name(&dir, &slugify(&req.name), suffix);
|
||||||
|
let new_id = join_id(parent, &file);
|
||||||
|
self.save_request(&new_id, &req)?;
|
||||||
|
self.insert_order_after(parent, split_id(id).1, &file)?;
|
||||||
|
Ok(new_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete(&self, id: &str) -> Result<()> {
|
||||||
|
if id.is_empty() {
|
||||||
|
bail!("refusing to delete the collection root");
|
||||||
|
}
|
||||||
|
let path = self.abs(id)?;
|
||||||
|
if path.is_dir() {
|
||||||
|
fs::remove_dir_all(&path)?;
|
||||||
|
} else {
|
||||||
|
fs::remove_file(&path)?;
|
||||||
|
}
|
||||||
|
let (parent, file) = split_id(id);
|
||||||
|
self.remove_from_order(parent, file)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves a node into `target_folder` at `index` (None = end). Also used to
|
||||||
|
/// reorder within the same folder.
|
||||||
|
pub fn move_node(&self, id: &str, target_folder: &str, index: Option<usize>) -> Result<String> {
|
||||||
|
let (parent, file) = split_id(id);
|
||||||
|
if target_folder == id || target_folder.starts_with(&format!("{id}/")) {
|
||||||
|
bail!("cannot move a folder into itself");
|
||||||
|
}
|
||||||
|
let new_file = if parent == target_folder {
|
||||||
|
file.to_string()
|
||||||
|
} else {
|
||||||
|
let dir = self.abs(target_folder)?;
|
||||||
|
let new_file = if dir.join(file).exists() {
|
||||||
|
let suffix = request_suffix(file);
|
||||||
|
let base = file.strip_suffix(suffix).unwrap_or(file);
|
||||||
|
unique_name(&dir, base, suffix)
|
||||||
|
} else {
|
||||||
|
file.to_string()
|
||||||
|
};
|
||||||
|
fs::rename(self.abs(id)?, dir.join(&new_file))?;
|
||||||
|
self.remove_from_order(parent, file)?;
|
||||||
|
new_file
|
||||||
|
};
|
||||||
|
let mut order = self.effective_order(target_folder)?;
|
||||||
|
order.retain(|f| f != &new_file);
|
||||||
|
let at = index.unwrap_or(order.len()).min(order.len());
|
||||||
|
order.insert(at, new_file.clone());
|
||||||
|
self.set_order(target_folder, order)?;
|
||||||
|
Ok(join_id(target_folder, &new_file))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ ordering
|
||||||
|
|
||||||
|
/// Order as it is on disk right now, so earlier writes in the same
|
||||||
|
/// operation are taken into account.
|
||||||
|
fn effective_order(&self, folder: &str) -> Result<Vec<String>> {
|
||||||
|
let dir = self.abs(folder)?;
|
||||||
|
let stored = if folder.is_empty() {
|
||||||
|
read_yaml::<Manifest>(&self.root.join(MANIFEST))?.order
|
||||||
|
} else {
|
||||||
|
self.folder_meta(folder)?.order
|
||||||
|
};
|
||||||
|
let entries = list_entries(&dir)?;
|
||||||
|
Ok(apply_order(&stored, entries))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_order(&self, folder: &str, order: Vec<String>) -> Result<()> {
|
||||||
|
if folder.is_empty() {
|
||||||
|
let mut m: Manifest = read_yaml(&self.root.join(MANIFEST))?;
|
||||||
|
m.order = order;
|
||||||
|
self.save_manifest(&m)
|
||||||
|
} else {
|
||||||
|
let mut meta = self.folder_meta(folder)?;
|
||||||
|
meta.order = order;
|
||||||
|
self.save_folder_meta(folder, &meta)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn append_order(&self, folder: &str, file: &str) -> Result<()> {
|
||||||
|
let mut order = self.effective_order(folder)?;
|
||||||
|
if !order.iter().any(|f| f == file) {
|
||||||
|
order.push(file.to_string());
|
||||||
|
}
|
||||||
|
self.set_order(folder, order)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_order_after(&self, folder: &str, after: &str, file: &str) -> Result<()> {
|
||||||
|
let mut order = self.effective_order(folder)?;
|
||||||
|
order.retain(|f| f != file);
|
||||||
|
let at = order.iter().position(|f| f == after).map(|i| i + 1).unwrap_or(order.len());
|
||||||
|
order.insert(at, file.to_string());
|
||||||
|
self.set_order(folder, order)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn replace_in_order(&self, folder: &str, old: &str, new: &str) -> Result<()> {
|
||||||
|
let stored = if folder.is_empty() {
|
||||||
|
read_yaml::<Manifest>(&self.root.join(MANIFEST))?.order
|
||||||
|
} else {
|
||||||
|
self.folder_meta(folder)?.order
|
||||||
|
};
|
||||||
|
if stored.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let order = stored
|
||||||
|
.into_iter()
|
||||||
|
.map(|f| if f == old { new.to_string() } else { f })
|
||||||
|
.collect();
|
||||||
|
self.set_order(folder, order)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_from_order(&self, folder: &str, file: &str) -> Result<()> {
|
||||||
|
let stored = if folder.is_empty() {
|
||||||
|
read_yaml::<Manifest>(&self.root.join(MANIFEST))?.order
|
||||||
|
} else {
|
||||||
|
let p = self.abs(folder)?.join(FOLDER_META);
|
||||||
|
if !p.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
self.folder_meta(folder)?.order
|
||||||
|
};
|
||||||
|
if !stored.iter().any(|f| f == file) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
self.set_order(folder, stored.into_iter().filter(|f| f != file).collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- loading
|
||||||
|
|
||||||
|
fn load_folder(
|
||||||
|
root: &Path,
|
||||||
|
id: &str,
|
||||||
|
name: &str,
|
||||||
|
order: &[String],
|
||||||
|
problems: &mut Vec<Problem>,
|
||||||
|
) -> Result<FolderNode> {
|
||||||
|
let dir = if id.is_empty() { root.to_path_buf() } else { root.join(id) };
|
||||||
|
let entries = list_entries(&dir)?;
|
||||||
|
let ordered = apply_order(order, entries);
|
||||||
|
let mut children = Vec::with_capacity(ordered.len());
|
||||||
|
for file in ordered {
|
||||||
|
let child_id = join_id(id, &file);
|
||||||
|
let path = dir.join(&file);
|
||||||
|
if path.is_dir() {
|
||||||
|
let meta: FolderMeta = match path.join(FOLDER_META) {
|
||||||
|
p if p.exists() => match read_yaml(&p) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(e) => {
|
||||||
|
problems.push(Problem {
|
||||||
|
path: format!("{child_id}/{FOLDER_META}"),
|
||||||
|
message: format!("{e:#}"),
|
||||||
|
});
|
||||||
|
FolderMeta::default()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ => FolderMeta::default(),
|
||||||
|
};
|
||||||
|
let fname = meta.name.clone().unwrap_or_else(|| file.clone());
|
||||||
|
children.push(Node::Folder(load_folder(
|
||||||
|
root, &child_id, &fname, &meta.order, problems,
|
||||||
|
)?));
|
||||||
|
} else {
|
||||||
|
match read_yaml::<RequestHead>(&path) {
|
||||||
|
Ok(mut head) => {
|
||||||
|
head.id = child_id;
|
||||||
|
if head.name.is_empty() {
|
||||||
|
head.name = file.trim_end_matches(".yaml").to_string();
|
||||||
|
}
|
||||||
|
children.push(Node::Request(head));
|
||||||
|
}
|
||||||
|
Err(e) => problems.push(Problem {
|
||||||
|
path: child_id,
|
||||||
|
message: format!("{e:#}"),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(FolderNode {
|
||||||
|
id: id.to_string(),
|
||||||
|
name: name.to_string(),
|
||||||
|
children,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request files and sub folders of a directory, unordered.
|
||||||
|
fn list_entries(dir: &Path) -> Result<Vec<String>> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for e in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
|
||||||
|
let e = e?;
|
||||||
|
let name = e.file_name().to_string_lossy().to_string();
|
||||||
|
if name.starts_with('.') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let ft = e.file_type()?;
|
||||||
|
if ft.is_dir() {
|
||||||
|
if name == ENV_DIR || name == "node_modules" || name == "target" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push(name);
|
||||||
|
} else if (name.ends_with(".yaml") || name.ends_with(".yml"))
|
||||||
|
&& name != MANIFEST
|
||||||
|
&& name != FOLDER_META
|
||||||
|
{
|
||||||
|
out.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stored order first (skipping entries that no longer exist), then the rest
|
||||||
|
/// sorted by name.
|
||||||
|
fn apply_order(stored: &[String], mut entries: Vec<String>) -> Vec<String> {
|
||||||
|
let mut out = Vec::with_capacity(entries.len());
|
||||||
|
for s in stored {
|
||||||
|
if let Some(i) = entries.iter().position(|e| e == s) {
|
||||||
|
out.push(entries.swap_remove(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entries.sort_by_key(|a| a.to_lowercase());
|
||||||
|
out.extend(entries);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_env_list(root: &Path) -> Result<Vec<EnvEntry>> {
|
||||||
|
let dir = root.join(ENV_DIR);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if !dir.exists() {
|
||||||
|
return Ok(out);
|
||||||
|
}
|
||||||
|
for e in fs::read_dir(&dir)? {
|
||||||
|
let e = e?;
|
||||||
|
let name = e.file_name().to_string_lossy().to_string();
|
||||||
|
let Some(id) = name.strip_suffix(".yaml") else { continue };
|
||||||
|
if id.ends_with(".secrets") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let env: Environment = read_yaml(&e.path()).unwrap_or_default();
|
||||||
|
out.push(EnvEntry {
|
||||||
|
id: id.to_string(),
|
||||||
|
name: env.name.unwrap_or_else(|| id.to_string()),
|
||||||
|
color: env.color,
|
||||||
|
protected: env.protected,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- helpers
|
||||||
|
|
||||||
|
pub fn read_yaml<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T> {
|
||||||
|
let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
|
||||||
|
serde_yaml_ng::from_str(&text).with_context(|| format!("parsing {}", path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes atomically (temp file + rename) so a crash never leaves half a file
|
||||||
|
/// and file watchers see one change.
|
||||||
|
pub fn write_yaml<T: Serialize>(path: &Path, value: &T) -> Result<()> {
|
||||||
|
let text = serde_yaml_ng::to_string(value)?;
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
if fs::read_to_string(path).ok().as_deref() == Some(text.as_str()) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let tmp = path.with_extension("yaml.tmp");
|
||||||
|
fs::write(&tmp, text)?;
|
||||||
|
fs::rename(&tmp, path)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_gitignore(root: &Path) -> Result<()> {
|
||||||
|
let p = root.join(".gitignore");
|
||||||
|
let line = "*.secrets.yaml";
|
||||||
|
let cur = fs::read_to_string(&p).unwrap_or_default();
|
||||||
|
if !cur.lines().any(|l| l.trim() == line) {
|
||||||
|
let mut next = cur;
|
||||||
|
if !next.is_empty() && !next.ends_with('\n') {
|
||||||
|
next.push('\n');
|
||||||
|
}
|
||||||
|
next.push_str(line);
|
||||||
|
next.push('\n');
|
||||||
|
fs::write(&p, next)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Joins `id` onto `root` and refuses anything that would leave it.
|
||||||
|
pub fn resolve_inside(root: &Path, id: &str) -> Result<PathBuf> {
|
||||||
|
let rel = Path::new(id);
|
||||||
|
for c in rel.components() {
|
||||||
|
match c {
|
||||||
|
Component::Normal(_) | Component::CurDir => {}
|
||||||
|
_ => return Err(anyhow!("invalid path '{id}'")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(root.join(rel))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_slug(s: &str) -> Result<()> {
|
||||||
|
if s.is_empty() || s.contains(['/', '\\']) || s.starts_with('.') {
|
||||||
|
bail!("invalid name '{s}'");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn join_id(parent: &str, file: &str) -> String {
|
||||||
|
if parent.is_empty() {
|
||||||
|
file.to_string()
|
||||||
|
} else {
|
||||||
|
format!("{parent}/{file}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn split_id(id: &str) -> (&str, &str) {
|
||||||
|
match id.rfind('/') {
|
||||||
|
Some(i) => (&id[..i], &id[i + 1..]),
|
||||||
|
None => ("", id),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_suffix(file: &str) -> &'static str {
|
||||||
|
if file.ends_with(".ws.yaml") {
|
||||||
|
".ws.yaml"
|
||||||
|
} else if file.ends_with(".gql.yaml") {
|
||||||
|
".gql.yaml"
|
||||||
|
} else if file.ends_with(".yml") {
|
||||||
|
".yml"
|
||||||
|
} else {
|
||||||
|
".yaml"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn slugify(name: &str) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut dash = false;
|
||||||
|
for ch in name.trim().chars() {
|
||||||
|
let c = match ch {
|
||||||
|
'ä' | 'Ä' => Some("ae"),
|
||||||
|
'ö' | 'Ö' => Some("oe"),
|
||||||
|
'ü' | 'Ü' => Some("ue"),
|
||||||
|
'ß' => Some("ss"),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
if let Some(rep) = c {
|
||||||
|
out.push_str(rep);
|
||||||
|
dash = false;
|
||||||
|
} else if ch.is_ascii_alphanumeric() {
|
||||||
|
out.push(ch.to_ascii_lowercase());
|
||||||
|
dash = false;
|
||||||
|
} else if !dash && !out.is_empty() {
|
||||||
|
out.push('-');
|
||||||
|
dash = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let out = out.trim_end_matches('-').to_string();
|
||||||
|
if out.is_empty() {
|
||||||
|
"untitled".into()
|
||||||
|
} else {
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unique_name(dir: &Path, base: &str, suffix: &str) -> String {
|
||||||
|
let first = format!("{base}{suffix}");
|
||||||
|
if !dir.join(&first).exists() {
|
||||||
|
return first;
|
||||||
|
}
|
||||||
|
(2..)
|
||||||
|
.map(|n| format!("{base}-{n}{suffix}"))
|
||||||
|
.find(|n| !dir.join(n).exists())
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn tmp() -> PathBuf {
|
||||||
|
let p = std::env::temp_dir().join(format!("knock-test-{}", uuid::Uuid::new_v4()));
|
||||||
|
fs::create_dir_all(&p).unwrap();
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_load_and_order() {
|
||||||
|
let dir = tmp();
|
||||||
|
let c = Collection::create(&dir, "My API").unwrap();
|
||||||
|
assert!(fs::read_to_string(dir.join(".gitignore")).unwrap().contains("*.secrets.yaml"));
|
||||||
|
let users = c.create_folder("", "Users").unwrap();
|
||||||
|
let mut r = Request::default();
|
||||||
|
r.name = "List users".into();
|
||||||
|
let a = c.create_request(&users, &r).unwrap();
|
||||||
|
r.name = "Create user".into();
|
||||||
|
let b = c.create_request(&users, &r).unwrap();
|
||||||
|
assert_eq!(a, "users/list-users.yaml");
|
||||||
|
|
||||||
|
let c = Collection::open(&dir).unwrap();
|
||||||
|
assert_eq!(c.requests_in("users"), vec![a.clone(), b.clone()]);
|
||||||
|
assert_eq!(c.environments[0].id, "local");
|
||||||
|
|
||||||
|
// move b before a
|
||||||
|
c.move_node(&b, "users", Some(0)).unwrap();
|
||||||
|
let c = Collection::open(&dir).unwrap();
|
||||||
|
assert_eq!(c.requests_in(""), vec![b.clone(), a.clone()]);
|
||||||
|
|
||||||
|
let renamed = c.rename(&a, "All users").unwrap();
|
||||||
|
assert_eq!(renamed, "users/all-users.yaml");
|
||||||
|
let c = Collection::open(&dir).unwrap();
|
||||||
|
assert_eq!(c.requests_in(""), vec![b.clone(), renamed.clone()]);
|
||||||
|
|
||||||
|
let dup = c.duplicate(&b).unwrap();
|
||||||
|
let c = Collection::open(&dir).unwrap();
|
||||||
|
assert_eq!(c.requests_in(""), vec![b.clone(), dup.clone(), renamed.clone()]);
|
||||||
|
|
||||||
|
let moved = c.move_node(&dup, "", None).unwrap();
|
||||||
|
let c = Collection::open(&dir).unwrap();
|
||||||
|
assert_eq!(c.requests_in(""), vec![b.clone(), renamed.clone(), moved.clone()]);
|
||||||
|
c.delete(&moved).unwrap();
|
||||||
|
let c = Collection::open(&dir).unwrap();
|
||||||
|
assert_eq!(c.requests_in("").len(), 2);
|
||||||
|
assert!(c.move_node("users", "users", None).is_err());
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_escaping_paths() {
|
||||||
|
let root = Path::new("/tmp/x");
|
||||||
|
assert!(resolve_inside(root, "../etc/passwd").is_err());
|
||||||
|
assert!(resolve_inside(root, "/etc/passwd").is_err());
|
||||||
|
assert!(resolve_inside(root, "a/b.yaml").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn slugs() {
|
||||||
|
assert_eq!(slugify("Create user"), "create-user");
|
||||||
|
assert_eq!(slugify(" Größe / Übersicht!! "), "groesse-uebersicht");
|
||||||
|
assert_eq!(slugify("///"), "untitled");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,492 @@
|
|||||||
|
//! The HTTP engine. Redirects are followed by hand so every hop is visible,
|
||||||
|
//! cookies are kept in a per-collection jar we can show and edit.
|
||||||
|
|
||||||
|
use crate::model::{HttpVersion, ProxyMode};
|
||||||
|
use crate::prepare::{Prepared, PreparedBody};
|
||||||
|
use anyhow::{anyhow, Context, Result};
|
||||||
|
use cookie_store::CookieStore;
|
||||||
|
use futures_util::StreamExt;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
/// Bodies above this size go to a file instead of memory.
|
||||||
|
pub const MEMORY_LIMIT: usize = 50 * 1024 * 1024;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
|
pub struct Timings {
|
||||||
|
/// Time until the response headers arrived, summed over all hops.
|
||||||
|
pub ttfb_ms: f64,
|
||||||
|
pub download_ms: f64,
|
||||||
|
pub total_ms: f64,
|
||||||
|
pub redirect_ms: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Hop {
|
||||||
|
pub method: String,
|
||||||
|
pub url: String,
|
||||||
|
pub status: u16,
|
||||||
|
pub location: String,
|
||||||
|
pub headers: Vec<(String, String)>,
|
||||||
|
pub ms: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CookieInfo {
|
||||||
|
pub name: String,
|
||||||
|
pub value: String,
|
||||||
|
pub domain: String,
|
||||||
|
pub path: String,
|
||||||
|
pub expires: Option<String>,
|
||||||
|
pub secure: bool,
|
||||||
|
pub http_only: bool,
|
||||||
|
pub same_site: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Response {
|
||||||
|
pub status: u16,
|
||||||
|
pub status_text: String,
|
||||||
|
pub http_version: String,
|
||||||
|
pub url: String,
|
||||||
|
pub headers: Vec<(String, String)>,
|
||||||
|
/// Cookies set by this response (all hops).
|
||||||
|
pub cookies: Vec<CookieInfo>,
|
||||||
|
pub size: u64,
|
||||||
|
pub header_size: u64,
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
pub timings: Timings,
|
||||||
|
pub redirects: Vec<Hop>,
|
||||||
|
pub remote_addr: Option<String>,
|
||||||
|
/// Set when the body was larger than [`MEMORY_LIMIT`] and went to disk.
|
||||||
|
pub body_file: Option<PathBuf>,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub body: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Response {
|
||||||
|
pub fn header(&self, name: &str) -> Option<&str> {
|
||||||
|
self.headers
|
||||||
|
.iter()
|
||||||
|
.find(|(k, _)| k.eq_ignore_ascii_case(name))
|
||||||
|
.map(|(_, v)| v.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn text(&self) -> String {
|
||||||
|
String::from_utf8_lossy(&self.body).into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn json(&self) -> Option<serde_json::Value> {
|
||||||
|
serde_json::from_slice(&self.body).ok()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct TransportOptions {
|
||||||
|
pub proxy_mode: ProxyMode,
|
||||||
|
pub proxy_url: Option<String>,
|
||||||
|
pub no_proxy: Option<String>,
|
||||||
|
pub ca_bundle: Option<PathBuf>,
|
||||||
|
/// PEM with certificate and key, presented to the request's host.
|
||||||
|
pub identity_pem: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Hash, PartialEq, Eq, Clone)]
|
||||||
|
struct ClientKey {
|
||||||
|
verify: bool,
|
||||||
|
version: u8,
|
||||||
|
proxy: String,
|
||||||
|
ca: Option<PathBuf>,
|
||||||
|
identity: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Engine {
|
||||||
|
clients: Mutex<HashMap<ClientKey, reqwest::Client>>,
|
||||||
|
jars: Mutex<HashMap<String, Arc<Mutex<CookieStore>>>>,
|
||||||
|
spill_dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Engine {
|
||||||
|
pub fn new(spill_dir: PathBuf) -> Self {
|
||||||
|
Self {
|
||||||
|
clients: Mutex::default(),
|
||||||
|
jars: Mutex::default(),
|
||||||
|
spill_dir,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn jar(&self, collection: &str) -> Arc<Mutex<CookieStore>> {
|
||||||
|
self.jars
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.entry(collection.to_string())
|
||||||
|
.or_insert_with(|| Arc::new(Mutex::new(CookieStore::default())))
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_jar(&self, collection: &str, json: &str) {
|
||||||
|
#[allow(deprecated)]
|
||||||
|
if let Ok(store) = CookieStore::load_json(json.as_bytes()) {
|
||||||
|
*self.jar(collection).lock().unwrap() = store;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_jar(&self, collection: &str) -> String {
|
||||||
|
let jar = self.jar(collection);
|
||||||
|
let store = jar.lock().unwrap();
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
#[allow(deprecated)]
|
||||||
|
let _ = store.save_json(&mut buf);
|
||||||
|
String::from_utf8(buf).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cookies(&self, collection: &str) -> Vec<CookieInfo> {
|
||||||
|
let jar = self.jar(collection);
|
||||||
|
let store = jar.lock().unwrap();
|
||||||
|
store.iter_unexpired().map(cookie_info).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_cookie(&self, collection: &str, domain: &str, path: &str, name: &str) {
|
||||||
|
let jar = self.jar(collection);
|
||||||
|
jar.lock().unwrap().remove(domain, path, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_cookies(&self, collection: &str) {
|
||||||
|
self.jar(collection).lock().unwrap().clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client(&self, p: &Prepared, t: &TransportOptions) -> Result<reqwest::Client> {
|
||||||
|
let version = match p.settings.http_version {
|
||||||
|
HttpVersion::Auto => 0,
|
||||||
|
HttpVersion::Http1 => 1,
|
||||||
|
HttpVersion::Http2 => 2,
|
||||||
|
};
|
||||||
|
let key = ClientKey {
|
||||||
|
verify: p.settings.verify_tls,
|
||||||
|
version,
|
||||||
|
proxy: format!("{:?}|{:?}|{:?}", t.proxy_mode, t.proxy_url, t.no_proxy),
|
||||||
|
ca: t.ca_bundle.clone(),
|
||||||
|
identity: t.identity_pem.as_ref().map(|b| {
|
||||||
|
use std::hash::{Hash, Hasher};
|
||||||
|
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||||
|
b.hash(&mut h);
|
||||||
|
h.finish()
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
if let Some(c) = self.clients.lock().unwrap().get(&key) {
|
||||||
|
return Ok(c.clone());
|
||||||
|
}
|
||||||
|
let mut b = reqwest::Client::builder()
|
||||||
|
.redirect(reqwest::redirect::Policy::none())
|
||||||
|
.user_agent(concat!("knock/", env!("CARGO_PKG_VERSION")))
|
||||||
|
.tls_danger_accept_invalid_certs(!p.settings.verify_tls)
|
||||||
|
.connect_timeout(Duration::from_secs(30));
|
||||||
|
b = match version {
|
||||||
|
1 => b.http1_only(),
|
||||||
|
2 => b.http2_prior_knowledge(),
|
||||||
|
_ => b,
|
||||||
|
};
|
||||||
|
b = match t.proxy_mode {
|
||||||
|
ProxyMode::System => b,
|
||||||
|
ProxyMode::None => b.no_proxy(),
|
||||||
|
ProxyMode::Custom => {
|
||||||
|
let url = t.proxy_url.as_deref().ok_or_else(|| anyhow!("custom proxy has no URL"))?;
|
||||||
|
let mut proxy = reqwest::Proxy::all(url).context("invalid proxy URL")?;
|
||||||
|
if let Some(np) = &t.no_proxy {
|
||||||
|
proxy = proxy.no_proxy(reqwest::NoProxy::from_string(np));
|
||||||
|
}
|
||||||
|
b.proxy(proxy)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(ca) = &t.ca_bundle {
|
||||||
|
let pem = std::fs::read(ca).with_context(|| format!("reading CA bundle {}", ca.display()))?;
|
||||||
|
for cert in reqwest::Certificate::from_pem_bundle(&pem).context("CA bundle is not valid PEM")? {
|
||||||
|
b = b.tls_certs_merge([cert]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(pem) = &t.identity_pem {
|
||||||
|
b = b.identity(reqwest::Identity::from_pem(pem).context("client certificate is not valid PEM")?);
|
||||||
|
}
|
||||||
|
let client = b.build()?;
|
||||||
|
self.clients.lock().unwrap().insert(key, client.clone());
|
||||||
|
Ok(client)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends a prepared request, following redirects according to its settings.
|
||||||
|
pub async fn send(
|
||||||
|
&self,
|
||||||
|
p: &Prepared,
|
||||||
|
transport: &TransportOptions,
|
||||||
|
jar_id: Option<&str>,
|
||||||
|
) -> Result<Response> {
|
||||||
|
let client = self.client(p, transport)?;
|
||||||
|
let jar = jar_id.filter(|_| p.settings.cookies).map(|id| self.jar(id));
|
||||||
|
let started = Instant::now();
|
||||||
|
let mut method = p.method.clone();
|
||||||
|
let mut url = url::Url::parse(&p.url)?;
|
||||||
|
let mut headers = p.headers.clone();
|
||||||
|
let mut body = Some(p.body.clone());
|
||||||
|
let mut hops = Vec::new();
|
||||||
|
let mut cookies = Vec::new();
|
||||||
|
let mut ttfb = 0.0;
|
||||||
|
let original_origin = url.origin();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let hop_start = Instant::now();
|
||||||
|
let m = reqwest::Method::from_bytes(method.as_bytes())
|
||||||
|
.map_err(|_| anyhow!("invalid method '{method}'"))?;
|
||||||
|
let mut rb = client
|
||||||
|
.request(m, url.clone())
|
||||||
|
.timeout(Duration::from_millis(p.settings.timeout_ms.max(1)));
|
||||||
|
let mut cookie_header: Option<String> = None;
|
||||||
|
for (k, v) in &headers {
|
||||||
|
if k.eq_ignore_ascii_case("cookie") {
|
||||||
|
cookie_header = Some(match cookie_header {
|
||||||
|
Some(c) => format!("{c}; {v}"),
|
||||||
|
None => v.clone(),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
rb = rb.header(k, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(jar) = &jar {
|
||||||
|
let store = jar.lock().unwrap();
|
||||||
|
let from_jar: Vec<String> = store
|
||||||
|
.get_request_values(&url)
|
||||||
|
.map(|(n, v)| format!("{n}={v}"))
|
||||||
|
.collect();
|
||||||
|
if !from_jar.is_empty() {
|
||||||
|
let jar_str = from_jar.join("; ");
|
||||||
|
cookie_header = Some(match cookie_header {
|
||||||
|
Some(c) => format!("{c}; {jar_str}"),
|
||||||
|
None => jar_str,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(c) = cookie_header {
|
||||||
|
rb = rb.header("Cookie", c);
|
||||||
|
}
|
||||||
|
rb = match body.as_ref() {
|
||||||
|
Some(PreparedBody::Bytes { data, .. }) => rb.body(data.clone()),
|
||||||
|
Some(PreparedBody::Multipart { parts }) => rb.multipart(build_multipart(parts).await?),
|
||||||
|
_ => rb,
|
||||||
|
};
|
||||||
|
let resp = rb.send().await.map_err(describe_error)?;
|
||||||
|
ttfb += hop_start.elapsed().as_secs_f64() * 1000.0;
|
||||||
|
|
||||||
|
let status = resp.status();
|
||||||
|
let resp_headers: Vec<(String, String)> = resp
|
||||||
|
.headers()
|
||||||
|
.iter()
|
||||||
|
.map(|(k, v)| (k.to_string(), String::from_utf8_lossy(v.as_bytes()).into_owned()))
|
||||||
|
.collect();
|
||||||
|
let set_cookies: Vec<&str> = resp_headers
|
||||||
|
.iter()
|
||||||
|
.filter(|(k, _)| k.eq_ignore_ascii_case("set-cookie"))
|
||||||
|
.map(|(_, v)| v.as_str())
|
||||||
|
.collect();
|
||||||
|
for sc in &set_cookies {
|
||||||
|
if let Ok(c) = cookie_store::RawCookie::parse(sc.to_string()) {
|
||||||
|
cookies.push(raw_cookie_info(&c, &url));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(jar) = &jar {
|
||||||
|
let parsed = set_cookies
|
||||||
|
.iter()
|
||||||
|
.filter_map(|s| cookie_store::RawCookie::parse(s.to_string()).ok());
|
||||||
|
jar.lock().unwrap().store_response_cookies(parsed, &url);
|
||||||
|
}
|
||||||
|
|
||||||
|
let location = resp
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::LOCATION)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(str::to_string);
|
||||||
|
if status.is_redirection()
|
||||||
|
&& p.settings.follow_redirects
|
||||||
|
&& location.is_some()
|
||||||
|
&& (hops.len() as u32) < p.settings.max_redirects
|
||||||
|
{
|
||||||
|
let loc = location.unwrap();
|
||||||
|
let next = url.join(&loc).with_context(|| format!("bad Location header '{loc}'"))?;
|
||||||
|
hops.push(Hop {
|
||||||
|
method: method.clone(),
|
||||||
|
url: url.to_string(),
|
||||||
|
status: status.as_u16(),
|
||||||
|
location: next.to_string(),
|
||||||
|
headers: resp_headers,
|
||||||
|
ms: hop_start.elapsed().as_secs_f64() * 1000.0,
|
||||||
|
});
|
||||||
|
let code = status.as_u16();
|
||||||
|
if code == 303 || ((code == 301 || code == 302) && method == "POST") {
|
||||||
|
if method != "HEAD" {
|
||||||
|
method = "GET".into();
|
||||||
|
}
|
||||||
|
body = None;
|
||||||
|
headers.retain(|(k, _)| {
|
||||||
|
!k.eq_ignore_ascii_case("content-type") && !k.eq_ignore_ascii_case("content-length")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if next.origin() != original_origin {
|
||||||
|
// Same rule as curl: credentials never follow to another host.
|
||||||
|
headers.retain(|(k, _)| {
|
||||||
|
!k.eq_ignore_ascii_case("authorization") && !k.eq_ignore_ascii_case("cookie")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
url = next;
|
||||||
|
// Drain so the connection can be reused.
|
||||||
|
let _ = resp.bytes().await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let redirect_ms: f64 = hops.iter().map(|h| h.ms).sum();
|
||||||
|
let http_version = format!("{:?}", resp.version()).replace("HTTP/", "");
|
||||||
|
let remote_addr = resp.remote_addr().map(|a| a.to_string());
|
||||||
|
let final_url = resp.url().to_string();
|
||||||
|
let content_type = resp
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::CONTENT_TYPE)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(str::to_string);
|
||||||
|
let header_size: u64 = resp_headers.iter().map(|(k, v)| (k.len() + v.len() + 4) as u64).sum();
|
||||||
|
let status_text = status.canonical_reason().unwrap_or("").to_string();
|
||||||
|
|
||||||
|
let dl_start = Instant::now();
|
||||||
|
let (body, body_file, size) = self.read_body(resp).await?;
|
||||||
|
let download_ms = dl_start.elapsed().as_secs_f64() * 1000.0;
|
||||||
|
|
||||||
|
return Ok(Response {
|
||||||
|
status: status.as_u16(),
|
||||||
|
status_text,
|
||||||
|
http_version,
|
||||||
|
url: final_url,
|
||||||
|
headers: resp_headers,
|
||||||
|
cookies,
|
||||||
|
size,
|
||||||
|
header_size,
|
||||||
|
content_type,
|
||||||
|
timings: Timings {
|
||||||
|
ttfb_ms: ttfb,
|
||||||
|
download_ms,
|
||||||
|
total_ms: started.elapsed().as_secs_f64() * 1000.0,
|
||||||
|
redirect_ms,
|
||||||
|
},
|
||||||
|
redirects: hops,
|
||||||
|
remote_addr,
|
||||||
|
body_file,
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_body(&self, resp: reqwest::Response) -> Result<(Vec<u8>, Option<PathBuf>, u64)> {
|
||||||
|
let mut stream = resp.bytes_stream();
|
||||||
|
let mut buf: Vec<u8> = Vec::new();
|
||||||
|
let mut file: Option<(std::fs::File, PathBuf)> = None;
|
||||||
|
let mut size = 0u64;
|
||||||
|
while let Some(chunk) = stream.next().await {
|
||||||
|
let chunk = chunk.map_err(describe_error)?;
|
||||||
|
size += chunk.len() as u64;
|
||||||
|
if let Some((f, _)) = file.as_mut() {
|
||||||
|
f.write_all(&chunk)?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if buf.len() + chunk.len() > MEMORY_LIMIT {
|
||||||
|
std::fs::create_dir_all(&self.spill_dir)?;
|
||||||
|
let path = self.spill_dir.join(format!("response-{}.bin", uuid::Uuid::new_v4()));
|
||||||
|
let mut f = std::fs::File::create(&path)?;
|
||||||
|
f.write_all(&buf)?;
|
||||||
|
f.write_all(&chunk)?;
|
||||||
|
// Keep the first MB in memory for the preview.
|
||||||
|
buf.truncate(1024 * 1024);
|
||||||
|
file = Some((f, path));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
buf.extend_from_slice(&chunk);
|
||||||
|
}
|
||||||
|
Ok((buf, file.map(|(_, p)| p), size))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn build_multipart(parts: &[crate::prepare::PreparedPart]) -> Result<reqwest::multipart::Form> {
|
||||||
|
let mut form = reqwest::multipart::Form::new();
|
||||||
|
for p in parts {
|
||||||
|
let part = if let Some(path) = &p.file {
|
||||||
|
let data = tokio::fs::read(path)
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("reading {}", path.display()))?;
|
||||||
|
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||||
|
reqwest::multipart::Part::bytes(data).file_name(name)
|
||||||
|
} else {
|
||||||
|
reqwest::multipart::Part::text(p.value.clone().unwrap_or_default())
|
||||||
|
};
|
||||||
|
let part = match &p.content_type {
|
||||||
|
Some(ct) => part.mime_str(ct)?,
|
||||||
|
None => part,
|
||||||
|
};
|
||||||
|
form = form.part(p.name.clone(), part);
|
||||||
|
}
|
||||||
|
Ok(form)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// reqwest errors hide the interesting part in the source chain.
|
||||||
|
fn describe_error(e: reqwest::Error) -> anyhow::Error {
|
||||||
|
let mut msg = if e.is_timeout() {
|
||||||
|
"request timed out".to_string()
|
||||||
|
} else if e.is_connect() {
|
||||||
|
"could not connect".to_string()
|
||||||
|
} else {
|
||||||
|
"request failed".to_string()
|
||||||
|
};
|
||||||
|
let mut src: Option<&dyn std::error::Error> = std::error::Error::source(&e);
|
||||||
|
let mut seen = Vec::new();
|
||||||
|
while let Some(s) = src {
|
||||||
|
let t = s.to_string();
|
||||||
|
if !seen.contains(&t) {
|
||||||
|
msg.push_str(": ");
|
||||||
|
msg.push_str(&t);
|
||||||
|
seen.push(t);
|
||||||
|
}
|
||||||
|
src = s.source();
|
||||||
|
}
|
||||||
|
anyhow!(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cookie_info(c: &cookie_store::Cookie<'_>) -> CookieInfo {
|
||||||
|
CookieInfo {
|
||||||
|
name: c.name().to_string(),
|
||||||
|
value: c.value().to_string(),
|
||||||
|
domain: match &c.domain {
|
||||||
|
cookie_store::CookieDomain::HostOnly(d) | cookie_store::CookieDomain::Suffix(d) => d.clone(),
|
||||||
|
_ => String::new(),
|
||||||
|
},
|
||||||
|
path: String::from(c.path.as_ref()),
|
||||||
|
expires: match c.expires {
|
||||||
|
cookie_store::CookieExpiration::AtUtc(t) => Some(t.to_string()),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
secure: c.secure().unwrap_or(false),
|
||||||
|
http_only: c.http_only().unwrap_or(false),
|
||||||
|
same_site: c.same_site().map(|s| s.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn raw_cookie_info(c: &cookie_store::RawCookie<'_>, url: &url::Url) -> CookieInfo {
|
||||||
|
CookieInfo {
|
||||||
|
name: c.name().to_string(),
|
||||||
|
value: c.value().to_string(),
|
||||||
|
domain: c.domain().map(str::to_string).unwrap_or_else(|| url.host_str().unwrap_or("").to_string()),
|
||||||
|
path: c.path().unwrap_or("/").to_string(),
|
||||||
|
expires: c
|
||||||
|
.expires_datetime()
|
||||||
|
.map(|t| t.to_string())
|
||||||
|
.or_else(|| c.max_age().map(|a| format!("max-age {}s", a.whole_seconds()))),
|
||||||
|
secure: c.secure().unwrap_or(false),
|
||||||
|
http_only: c.http_only().unwrap_or(false),
|
||||||
|
same_site: c.same_site().map(|s| s.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
pub mod auth;
|
||||||
|
pub mod checks;
|
||||||
|
pub mod collection;
|
||||||
|
pub mod http;
|
||||||
|
pub mod model;
|
||||||
|
pub mod prepare;
|
||||||
|
pub mod run;
|
||||||
|
pub mod secrets;
|
||||||
|
pub mod vars;
|
||||||
|
|
||||||
|
pub use collection::Collection;
|
||||||
@@ -0,0 +1,693 @@
|
|||||||
|
//! On-disk data model. Every struct keeps unknown keys in `extra` so a file
|
||||||
|
//! written by a newer knock survives a round trip through an older one.
|
||||||
|
|
||||||
|
use indexmap::IndexMap;
|
||||||
|
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||||
|
use serde_yaml_ng::Value as Yaml;
|
||||||
|
|
||||||
|
pub type Extra = IndexMap<String, Yaml>;
|
||||||
|
|
||||||
|
pub const FORMAT_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
fn is_true(b: &bool) -> bool {
|
||||||
|
*b
|
||||||
|
}
|
||||||
|
fn is_false(b: &bool) -> bool {
|
||||||
|
!*b
|
||||||
|
}
|
||||||
|
fn yes() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct KeyValue {
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub value: String,
|
||||||
|
#[serde(default = "yes", skip_serializing_if = "is_true")]
|
||||||
|
pub enabled: bool,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub description: Option<String>,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub extra: Extra,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyValue {
|
||||||
|
pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
name: name.into(),
|
||||||
|
value: value.into(),
|
||||||
|
enabled: true,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- manifest
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
|
pub struct Manifest {
|
||||||
|
#[serde(default = "format_version")]
|
||||||
|
pub version: u32,
|
||||||
|
pub name: String,
|
||||||
|
/// Stable id used to key secrets and tokens in the keyring.
|
||||||
|
#[serde(default)]
|
||||||
|
pub id: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Auth::is_none_or_inherit")]
|
||||||
|
pub auth: Auth,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub headers: Vec<KeyValue>,
|
||||||
|
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
|
||||||
|
pub vars: IndexMap<String, String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub order: Vec<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "CollectionSettings::is_default")]
|
||||||
|
pub settings: CollectionSettings,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub extra: Extra,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_version() -> u32 {
|
||||||
|
FORMAT_VERSION
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct CollectionSettings {
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub proxy: Option<ProxySettings>,
|
||||||
|
/// Extra CA bundle (PEM) trusted for every request in this collection.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub ca_bundle: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub client_certs: Vec<ClientCert>,
|
||||||
|
#[serde(default = "yes", skip_serializing_if = "is_true")]
|
||||||
|
pub cookies: bool,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub extra: Extra,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CollectionSettings {
|
||||||
|
fn is_default(&self) -> bool {
|
||||||
|
self.proxy.is_none()
|
||||||
|
&& self.ca_bundle.is_none()
|
||||||
|
&& self.client_certs.is_empty()
|
||||||
|
&& self.cookies
|
||||||
|
&& self.extra.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct ProxySettings {
|
||||||
|
/// `system` honours HTTP(S)_PROXY / NO_PROXY, `none` disables, `custom` uses `url`.
|
||||||
|
#[serde(default)]
|
||||||
|
pub mode: ProxyMode,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub url: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub no_proxy: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum ProxyMode {
|
||||||
|
#[default]
|
||||||
|
System,
|
||||||
|
None,
|
||||||
|
Custom,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct ClientCert {
|
||||||
|
/// Host (optionally with port) the certificate is presented to.
|
||||||
|
pub host: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub cert: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub key: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub pkcs12: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub passphrase: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- folder
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
|
pub struct FolderMeta {
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub name: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub order: Vec<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Auth::is_inherit")]
|
||||||
|
pub auth: Auth,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub headers: Vec<KeyValue>,
|
||||||
|
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
|
||||||
|
pub vars: IndexMap<String, String>,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub extra: Extra,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- request
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum RequestKind {
|
||||||
|
#[default]
|
||||||
|
Http,
|
||||||
|
Graphql,
|
||||||
|
Ws,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Request {
|
||||||
|
pub name: String,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub kind: RequestKind,
|
||||||
|
#[serde(default = "default_method", skip_serializing_if = "Option::is_none")]
|
||||||
|
pub method: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub url: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Params::is_empty")]
|
||||||
|
pub params: Params,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub headers: Vec<KeyValue>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub auth: Auth,
|
||||||
|
#[serde(default, skip_serializing_if = "Body::is_none")]
|
||||||
|
pub body: Body,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub graphql: Option<GraphqlSpec>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub ws: Option<WsSpec>,
|
||||||
|
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
|
||||||
|
pub vars: IndexMap<String, String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub extract: Vec<ExtractRule>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub assert: Vec<AssertRule>,
|
||||||
|
#[serde(default, skip_serializing_if = "RequestSettings::is_default")]
|
||||||
|
pub settings: RequestSettings,
|
||||||
|
/// JSON Schema (inline or `$ref` to a file / OpenAPI pointer) describing the body.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub schema: Option<serde_json::Value>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub docs: Option<String>,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub extra: Extra,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_method() -> Option<String> {
|
||||||
|
Some("GET".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Request {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
name: "New request".into(),
|
||||||
|
kind: RequestKind::Http,
|
||||||
|
method: default_method(),
|
||||||
|
url: String::new(),
|
||||||
|
params: Params::default(),
|
||||||
|
headers: Vec::new(),
|
||||||
|
auth: Auth::Inherit,
|
||||||
|
body: Body::default(),
|
||||||
|
graphql: None,
|
||||||
|
ws: None,
|
||||||
|
vars: IndexMap::new(),
|
||||||
|
extract: Vec::new(),
|
||||||
|
assert: Vec::new(),
|
||||||
|
settings: RequestSettings::default(),
|
||||||
|
schema: None,
|
||||||
|
docs: None,
|
||||||
|
extra: Extra::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Request {
|
||||||
|
pub fn method(&self) -> &str {
|
||||||
|
self.method.as_deref().unwrap_or("GET")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Params {
|
||||||
|
#[serde(default)]
|
||||||
|
pub query: Vec<KeyValue>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub path: IndexMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Params {
|
||||||
|
fn is_empty(&self) -> bool {
|
||||||
|
self.query.is_empty() && self.path.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum BodyType {
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
Json,
|
||||||
|
Raw,
|
||||||
|
#[serde(rename = "form")]
|
||||||
|
FormUrlencoded,
|
||||||
|
Multipart,
|
||||||
|
Binary,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Body {
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub kind: BodyType,
|
||||||
|
/// Text content for json and raw bodies.
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
pub content: String,
|
||||||
|
/// Content type for raw bodies, e.g. `application/xml`.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
/// Comments are allowed and stripped before sending.
|
||||||
|
#[serde(default, skip_serializing_if = "is_false")]
|
||||||
|
pub jsonc: bool,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub form: Vec<KeyValue>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub multipart: Vec<MultipartPart>,
|
||||||
|
/// File path for binary bodies, relative to the collection root.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub file: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Body {
|
||||||
|
fn is_none(&self) -> bool {
|
||||||
|
self.kind == BodyType::None && self.content.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct MultipartPart {
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
pub value: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub file: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
#[serde(default = "yes", skip_serializing_if = "is_true")]
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct GraphqlSpec {
|
||||||
|
#[serde(default)]
|
||||||
|
pub query: String,
|
||||||
|
/// JSON text, edited with the same JSON editor as bodies.
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
pub variables: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub operation_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct WsSpec {
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub subprotocols: Vec<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub messages: Vec<WsSavedMessage>,
|
||||||
|
#[serde(default, skip_serializing_if = "is_false")]
|
||||||
|
pub auto_reconnect: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct WsSavedMessage {
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub format: WsFormat,
|
||||||
|
#[serde(default)]
|
||||||
|
pub content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum WsFormat {
|
||||||
|
#[default]
|
||||||
|
Text,
|
||||||
|
Json,
|
||||||
|
Hex,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum HttpVersion {
|
||||||
|
#[default]
|
||||||
|
#[serde(rename = "auto")]
|
||||||
|
Auto,
|
||||||
|
#[serde(rename = "1.1")]
|
||||||
|
Http1,
|
||||||
|
#[serde(rename = "2")]
|
||||||
|
Http2,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct RequestSettings {
|
||||||
|
#[serde(default = "default_timeout")]
|
||||||
|
pub timeout_ms: u64,
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub follow_redirects: bool,
|
||||||
|
#[serde(default = "default_max_redirects")]
|
||||||
|
pub max_redirects: u32,
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub verify_tls: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub http_version: HttpVersion,
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub cookies: bool,
|
||||||
|
/// Retry once after a 401 when an OAuth token could be refreshed.
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub retry_on_401: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_timeout() -> u64 {
|
||||||
|
30_000
|
||||||
|
}
|
||||||
|
fn default_max_redirects() -> u32 {
|
||||||
|
10
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for RequestSettings {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
timeout_ms: default_timeout(),
|
||||||
|
follow_redirects: true,
|
||||||
|
max_redirects: default_max_redirects(),
|
||||||
|
verify_tls: true,
|
||||||
|
http_version: HttpVersion::Auto,
|
||||||
|
cookies: true,
|
||||||
|
retry_on_401: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RequestSettings {
|
||||||
|
fn is_default(&self) -> bool {
|
||||||
|
*self == Self::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum ExtractSource {
|
||||||
|
#[default]
|
||||||
|
Json,
|
||||||
|
Header,
|
||||||
|
Cookie,
|
||||||
|
Regex,
|
||||||
|
Status,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct ExtractRule {
|
||||||
|
pub var: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub from: ExtractSource,
|
||||||
|
/// JSONPath, header name, cookie name or regex, depending on `from`.
|
||||||
|
#[serde(default)]
|
||||||
|
pub path: String,
|
||||||
|
#[serde(default = "yes", skip_serializing_if = "is_true")]
|
||||||
|
pub enabled: bool,
|
||||||
|
/// Keep the value after the session ends.
|
||||||
|
#[serde(default, skip_serializing_if = "is_false")]
|
||||||
|
pub persist: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum AssertTarget {
|
||||||
|
#[default]
|
||||||
|
Status,
|
||||||
|
Header,
|
||||||
|
Time,
|
||||||
|
Json,
|
||||||
|
Size,
|
||||||
|
Body,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct AssertRule {
|
||||||
|
pub on: AssertTarget,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub path: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub equals: Option<serde_json::Value>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub not_equals: Option<serde_json::Value>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub contains: Option<serde_json::Value>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub exists: Option<bool>,
|
||||||
|
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub type_is: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub matches: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub gt: Option<f64>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub lt: Option<f64>,
|
||||||
|
#[serde(default = "yes", skip_serializing_if = "is_true")]
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- auth
|
||||||
|
|
||||||
|
/// Auth is `inherit`, `none`, or a map with a `type` key. The map form keeps
|
||||||
|
/// its fields loosely typed so the UI can round-trip anything it does not know.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq)]
|
||||||
|
pub enum Auth {
|
||||||
|
#[default]
|
||||||
|
Inherit,
|
||||||
|
None,
|
||||||
|
Config(AuthConfig),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Auth {
|
||||||
|
pub fn is_inherit(&self) -> bool {
|
||||||
|
matches!(self, Auth::Inherit)
|
||||||
|
}
|
||||||
|
pub fn is_none_or_inherit(&self) -> bool {
|
||||||
|
matches!(self, Auth::Inherit | Auth::None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct AuthConfig {
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub kind: String,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub fields: IndexMap<String, serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthConfig {
|
||||||
|
pub fn str(&self, key: &str) -> Option<&str> {
|
||||||
|
self.fields.get(key).and_then(|v| v.as_str())
|
||||||
|
}
|
||||||
|
pub fn string(&self, key: &str) -> String {
|
||||||
|
self.str(key).unwrap_or_default().to_string()
|
||||||
|
}
|
||||||
|
pub fn bool(&self, key: &str, default: bool) -> bool {
|
||||||
|
self.fields.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Serialize for Auth {
|
||||||
|
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||||
|
match self {
|
||||||
|
Auth::Inherit => s.serialize_str("inherit"),
|
||||||
|
Auth::None => s.serialize_str("none"),
|
||||||
|
Auth::Config(c) => c.serialize(s),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'de> Deserialize<'de> for Auth {
|
||||||
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||||
|
let v = serde_json::Value::deserialize(d)?;
|
||||||
|
match v {
|
||||||
|
serde_json::Value::Null => Ok(Auth::Inherit),
|
||||||
|
serde_json::Value::String(s) => match s.as_str() {
|
||||||
|
"inherit" => Ok(Auth::Inherit),
|
||||||
|
"none" => Ok(Auth::None),
|
||||||
|
other => Ok(Auth::Config(AuthConfig {
|
||||||
|
kind: other.to_string(),
|
||||||
|
fields: IndexMap::new(),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
serde_json::Value::Object(_) => {
|
||||||
|
let c: AuthConfig =
|
||||||
|
serde_json::from_value(v).map_err(serde::de::Error::custom)?;
|
||||||
|
match c.kind.as_str() {
|
||||||
|
"inherit" => Ok(Auth::Inherit),
|
||||||
|
"none" => Ok(Auth::None),
|
||||||
|
_ => Ok(Auth::Config(c)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => Err(serde::de::Error::custom("auth must be a string or a map")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- environment
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
|
pub struct Environment {
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub name: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub color: Option<String>,
|
||||||
|
/// Shows the "you are sending to prod" banner and confirms destructive methods.
|
||||||
|
#[serde(default, skip_serializing_if = "is_false")]
|
||||||
|
pub protected: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub vars: IndexMap<String, EnvVar>,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub extra: Extra,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `key: value` or `key: { value, secret: true }`. Secret values never live
|
||||||
|
/// here; the file only marks the variable as secret.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct EnvVar {
|
||||||
|
pub value: String,
|
||||||
|
pub secret: bool,
|
||||||
|
pub description: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Serialize for EnvVar {
|
||||||
|
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||||
|
use serde::ser::SerializeMap;
|
||||||
|
if !self.secret && self.description.is_none() {
|
||||||
|
return s.serialize_str(&self.value);
|
||||||
|
}
|
||||||
|
let mut m = s.serialize_map(None)?;
|
||||||
|
if !self.secret {
|
||||||
|
m.serialize_entry("value", &self.value)?;
|
||||||
|
}
|
||||||
|
if self.secret {
|
||||||
|
m.serialize_entry("secret", &true)?;
|
||||||
|
}
|
||||||
|
if let Some(d) = &self.description {
|
||||||
|
m.serialize_entry("description", d)?;
|
||||||
|
}
|
||||||
|
m.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'de> Deserialize<'de> for EnvVar {
|
||||||
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||||
|
let v = serde_json::Value::deserialize(d)?;
|
||||||
|
Ok(match v {
|
||||||
|
serde_json::Value::Object(m) => EnvVar {
|
||||||
|
value: m.get("value").map(scalar_to_string).unwrap_or_default(),
|
||||||
|
secret: m.get("secret").and_then(|v| v.as_bool()).unwrap_or(false),
|
||||||
|
description: m
|
||||||
|
.get("description")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(str::to_string),
|
||||||
|
},
|
||||||
|
other => EnvVar {
|
||||||
|
value: scalar_to_string(&other),
|
||||||
|
secret: false,
|
||||||
|
description: None,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn scalar_to_string(v: &serde_json::Value) -> String {
|
||||||
|
match v {
|
||||||
|
serde_json::Value::String(s) => s.clone(),
|
||||||
|
serde_json::Value::Null => String::new(),
|
||||||
|
other => other.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
|
pub struct SecretsFile {
|
||||||
|
#[serde(default)]
|
||||||
|
pub vars: IndexMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const SAMPLE: &str = r#"
|
||||||
|
name: Create user
|
||||||
|
type: http
|
||||||
|
method: POST
|
||||||
|
url: "{{baseUrl}}/users"
|
||||||
|
params:
|
||||||
|
query: []
|
||||||
|
path: {}
|
||||||
|
headers:
|
||||||
|
- { name: Accept, value: application/json }
|
||||||
|
auth: inherit
|
||||||
|
body:
|
||||||
|
type: json
|
||||||
|
content: |
|
||||||
|
{
|
||||||
|
"name": "{{userName}}",
|
||||||
|
"roles": ["admin"]
|
||||||
|
}
|
||||||
|
extract:
|
||||||
|
- { var: userId, from: json, path: $.id }
|
||||||
|
assert:
|
||||||
|
- { on: status, equals: 201 }
|
||||||
|
futureField:
|
||||||
|
nested: true
|
||||||
|
"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_spec_example_and_keeps_unknown_fields() {
|
||||||
|
let r: Request = serde_yaml_ng::from_str(SAMPLE).unwrap();
|
||||||
|
assert_eq!(r.method(), "POST");
|
||||||
|
assert_eq!(r.body.kind, BodyType::Json);
|
||||||
|
assert!(r.body.content.contains("\"roles\""));
|
||||||
|
assert_eq!(r.extract[0].path, "$.id");
|
||||||
|
assert_eq!(r.assert[0].equals, Some(serde_json::json!(201)));
|
||||||
|
assert!(r.extra.contains_key("futureField"));
|
||||||
|
|
||||||
|
let out = serde_yaml_ng::to_string(&r).unwrap();
|
||||||
|
assert!(out.contains("futureField"));
|
||||||
|
assert!(out.contains("content: |"), "body should stay a block scalar:\n{out}");
|
||||||
|
let again: Request = serde_yaml_ng::from_str(&out).unwrap();
|
||||||
|
assert_eq!(again.body, r.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auth_forms() {
|
||||||
|
let a: Auth = serde_yaml_ng::from_str("none").unwrap();
|
||||||
|
assert_eq!(a, Auth::None);
|
||||||
|
let a: Auth = serde_yaml_ng::from_str("{ type: bearer, token: '{{secret.t}}' }").unwrap();
|
||||||
|
match a {
|
||||||
|
Auth::Config(c) => {
|
||||||
|
assert_eq!(c.kind, "bearer");
|
||||||
|
assert_eq!(c.str("token"), Some("{{secret.t}}"));
|
||||||
|
}
|
||||||
|
_ => panic!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn env_vars() {
|
||||||
|
let e: Environment = serde_yaml_ng::from_str(
|
||||||
|
"vars:\n baseUrl: http://x\n port: 8080\n token: { secret: true }\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(e.vars["port"].value, "8080");
|
||||||
|
assert!(e.vars["token"].secret);
|
||||||
|
let out = serde_yaml_ng::to_string(&e).unwrap();
|
||||||
|
assert!(out.contains("baseUrl: http://x"));
|
||||||
|
assert!(out.contains("secret: true"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,567 @@
|
|||||||
|
//! Turns a stored request plus its context into a concrete, fully resolved
|
||||||
|
//! request. Nothing here touches the network.
|
||||||
|
|
||||||
|
use crate::collection::Collection;
|
||||||
|
use crate::model::*;
|
||||||
|
use crate::vars::{Layer, OauthLookup, Resolver, Scope, SecretLookup};
|
||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use indexmap::IndexMap;
|
||||||
|
use serde::Serialize;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum AuthOrigin {
|
||||||
|
Request,
|
||||||
|
Folder,
|
||||||
|
Collection,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct EffectiveAuth {
|
||||||
|
pub auth: Auth,
|
||||||
|
pub origin: AuthOrigin,
|
||||||
|
/// Folder id or request id the auth was defined on.
|
||||||
|
pub source: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything needed to resolve and send one request of a collection.
|
||||||
|
pub struct RequestContext {
|
||||||
|
pub resolver: Resolver,
|
||||||
|
pub auth: EffectiveAuth,
|
||||||
|
/// Inherited headers, collection first, then folders, root to leaf.
|
||||||
|
pub inherited_headers: Vec<KeyValue>,
|
||||||
|
pub root: PathBuf,
|
||||||
|
pub collection_settings: CollectionSettings,
|
||||||
|
pub collection_id: String,
|
||||||
|
pub env: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ContextInput<'a> {
|
||||||
|
pub collection: &'a Collection,
|
||||||
|
pub request_id: &'a str,
|
||||||
|
pub request: &'a Request,
|
||||||
|
pub env: Option<&'a str>,
|
||||||
|
pub runtime: IndexMap<String, String>,
|
||||||
|
pub globals: IndexMap<String, String>,
|
||||||
|
pub secrets: Arc<dyn SecretLookup>,
|
||||||
|
pub oauth: Option<Arc<dyn OauthLookup>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RequestContext {
|
||||||
|
pub fn build(input: ContextInput<'_>) -> Result<Self> {
|
||||||
|
let c = input.collection;
|
||||||
|
let ancestors = c.ancestors(input.request_id)?;
|
||||||
|
let mut layers = vec![
|
||||||
|
Layer::new(Scope::Runtime, "runtime", input.runtime),
|
||||||
|
Layer::new(Scope::Request, input.request_id, input.request.vars.clone()),
|
||||||
|
];
|
||||||
|
for (id, meta) in ancestors.iter().rev() {
|
||||||
|
layers.push(Layer::new(Scope::Folder, format!("{id}/folder.yaml"), meta.vars.clone()));
|
||||||
|
}
|
||||||
|
if let Some(env_id) = input.env {
|
||||||
|
let env = c.environment(env_id).with_context(|| format!("environment '{env_id}'"))?;
|
||||||
|
let file = c.secrets_file(env_id).unwrap_or_default();
|
||||||
|
let mut layer = Layer::new(Scope::Environment, env_id, IndexMap::new());
|
||||||
|
for (k, v) in env.vars {
|
||||||
|
if v.secret {
|
||||||
|
layer.secret.insert(k.clone());
|
||||||
|
layer.vars.insert(k.clone(), file.vars.get(&k).cloned().unwrap_or_default());
|
||||||
|
} else {
|
||||||
|
layer.vars.insert(k, v.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
layers.push(layer);
|
||||||
|
}
|
||||||
|
layers.push(Layer::new(Scope::Collection, "knock.yaml", c.manifest.vars.clone()));
|
||||||
|
layers.push(Layer::new(Scope::Global, "global", input.globals));
|
||||||
|
|
||||||
|
let mut resolver = Resolver::new(layers, input.secrets);
|
||||||
|
if let Some(o) = input.oauth {
|
||||||
|
resolver = resolver.with_oauth(o);
|
||||||
|
}
|
||||||
|
|
||||||
|
let auth = effective_auth(c, input.request_id, &input.request.auth, &ancestors);
|
||||||
|
let mut inherited_headers = c.manifest.headers.clone();
|
||||||
|
for (_, meta) in &ancestors {
|
||||||
|
inherited_headers.extend(meta.headers.iter().cloned());
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
resolver,
|
||||||
|
auth,
|
||||||
|
inherited_headers,
|
||||||
|
root: c.root.clone(),
|
||||||
|
collection_settings: c.manifest.settings.clone(),
|
||||||
|
collection_id: c.manifest.id.clone(),
|
||||||
|
env: input.env.map(str::to_string),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A context for a request that is not part of a collection (CLI one-offs,
|
||||||
|
/// pasted cURL, history replays).
|
||||||
|
pub fn standalone(request: &Request, root: PathBuf) -> Self {
|
||||||
|
Self {
|
||||||
|
resolver: Resolver::new(
|
||||||
|
vec![Layer::new(Scope::Request, "request", request.vars.clone())],
|
||||||
|
Arc::new(crate::vars::NoSecrets),
|
||||||
|
),
|
||||||
|
auth: EffectiveAuth {
|
||||||
|
auth: match &request.auth {
|
||||||
|
Auth::Inherit => Auth::None,
|
||||||
|
a => a.clone(),
|
||||||
|
},
|
||||||
|
origin: AuthOrigin::Request,
|
||||||
|
source: "request".into(),
|
||||||
|
},
|
||||||
|
inherited_headers: Vec::new(),
|
||||||
|
root,
|
||||||
|
collection_settings: CollectionSettings::default(),
|
||||||
|
collection_id: String::new(),
|
||||||
|
env: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn effective_auth(
|
||||||
|
c: &Collection,
|
||||||
|
request_id: &str,
|
||||||
|
own: &Auth,
|
||||||
|
ancestors: &[(String, FolderMeta)],
|
||||||
|
) -> EffectiveAuth {
|
||||||
|
if !own.is_inherit() {
|
||||||
|
return EffectiveAuth {
|
||||||
|
auth: own.clone(),
|
||||||
|
origin: AuthOrigin::Request,
|
||||||
|
source: request_id.to_string(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for (id, meta) in ancestors.iter().rev() {
|
||||||
|
if !meta.auth.is_inherit() {
|
||||||
|
return EffectiveAuth {
|
||||||
|
auth: meta.auth.clone(),
|
||||||
|
origin: AuthOrigin::Folder,
|
||||||
|
source: id.clone(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EffectiveAuth {
|
||||||
|
auth: match &c.manifest.auth {
|
||||||
|
Auth::Inherit => Auth::None,
|
||||||
|
a => a.clone(),
|
||||||
|
},
|
||||||
|
origin: AuthOrigin::Collection,
|
||||||
|
source: "knock.yaml".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- prepared
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Prepared {
|
||||||
|
pub method: String,
|
||||||
|
pub url: String,
|
||||||
|
pub headers: Vec<(String, String)>,
|
||||||
|
pub body: PreparedBody,
|
||||||
|
pub settings: RequestSettings,
|
||||||
|
/// Variables referenced but not defined anywhere.
|
||||||
|
pub missing: Vec<String>,
|
||||||
|
pub cycles: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||||
|
pub enum PreparedBody {
|
||||||
|
None,
|
||||||
|
Bytes {
|
||||||
|
#[serde(skip)]
|
||||||
|
data: Vec<u8>,
|
||||||
|
preview: String,
|
||||||
|
},
|
||||||
|
Multipart { parts: Vec<PreparedPart> },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct PreparedPart {
|
||||||
|
pub name: String,
|
||||||
|
pub value: Option<String>,
|
||||||
|
pub file: Option<PathBuf>,
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Prepared {
|
||||||
|
pub fn header(&self, name: &str) -> Option<&str> {
|
||||||
|
self.headers
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find(|(k, _)| k.eq_ignore_ascii_case(name))
|
||||||
|
.map(|(_, v)| v.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_header(&mut self, name: &str, value: impl Into<String>) {
|
||||||
|
self.headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
|
||||||
|
self.headers.push((name.to_string(), value.into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn body_bytes(&self) -> &[u8] {
|
||||||
|
match &self.body {
|
||||||
|
PreparedBody::Bytes { data, .. } => data,
|
||||||
|
_ => &[],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_query(&mut self, name: &str, value: &str) -> Result<()> {
|
||||||
|
let mut u = url::Url::parse(&self.url)?;
|
||||||
|
u.query_pairs_mut().append_pair(name, value);
|
||||||
|
self.url = u.to_string();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prepare(req: &Request, ctx: &RequestContext) -> Result<Prepared> {
|
||||||
|
let r = &ctx.resolver;
|
||||||
|
let mut missing = Vec::new();
|
||||||
|
let mut cycles = Vec::new();
|
||||||
|
let mut res = |s: &str| {
|
||||||
|
let x = r.resolve(s);
|
||||||
|
missing.extend(x.missing);
|
||||||
|
cycles.extend(x.cycles);
|
||||||
|
x.value
|
||||||
|
};
|
||||||
|
|
||||||
|
let method = res(req.method()).trim().to_uppercase();
|
||||||
|
if method.is_empty() {
|
||||||
|
bail!("method is empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut url = res(req.url.trim());
|
||||||
|
let path_params: IndexMap<String, String> =
|
||||||
|
req.params.path.iter().map(|(k, v)| (k.clone(), res(v))).collect();
|
||||||
|
url = substitute_path_params(&url, &path_params);
|
||||||
|
if !url.contains("://") {
|
||||||
|
url = format!("http://{url}");
|
||||||
|
}
|
||||||
|
let parsed = url::Url::parse(&url).with_context(|| format!("invalid URL '{url}'"))?;
|
||||||
|
url = parsed.to_string();
|
||||||
|
|
||||||
|
// Inherited headers: a deeper level replaces a shallower one by name.
|
||||||
|
// Request headers then replace inherited ones by name, but several request
|
||||||
|
// headers with the same name are all sent.
|
||||||
|
let mut headers: Vec<(String, String)> = Vec::new();
|
||||||
|
for h in ctx.inherited_headers.iter().filter(|h| h.enabled && !h.name.trim().is_empty()) {
|
||||||
|
let name = res(h.name.trim());
|
||||||
|
let value = res(&h.value);
|
||||||
|
headers.retain(|(k, _)| !k.eq_ignore_ascii_case(&name));
|
||||||
|
headers.push((name, value));
|
||||||
|
}
|
||||||
|
let own: Vec<(String, String)> = req
|
||||||
|
.headers
|
||||||
|
.iter()
|
||||||
|
.filter(|h| h.enabled && !h.name.trim().is_empty())
|
||||||
|
.map(|h| (res(h.name.trim()), res(&h.value)))
|
||||||
|
.collect();
|
||||||
|
headers.retain(|(k, _)| !own.iter().any(|(n, _)| n.eq_ignore_ascii_case(k)));
|
||||||
|
headers.extend(own);
|
||||||
|
|
||||||
|
let has = |hs: &Vec<(String, String)>, n: &str| hs.iter().any(|(k, _)| k.eq_ignore_ascii_case(n));
|
||||||
|
let body = match req.kind {
|
||||||
|
RequestKind::Graphql => {
|
||||||
|
let g = req.graphql.clone().unwrap_or_default();
|
||||||
|
let vars_text = res(&g.variables);
|
||||||
|
let variables: serde_json::Value = if vars_text.trim().is_empty() {
|
||||||
|
serde_json::Value::Null
|
||||||
|
} else {
|
||||||
|
serde_json::from_str(&strip_json_comments(&vars_text))
|
||||||
|
.context("GraphQL variables are not valid JSON")?
|
||||||
|
};
|
||||||
|
let mut payload = serde_json::json!({ "query": res(&g.query) });
|
||||||
|
if !variables.is_null() {
|
||||||
|
payload["variables"] = variables;
|
||||||
|
}
|
||||||
|
if let Some(op) = g.operation_name.filter(|s| !s.is_empty()) {
|
||||||
|
payload["operationName"] = serde_json::Value::String(op);
|
||||||
|
}
|
||||||
|
if !has(&headers, "content-type") {
|
||||||
|
headers.push(("Content-Type".into(), "application/json".into()));
|
||||||
|
}
|
||||||
|
bytes_body(serde_json::to_vec(&payload)?)
|
||||||
|
}
|
||||||
|
_ => match req.body.kind {
|
||||||
|
BodyType::None => PreparedBody::None,
|
||||||
|
BodyType::Json => {
|
||||||
|
let mut text = res(&req.body.content);
|
||||||
|
if req.body.jsonc {
|
||||||
|
text = strip_json_comments(&text);
|
||||||
|
}
|
||||||
|
if !has(&headers, "content-type") {
|
||||||
|
headers.push(("Content-Type".into(), "application/json".into()));
|
||||||
|
}
|
||||||
|
bytes_body(text.into_bytes())
|
||||||
|
}
|
||||||
|
BodyType::Raw => {
|
||||||
|
if !has(&headers, "content-type") {
|
||||||
|
let ct = req.body.content_type.clone().unwrap_or_else(|| "text/plain".into());
|
||||||
|
headers.push(("Content-Type".into(), ct));
|
||||||
|
}
|
||||||
|
bytes_body(res(&req.body.content).into_bytes())
|
||||||
|
}
|
||||||
|
BodyType::FormUrlencoded => {
|
||||||
|
let mut ser = url::form_urlencoded::Serializer::new(String::new());
|
||||||
|
for f in req.body.form.iter().filter(|f| f.enabled && !f.name.is_empty()) {
|
||||||
|
ser.append_pair(&res(&f.name), &res(&f.value));
|
||||||
|
}
|
||||||
|
if !has(&headers, "content-type") {
|
||||||
|
headers.push((
|
||||||
|
"Content-Type".into(),
|
||||||
|
"application/x-www-form-urlencoded".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
bytes_body(ser.finish().into_bytes())
|
||||||
|
}
|
||||||
|
BodyType::Multipart => {
|
||||||
|
// Content-Type with boundary is set by the HTTP client.
|
||||||
|
headers.retain(|(k, _)| !k.eq_ignore_ascii_case("content-type"));
|
||||||
|
PreparedBody::Multipart {
|
||||||
|
parts: req
|
||||||
|
.body
|
||||||
|
.multipart
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.enabled && !p.name.is_empty())
|
||||||
|
.map(|p| PreparedPart {
|
||||||
|
name: res(&p.name),
|
||||||
|
value: p.file.is_none().then(|| res(&p.value)),
|
||||||
|
file: p.file.as_ref().map(|f| ctx.root.join(res(f))),
|
||||||
|
content_type: p.content_type.clone(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BodyType::Binary => {
|
||||||
|
let Some(f) = &req.body.file else { bail!("binary body has no file selected") };
|
||||||
|
let path = ctx.root.join(res(f));
|
||||||
|
let data = std::fs::read(&path)
|
||||||
|
.with_context(|| format!("reading body file {}", path.display()))?;
|
||||||
|
if !has(&headers, "content-type") {
|
||||||
|
headers.push(("Content-Type".into(), "application/octet-stream".into()));
|
||||||
|
}
|
||||||
|
PreparedBody::Bytes {
|
||||||
|
preview: format!("<{} bytes from {}>", data.len(), path.display()),
|
||||||
|
data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
missing.sort();
|
||||||
|
missing.dedup();
|
||||||
|
Ok(Prepared {
|
||||||
|
method,
|
||||||
|
url,
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
|
settings: req.settings.clone(),
|
||||||
|
missing,
|
||||||
|
cycles,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bytes_body(data: Vec<u8>) -> PreparedBody {
|
||||||
|
let preview = match std::str::from_utf8(&data) {
|
||||||
|
Ok(s) if s.len() <= 64 * 1024 => s.to_string(),
|
||||||
|
Ok(s) => format!("{}…", &s[..s.floor_char_boundary_compat(64 * 1024)]),
|
||||||
|
Err(_) => format!("<{} bytes binary>", data.len()),
|
||||||
|
};
|
||||||
|
PreparedBody::Bytes { data, preview }
|
||||||
|
}
|
||||||
|
|
||||||
|
trait FloorBoundary {
|
||||||
|
fn floor_char_boundary_compat(&self, i: usize) -> usize;
|
||||||
|
}
|
||||||
|
impl FloorBoundary for str {
|
||||||
|
fn floor_char_boundary_compat(&self, mut i: usize) -> usize {
|
||||||
|
while i > 0 && !self.is_char_boundary(i) {
|
||||||
|
i -= 1;
|
||||||
|
}
|
||||||
|
i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces `:name` path segments. Ports (`host:8080`) are left alone because
|
||||||
|
/// only segments after the authority are considered.
|
||||||
|
pub fn substitute_path_params(url: &str, params: &IndexMap<String, String>) -> String {
|
||||||
|
if params.is_empty() {
|
||||||
|
return url.to_string();
|
||||||
|
}
|
||||||
|
let path_start = url
|
||||||
|
.find("://")
|
||||||
|
.map(|i| i + 3)
|
||||||
|
.and_then(|i| url[i..].find('/').map(|j| i + j))
|
||||||
|
.unwrap_or(url.len());
|
||||||
|
let (head, tail) = url.split_at(path_start);
|
||||||
|
let (path, rest) = match tail.find(['?', '#']) {
|
||||||
|
Some(i) => tail.split_at(i),
|
||||||
|
None => (tail, ""),
|
||||||
|
};
|
||||||
|
let path = path
|
||||||
|
.split('/')
|
||||||
|
.map(|seg| match seg.strip_prefix(':') {
|
||||||
|
Some(name) if params.contains_key(name) => {
|
||||||
|
percent_encoding::utf8_percent_encode(¶ms[name], SEGMENT).to_string()
|
||||||
|
}
|
||||||
|
_ => seg.to_string(),
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("/");
|
||||||
|
format!("{head}{path}{rest}")
|
||||||
|
}
|
||||||
|
|
||||||
|
const SEGMENT: &percent_encoding::AsciiSet = &percent_encoding::CONTROLS
|
||||||
|
.add(b' ')
|
||||||
|
.add(b'"')
|
||||||
|
.add(b'#')
|
||||||
|
.add(b'<')
|
||||||
|
.add(b'>')
|
||||||
|
.add(b'?')
|
||||||
|
.add(b'`')
|
||||||
|
.add(b'{')
|
||||||
|
.add(b'}')
|
||||||
|
.add(b'/')
|
||||||
|
.add(b'%');
|
||||||
|
|
||||||
|
/// Path parameter names (`:id`) found in a URL, in order.
|
||||||
|
pub fn path_param_names(url: &str) -> Vec<String> {
|
||||||
|
let start = url
|
||||||
|
.find("://")
|
||||||
|
.map(|i| i + 3)
|
||||||
|
.and_then(|i| url[i..].find('/').map(|j| i + j))
|
||||||
|
.unwrap_or(0);
|
||||||
|
let path = &url[start..];
|
||||||
|
let path = &path[..path.find(['?', '#']).unwrap_or(path.len())];
|
||||||
|
path.split('/')
|
||||||
|
.filter_map(|s| s.strip_prefix(':'))
|
||||||
|
.filter(|s| !s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-'))
|
||||||
|
.map(str::to_string)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes `//` and `/* */` comments outside strings, plus trailing commas.
|
||||||
|
pub fn strip_json_comments(src: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(src.len());
|
||||||
|
let b: Vec<char> = src.chars().collect();
|
||||||
|
let mut i = 0;
|
||||||
|
let mut in_str = false;
|
||||||
|
while i < b.len() {
|
||||||
|
let c = b[i];
|
||||||
|
if in_str {
|
||||||
|
out.push(c);
|
||||||
|
if c == '\\' && i + 1 < b.len() {
|
||||||
|
out.push(b[i + 1]);
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if c == '"' {
|
||||||
|
in_str = false;
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match c {
|
||||||
|
'"' => {
|
||||||
|
in_str = true;
|
||||||
|
out.push(c);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
'/' if b.get(i + 1) == Some(&'/') => {
|
||||||
|
while i < b.len() && b[i] != '\n' {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
'/' if b.get(i + 1) == Some(&'*') => {
|
||||||
|
i += 2;
|
||||||
|
while i + 1 < b.len() && !(b[i] == '*' && b[i + 1] == '/') {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
i += 2;
|
||||||
|
}
|
||||||
|
',' => {
|
||||||
|
let mut j = i + 1;
|
||||||
|
while j < b.len() && b[j].is_whitespace() {
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
// Keep the comma unless the next real token closes a container.
|
||||||
|
let mut k = j;
|
||||||
|
loop {
|
||||||
|
if b.get(k) == Some(&'/') && b.get(k + 1) == Some(&'/') {
|
||||||
|
while k < b.len() && b[k] != '\n' {
|
||||||
|
k += 1;
|
||||||
|
}
|
||||||
|
} else if b.get(k) == Some(&'/') && b.get(k + 1) == Some(&'*') {
|
||||||
|
k += 2;
|
||||||
|
while k + 1 < b.len() && !(b[k] == '*' && b[k + 1] == '/') {
|
||||||
|
k += 1;
|
||||||
|
}
|
||||||
|
k += 2;
|
||||||
|
} else if b.get(k).is_some_and(|c| c.is_whitespace()) {
|
||||||
|
k += 1;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !matches!(b.get(k), Some('}') | Some(']')) {
|
||||||
|
out.push(',');
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
out.push(c);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn path_params() {
|
||||||
|
let mut p = IndexMap::new();
|
||||||
|
p.insert("id".to_string(), "a b".to_string());
|
||||||
|
assert_eq!(
|
||||||
|
substitute_path_params("http://h:8080/users/:id/x?q=:id", &p),
|
||||||
|
"http://h:8080/users/a%20b/x?q=:id"
|
||||||
|
);
|
||||||
|
assert_eq!(path_param_names("http://h:8080/u/:id/:other?x=:no"), vec!["id", "other"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn jsonc() {
|
||||||
|
let s = "{\n // c\n \"a\": \"http://x\", /* b */\n \"b\": [1,2,],\n}";
|
||||||
|
let v: serde_json::Value = serde_json::from_str(&strip_json_comments(s)).unwrap();
|
||||||
|
assert_eq!(v["a"], "http://x");
|
||||||
|
assert_eq!(v["b"][1], 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn header_override() {
|
||||||
|
let req = Request {
|
||||||
|
url: "http://x/".into(),
|
||||||
|
headers: vec![KeyValue::new("Accept", "text/plain"), KeyValue::new("X-A", "1"), KeyValue::new("X-A", "2")],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut ctx = RequestContext::standalone(&req, PathBuf::from("/tmp"));
|
||||||
|
ctx.inherited_headers = vec![KeyValue::new("accept", "application/json"), KeyValue::new("X-Team", "core")];
|
||||||
|
let p = prepare(&req, &ctx).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
p.headers,
|
||||||
|
vec![
|
||||||
|
("X-Team".to_string(), "core".to_string()),
|
||||||
|
("Accept".to_string(), "text/plain".to_string()),
|
||||||
|
("X-A".to_string(), "1".to_string()),
|
||||||
|
("X-A".to_string(), "2".to_string()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
//! One request, start to finish: resolve, authenticate, send, check. The GUI,
|
||||||
|
//! the runner and the CLI all go through [`execute`].
|
||||||
|
|
||||||
|
use crate::auth::{self, AuthDebug, AuthHost};
|
||||||
|
use crate::checks::{run_asserts, run_extracts, AssertResult, Extracted};
|
||||||
|
use crate::http::{Engine, Response, TransportOptions};
|
||||||
|
use crate::model::*;
|
||||||
|
use crate::prepare::{prepare, Prepared, PreparedBody, RequestContext};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct SentRequest {
|
||||||
|
pub method: String,
|
||||||
|
pub url: String,
|
||||||
|
pub headers: Vec<(String, String)>,
|
||||||
|
pub body: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct RunOutput {
|
||||||
|
pub request: Option<SentRequest>,
|
||||||
|
pub response: Option<Response>,
|
||||||
|
pub auth: AuthDebug,
|
||||||
|
pub asserts: Vec<AssertResult>,
|
||||||
|
pub extracted: Vec<Extracted>,
|
||||||
|
pub error: Option<String>,
|
||||||
|
pub missing: Vec<String>,
|
||||||
|
/// The request was sent a second time after refreshing an expired token.
|
||||||
|
pub retried: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RunOutput {
|
||||||
|
pub fn passed(&self) -> bool {
|
||||||
|
self.error.is_none() && self.asserts.iter().all(|a| a.passed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn transport_for(ctx: &RequestContext, url: &str) -> TransportOptions {
|
||||||
|
let s = &ctx.collection_settings;
|
||||||
|
let r = &ctx.resolver;
|
||||||
|
let mut t = TransportOptions::default();
|
||||||
|
if let Some(p) = &s.proxy {
|
||||||
|
t.proxy_mode = p.mode;
|
||||||
|
t.proxy_url = p.url.as_ref().map(|u| r.apply(u));
|
||||||
|
t.no_proxy = p.no_proxy.as_ref().map(|u| r.apply(u));
|
||||||
|
}
|
||||||
|
t.ca_bundle = s.ca_bundle.as_ref().map(|p| ctx.root.join(r.apply(p)));
|
||||||
|
if let Ok(u) = url::Url::parse(url) {
|
||||||
|
let host = u.host_str().unwrap_or_default();
|
||||||
|
let with_port = format!("{host}:{}", u.port_or_known_default().unwrap_or(0));
|
||||||
|
if let Some(c) = s.client_certs.iter().find(|c| c.host == host || c.host == with_port) {
|
||||||
|
let mut pem = Vec::new();
|
||||||
|
for f in [&c.cert, &c.key].into_iter().flatten() {
|
||||||
|
if let Ok(b) = std::fs::read(ctx.root.join(r.apply(f))) {
|
||||||
|
pem.extend(b);
|
||||||
|
pem.push(b'\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !pem.is_empty() {
|
||||||
|
t.identity_pem = Some(pem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sent(p: &Prepared) -> SentRequest {
|
||||||
|
SentRequest {
|
||||||
|
method: p.method.clone(),
|
||||||
|
url: p.url.clone(),
|
||||||
|
headers: p.headers.clone(),
|
||||||
|
body: match &p.body {
|
||||||
|
PreparedBody::None => String::new(),
|
||||||
|
PreparedBody::Bytes { preview, .. } => preview.clone(),
|
||||||
|
PreparedBody::Multipart { parts } => parts
|
||||||
|
.iter()
|
||||||
|
.map(|x| match &x.file {
|
||||||
|
Some(f) => format!("{}=@{}", x.name, f.display()),
|
||||||
|
None => format!("{}={}", x.name, x.value.clone().unwrap_or_default()),
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute(
|
||||||
|
engine: &Engine,
|
||||||
|
req: &Request,
|
||||||
|
ctx: &RequestContext,
|
||||||
|
host: Option<&dyn AuthHost>,
|
||||||
|
) -> RunOutput {
|
||||||
|
let mut out = RunOutput {
|
||||||
|
request: None,
|
||||||
|
response: None,
|
||||||
|
auth: AuthDebug::default(),
|
||||||
|
asserts: Vec::new(),
|
||||||
|
extracted: Vec::new(),
|
||||||
|
error: None,
|
||||||
|
missing: Vec::new(),
|
||||||
|
retried: false,
|
||||||
|
};
|
||||||
|
let base = match prepare(req, ctx) {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(e) => {
|
||||||
|
out.error = Some(format!("{e:#}"));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
out.missing = base.missing.clone();
|
||||||
|
|
||||||
|
let is_oauth = matches!(&ctx.auth.auth, Auth::Config(c) if c.kind == "oauth2" || c.kind == "oidc");
|
||||||
|
let mut force_refresh = false;
|
||||||
|
loop {
|
||||||
|
let mut p = base.clone();
|
||||||
|
out.auth = auth::apply(&ctx.auth, &mut p, &ctx.resolver, host, force_refresh).await;
|
||||||
|
out.request = Some(sent(&p));
|
||||||
|
if out.auth.failed() {
|
||||||
|
out.error = Some("authentication failed, see the Auth tab".into());
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
let transport = transport_for(ctx, &p.url);
|
||||||
|
let jar = (ctx.collection_settings.cookies && !ctx.collection_id.is_empty())
|
||||||
|
.then_some(ctx.collection_id.as_str());
|
||||||
|
match engine.send(&p, &transport, jar).await {
|
||||||
|
Ok(resp) => {
|
||||||
|
if resp.status == 401 && is_oauth && !force_refresh && req.settings.retry_on_401 {
|
||||||
|
force_refresh = true;
|
||||||
|
out.retried = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.asserts = run_asserts(&req.assert, &resp);
|
||||||
|
out.extracted = run_extracts(&req.extract, &resp);
|
||||||
|
out.response = Some(resp);
|
||||||
|
}
|
||||||
|
Err(e) => out.error = Some(format!("{e:#}")),
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
//! Secret values live in the OS keyring (Secret Service / KWallet on Linux)
|
||||||
|
//! or in a gitignored `<env>.secrets.yaml`. For CI, `KNOCK_SECRET_<NAME>`
|
||||||
|
//! environment variables win over both.
|
||||||
|
|
||||||
|
use crate::vars::SecretLookup;
|
||||||
|
use anyhow::Result;
|
||||||
|
use indexmap::IndexMap;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
pub const SERVICE: &str = "knock";
|
||||||
|
|
||||||
|
fn account(collection: &str, env: Option<&str>, name: &str) -> String {
|
||||||
|
format!("{collection}:{}:{name}", env.unwrap_or(""))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn env_var_name(name: &str) -> String {
|
||||||
|
let mut s = String::from("KNOCK_SECRET_");
|
||||||
|
for c in name.chars() {
|
||||||
|
s.push(if c.is_ascii_alphanumeric() { c.to_ascii_uppercase() } else { '_' });
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn keyring_get(collection: &str, env: Option<&str>, name: &str) -> Option<String> {
|
||||||
|
keyring::Entry::new(SERVICE, &account(collection, env, name))
|
||||||
|
.ok()?
|
||||||
|
.get_password()
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn keyring_set(collection: &str, env: Option<&str>, name: &str, value: &str) -> Result<()> {
|
||||||
|
keyring::Entry::new(SERVICE, &account(collection, env, name))?.set_password(value)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn keyring_delete(collection: &str, env: Option<&str>, name: &str) -> Result<()> {
|
||||||
|
match keyring::Entry::new(SERVICE, &account(collection, env, name))?.delete_credential() {
|
||||||
|
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||||
|
Err(e) => Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generic keyring slot for things that are not variables (tokens, passphrases).
|
||||||
|
pub fn slot_get(key: &str) -> Option<String> {
|
||||||
|
keyring::Entry::new(SERVICE, key).ok()?.get_password().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn slot_set(key: &str, value: &str) -> Result<()> {
|
||||||
|
keyring::Entry::new(SERVICE, key)?.set_password(value)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn slot_delete(key: &str) -> Result<()> {
|
||||||
|
match keyring::Entry::new(SERVICE, key)?.delete_credential() {
|
||||||
|
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||||
|
Err(e) => Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a secret value was found, for the UI.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum SecretSource {
|
||||||
|
EnvVar,
|
||||||
|
Keyring,
|
||||||
|
File,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SecretStore {
|
||||||
|
pub collection: String,
|
||||||
|
pub env: Option<String>,
|
||||||
|
pub file: IndexMap<String, String>,
|
||||||
|
pub use_keyring: bool,
|
||||||
|
cache: Mutex<HashMap<String, Option<(String, SecretSource)>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SecretStore {
|
||||||
|
pub fn new(collection: &str, env: Option<&str>, file: IndexMap<String, String>, use_keyring: bool) -> Self {
|
||||||
|
Self {
|
||||||
|
collection: collection.to_string(),
|
||||||
|
env: env.map(str::to_string),
|
||||||
|
file,
|
||||||
|
use_keyring,
|
||||||
|
cache: Mutex::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find(&self, name: &str) -> Option<(String, SecretSource)> {
|
||||||
|
if let Some(hit) = self.cache.lock().unwrap().get(name) {
|
||||||
|
return hit.clone();
|
||||||
|
}
|
||||||
|
let found = std::env::var(env_var_name(name))
|
||||||
|
.ok()
|
||||||
|
.map(|v| (v, SecretSource::EnvVar))
|
||||||
|
.or_else(|| {
|
||||||
|
if !self.use_keyring {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
keyring_get(&self.collection, self.env.as_deref(), name)
|
||||||
|
.or_else(|| keyring_get(&self.collection, None, name))
|
||||||
|
.map(|v| (v, SecretSource::Keyring))
|
||||||
|
})
|
||||||
|
.or_else(|| self.file.get(name).cloned().map(|v| (v, SecretSource::File)));
|
||||||
|
self.cache.lock().unwrap().insert(name.to_string(), found.clone());
|
||||||
|
found
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SecretLookup for SecretStore {
|
||||||
|
fn secret(&self, name: &str) -> Option<String> {
|
||||||
|
self.find(name).map(|(v, _)| v)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,437 @@
|
|||||||
|
//! `{{name}}` resolution. Layers are searched narrowest first; the first hit
|
||||||
|
//! wins. Values may contain variables themselves; cycles are reported.
|
||||||
|
|
||||||
|
use base64::Engine;
|
||||||
|
use indexmap::IndexMap;
|
||||||
|
use serde::Serialize;
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Scope {
|
||||||
|
Runtime,
|
||||||
|
Request,
|
||||||
|
Folder,
|
||||||
|
Environment,
|
||||||
|
Collection,
|
||||||
|
Global,
|
||||||
|
Secret,
|
||||||
|
Dynamic,
|
||||||
|
Oauth,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Layer {
|
||||||
|
pub scope: Scope,
|
||||||
|
/// Where the value comes from, e.g. `users/folder.yaml` or `prod`.
|
||||||
|
pub source: String,
|
||||||
|
pub vars: IndexMap<String, String>,
|
||||||
|
/// Names in this layer whose values must be masked.
|
||||||
|
pub secret: HashSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Layer {
|
||||||
|
pub fn new(scope: Scope, source: impl Into<String>, vars: IndexMap<String, String>) -> Self {
|
||||||
|
Self {
|
||||||
|
scope,
|
||||||
|
source: source.into(),
|
||||||
|
vars,
|
||||||
|
secret: HashSet::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks up `{{secret.x}}` and variables flagged `secret` in an environment.
|
||||||
|
pub trait SecretLookup: Send + Sync {
|
||||||
|
fn secret(&self, name: &str) -> Option<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answers `{{oauth.<name>.<field>}}` from the token store.
|
||||||
|
pub trait OauthLookup: Send + Sync {
|
||||||
|
fn oauth_value(&self, config: &str, field: &str) -> Option<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct NoSecrets;
|
||||||
|
impl SecretLookup for NoSecrets {
|
||||||
|
fn secret(&self, _: &str) -> Option<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct VarInfo {
|
||||||
|
pub name: String,
|
||||||
|
pub value: Option<String>,
|
||||||
|
pub scope: Option<Scope>,
|
||||||
|
pub source: Option<String>,
|
||||||
|
pub secret: bool,
|
||||||
|
/// Set when the value could not be fully resolved (cycle or missing inner var).
|
||||||
|
pub problem: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize)]
|
||||||
|
pub struct Resolution {
|
||||||
|
pub value: String,
|
||||||
|
pub missing: Vec<String>,
|
||||||
|
pub cycles: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Resolver {
|
||||||
|
pub layers: Vec<Layer>,
|
||||||
|
secrets: Arc<dyn SecretLookup>,
|
||||||
|
oauth: Option<Arc<dyn OauthLookup>>,
|
||||||
|
/// Secret values seen while resolving, so output can be masked.
|
||||||
|
seen_secrets: Arc<std::sync::Mutex<HashSet<String>>>,
|
||||||
|
/// Dynamic values are fixed per resolver, so `{{$uuid}}` twice in one
|
||||||
|
/// request gives the same value in URL and body.
|
||||||
|
dynamic_cache: Arc<std::sync::Mutex<HashMap<String, String>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Resolver {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Resolver").field("layers", &self.layers).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Resolver {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new(Vec::new(), Arc::new(NoSecrets))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_DEPTH: usize = 16;
|
||||||
|
pub const MASK: &str = "••••••";
|
||||||
|
|
||||||
|
impl Resolver {
|
||||||
|
pub fn new(layers: Vec<Layer>, secrets: Arc<dyn SecretLookup>) -> Self {
|
||||||
|
Self {
|
||||||
|
layers,
|
||||||
|
secrets,
|
||||||
|
oauth: None,
|
||||||
|
seen_secrets: Default::default(),
|
||||||
|
dynamic_cache: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_oauth(mut self, o: Arc<dyn OauthLookup>) -> Self {
|
||||||
|
self.oauth = Some(o);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a layer that wins over everything else (runtime values).
|
||||||
|
pub fn push_front(&mut self, layer: Layer) {
|
||||||
|
self.layers.insert(0, layer);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolve(&self, text: &str) -> Resolution {
|
||||||
|
let mut res = Resolution::default();
|
||||||
|
let mut stack = Vec::new();
|
||||||
|
res.value = self.expand(text, &mut stack, &mut res.missing, &mut res.cycles);
|
||||||
|
res.missing.dedup();
|
||||||
|
res.cycles.dedup();
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves and drops the diagnostics. Missing variables stay as `{{name}}`.
|
||||||
|
pub fn apply(&self, text: &str) -> String {
|
||||||
|
if !text.contains("{{") {
|
||||||
|
return text.to_string();
|
||||||
|
}
|
||||||
|
self.resolve(text).value
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn info(&self, name: &str) -> VarInfo {
|
||||||
|
let mut missing = Vec::new();
|
||||||
|
let mut cycles = Vec::new();
|
||||||
|
let mut stack = Vec::new();
|
||||||
|
let found = self.lookup_raw(name);
|
||||||
|
let (value, scope, source, secret) = match found {
|
||||||
|
Some(l) => (Some(l.0), Some(l.1), Some(l.2), l.3),
|
||||||
|
None => (None, None, None, false),
|
||||||
|
};
|
||||||
|
let value = value.map(|v| self.expand(&v, &mut stack, &mut missing, &mut cycles));
|
||||||
|
let problem = if !cycles.is_empty() {
|
||||||
|
Some(format!("cycle: {}", cycles.join(", ")))
|
||||||
|
} else if !missing.is_empty() {
|
||||||
|
Some(format!("undefined: {}", missing.join(", ")))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
VarInfo {
|
||||||
|
name: name.to_string(),
|
||||||
|
value,
|
||||||
|
scope,
|
||||||
|
source,
|
||||||
|
secret,
|
||||||
|
problem,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every variable name visible to this resolver, for autocomplete.
|
||||||
|
pub fn names(&self) -> Vec<VarInfo> {
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for l in &self.layers {
|
||||||
|
for k in l.vars.keys() {
|
||||||
|
if seen.insert(k.clone()) {
|
||||||
|
out.push(self.info(k));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces every secret value seen so far with a mask.
|
||||||
|
pub fn mask(&self, text: &str) -> String {
|
||||||
|
let seen = self.seen_secrets.lock().unwrap();
|
||||||
|
let mut out = text.to_string();
|
||||||
|
let mut vals: Vec<&String> = seen.iter().filter(|s| s.len() >= 3).collect();
|
||||||
|
vals.sort_by_key(|s| std::cmp::Reverse(s.len()));
|
||||||
|
for v in vals {
|
||||||
|
out = out.replace(v.as_str(), MASK);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn secret_values(&self) -> Vec<String> {
|
||||||
|
self.seen_secrets.lock().unwrap().iter().cloned().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn note_secret(&self, value: &str) {
|
||||||
|
if !value.is_empty() {
|
||||||
|
self.seen_secrets.lock().unwrap().insert(value.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lookup_raw(&self, name: &str) -> Option<(String, Scope, String, bool)> {
|
||||||
|
if let Some(rest) = name.strip_prefix("secret.") {
|
||||||
|
return self
|
||||||
|
.secrets
|
||||||
|
.secret(rest)
|
||||||
|
.map(|v| (v, Scope::Secret, "keyring".to_string(), true));
|
||||||
|
}
|
||||||
|
if let Some(rest) = name.strip_prefix("oauth.") {
|
||||||
|
if let (Some(o), Some((cfg, field))) = (&self.oauth, rest.split_once('.')) {
|
||||||
|
return o
|
||||||
|
.oauth_value(cfg, field)
|
||||||
|
.map(|v| (v, Scope::Oauth, format!("oauth {cfg}"), true));
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
for l in &self.layers {
|
||||||
|
if let Some(v) = l.vars.get(name) {
|
||||||
|
if l.secret.contains(name) {
|
||||||
|
let v = if v.is_empty() {
|
||||||
|
self.secrets.secret(name).unwrap_or_default()
|
||||||
|
} else {
|
||||||
|
v.clone()
|
||||||
|
};
|
||||||
|
return Some((v, l.scope, l.source.clone(), true));
|
||||||
|
}
|
||||||
|
return Some((v.clone(), l.scope, l.source.clone(), false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expand(
|
||||||
|
&self,
|
||||||
|
text: &str,
|
||||||
|
stack: &mut Vec<String>,
|
||||||
|
missing: &mut Vec<String>,
|
||||||
|
cycles: &mut Vec<String>,
|
||||||
|
) -> String {
|
||||||
|
let mut out = String::with_capacity(text.len());
|
||||||
|
let mut rest = text;
|
||||||
|
while let Some(start) = rest.find("{{") {
|
||||||
|
out.push_str(&rest[..start]);
|
||||||
|
let after = &rest[start + 2..];
|
||||||
|
let Some(end) = find_close(after) else {
|
||||||
|
out.push_str(&rest[start..]);
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
let inner = after[..end].trim();
|
||||||
|
let raw = &rest[start..start + 2 + end + 2];
|
||||||
|
rest = &after[end + 2..];
|
||||||
|
|
||||||
|
if inner.is_empty() {
|
||||||
|
out.push_str(raw);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(v) = self.dynamic(inner, stack, missing, cycles) {
|
||||||
|
out.push_str(&v);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if stack.iter().any(|s| s == inner) || stack.len() >= MAX_DEPTH {
|
||||||
|
cycles.push(inner.to_string());
|
||||||
|
out.push_str(raw);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match self.lookup_raw(inner) {
|
||||||
|
Some((v, _, _, secret)) => {
|
||||||
|
stack.push(inner.to_string());
|
||||||
|
let expanded = if v.contains("{{") {
|
||||||
|
self.expand(&v, stack, missing, cycles)
|
||||||
|
} else {
|
||||||
|
v
|
||||||
|
};
|
||||||
|
stack.pop();
|
||||||
|
if secret {
|
||||||
|
self.note_secret(&expanded);
|
||||||
|
}
|
||||||
|
out.push_str(&expanded);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
missing.push(inner.to_string());
|
||||||
|
out.push_str(raw);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str(rest);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dynamic(
|
||||||
|
&self,
|
||||||
|
inner: &str,
|
||||||
|
stack: &mut Vec<String>,
|
||||||
|
missing: &mut Vec<String>,
|
||||||
|
cycles: &mut Vec<String>,
|
||||||
|
) -> Option<String> {
|
||||||
|
let name = inner.strip_prefix('$')?;
|
||||||
|
if let Some(arg) = name.strip_prefix("base64(").and_then(|s| s.strip_suffix(')')) {
|
||||||
|
let arg = self.expand(arg, stack, missing, cycles);
|
||||||
|
return Some(base64::engine::general_purpose::STANDARD.encode(arg));
|
||||||
|
}
|
||||||
|
let mut cache = self.dynamic_cache.lock().unwrap();
|
||||||
|
if let Some(v) = cache.get(name) {
|
||||||
|
return Some(v.clone());
|
||||||
|
}
|
||||||
|
let v = dynamic_value(name)?;
|
||||||
|
cache.insert(name.to_string(), v.clone());
|
||||||
|
Some(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const DYNAMIC_VARS: &[(&str, &str)] = &[
|
||||||
|
("$uuid", "Random UUID v4"),
|
||||||
|
("$timestamp", "Unix time in seconds"),
|
||||||
|
("$timestampMs", "Unix time in milliseconds"),
|
||||||
|
("$isoDate", "Current time, ISO 8601"),
|
||||||
|
("$randomInt", "Random integer 0..1000"),
|
||||||
|
("$randomEmail", "Random e-mail address"),
|
||||||
|
("$base64(...)", "Base64 of the argument"),
|
||||||
|
];
|
||||||
|
|
||||||
|
fn dynamic_value(name: &str) -> Option<String> {
|
||||||
|
use rand::Rng;
|
||||||
|
let now = chrono::Utc::now();
|
||||||
|
Some(match name {
|
||||||
|
"uuid" | "guid" => uuid::Uuid::new_v4().to_string(),
|
||||||
|
"timestamp" => now.timestamp().to_string(),
|
||||||
|
"timestampMs" => now.timestamp_millis().to_string(),
|
||||||
|
"isoDate" | "isoTimestamp" => now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
|
||||||
|
"randomInt" => rand::thread_rng().gen_range(0..1000).to_string(),
|
||||||
|
"randomEmail" => format!("user{}@example.com", rand::thread_rng().gen_range(1000..99999)),
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Index of the matching `}}` for text that starts right after `{{`.
|
||||||
|
fn find_close(s: &str) -> Option<usize> {
|
||||||
|
let b = s.as_bytes();
|
||||||
|
let mut depth = 0;
|
||||||
|
let mut i = 0;
|
||||||
|
while i + 1 < b.len() {
|
||||||
|
if b[i] == b'{' && b[i + 1] == b'{' {
|
||||||
|
depth += 1;
|
||||||
|
i += 2;
|
||||||
|
} else if b[i] == b'}' && b[i + 1] == b'}' {
|
||||||
|
if depth == 0 {
|
||||||
|
return Some(i);
|
||||||
|
}
|
||||||
|
depth -= 1;
|
||||||
|
i += 2;
|
||||||
|
} else {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every `{{name}}` reference in a text, top level only.
|
||||||
|
pub fn references(text: &str) -> Vec<String> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut rest = text;
|
||||||
|
while let Some(start) = rest.find("{{") {
|
||||||
|
let after = &rest[start + 2..];
|
||||||
|
let Some(end) = find_close(after) else { break };
|
||||||
|
out.push(after[..end].trim().to_string());
|
||||||
|
rest = &after[end + 2..];
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
struct S;
|
||||||
|
impl SecretLookup for S {
|
||||||
|
fn secret(&self, name: &str) -> Option<String> {
|
||||||
|
(name == "pw" || name == "token").then(|| format!("s3cret-{name}"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layer(scope: Scope, kv: &[(&str, &str)]) -> Layer {
|
||||||
|
Layer::new(
|
||||||
|
scope,
|
||||||
|
format!("{scope:?}"),
|
||||||
|
kv.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn narrow_scope_wins_and_nesting_works() {
|
||||||
|
let r = Resolver::new(
|
||||||
|
vec![
|
||||||
|
layer(Scope::Request, &[("v", "v2")]),
|
||||||
|
layer(Scope::Environment, &[("base", "https://api"), ("v", "v1"), ("url", "{{base}}/{{v}}")]),
|
||||||
|
],
|
||||||
|
Arc::new(S),
|
||||||
|
);
|
||||||
|
let res = r.resolve("{{url}}/users?x={{missing}}");
|
||||||
|
assert_eq!(res.value, "https://api/v2/users?x={{missing}}");
|
||||||
|
assert_eq!(res.missing, vec!["missing"]);
|
||||||
|
assert_eq!(r.info("v").scope, Some(Scope::Request));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cycles_are_reported() {
|
||||||
|
let r = Resolver::new(vec![layer(Scope::Environment, &[("a", "{{b}}"), ("b", "{{a}}")])], Arc::new(NoSecrets));
|
||||||
|
let res = r.resolve("{{a}}");
|
||||||
|
assert!(!res.cycles.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn secrets_and_masking() {
|
||||||
|
let mut env = layer(Scope::Environment, &[("token", "")]);
|
||||||
|
env.secret.insert("token".into());
|
||||||
|
let r = Resolver::new(vec![env], Arc::new(S));
|
||||||
|
assert_eq!(r.apply("Bearer {{token}} {{secret.pw}}"), "Bearer s3cret-token s3cret-pw");
|
||||||
|
assert_eq!(r.mask("x s3cret-token y s3cret-pw"), format!("x {MASK} y {MASK}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dynamic_and_base64() {
|
||||||
|
let r = Resolver::new(vec![layer(Scope::Environment, &[("u", "me")])], Arc::new(S));
|
||||||
|
let a = r.apply("{{$uuid}}");
|
||||||
|
assert_eq!(a.len(), 36);
|
||||||
|
assert_eq!(r.apply("{{$uuid}}"), a, "stable within one resolver");
|
||||||
|
assert_eq!(r.apply("{{$base64({{u}}:pw)}}"), "bWU6cHc=");
|
||||||
|
assert_eq!(references("a {{x}} b {{$base64({{y}})}}"), vec!["x", "$base64({{y}})"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en" class="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>knock</title>
|
||||||
|
<script>
|
||||||
|
try {
|
||||||
|
const m = localStorage.getItem('ck-theme') || 'dark';
|
||||||
|
if (!localStorage.getItem('ck-theme')) localStorage.setItem('ck-theme', 'dark');
|
||||||
|
const dark = m === 'dark' || (m === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
|
||||||
|
|
||||||
|
document.documentElement.classList.toggle('dark', dark);
|
||||||
|
} catch {}
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<rect width="512" height="512" rx="114" fill="#101318"/>
|
||||||
|
<g transform="translate(107 107) scale(2.98)" fill="none" stroke="#2EC4F1" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="50" cy="50" r="36" stroke-width="12"/>
|
||||||
|
<path d="M45 40 L55 50 L45 60" stroke-width="10"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 424 B |
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<rect width="16" height="16" rx="3.5" fill="#101318"/>
|
||||||
|
<g transform="translate(1.5 1.5) scale(0.13)" fill="none" stroke="#2EC4F1" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="50" cy="50" r="36" stroke-width="16"/>
|
||||||
|
<path d="M46 40 L55 50 L46 60" stroke-width="15"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 420 B |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="50" cy="50" r="36" stroke-width="12"/>
|
||||||
|
<path d="M45 40 L55 50 L45 60" stroke-width="10"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 327 B |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<g fill="none" stroke="#0B7FAD" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="50" cy="50" r="36" stroke-width="12"/>
|
||||||
|
<path d="M45 40 L55 50 L45 60" stroke-width="10"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 322 B |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<g fill="none" stroke="#2EC4F1" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="50" cy="50" r="36" stroke-width="12"/>
|
||||||
|
<path d="M45 40 L55 50 L45 60" stroke-width="10"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 322 B |
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="70 0 2678 714" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<path fill="currentColor" d="M70 700V0H196V387H214L378 204H542L313 444L550 700H388L214 503H196V700Z M589 700V204H713V269H731Q743 243 776 219.5Q809 196 876 196Q934 196 977.5 222.5Q1021 249 1045 295.5Q1069 342 1069 404V700H943V414Q943 358 915.5 330Q888 302 837 302Q779 302 747 340.5Q715 379 715 448V700Z M1960 714Q1888 714 1829.5 684Q1771 654 1737 597Q1703 540 1703 459V445Q1703 364 1737 307Q1771 250 1829.5 220Q1888 190 1960 190Q2031 190 2082 215Q2133 240 2164.5 283.5Q2196 327 2206 382L2084 408Q2080 378 2066 354Q2052 330 2026.5 316Q2001 302 1963 302Q1925 302 1894.5 318.5Q1864 335 1846.5 367.5Q1829 400 1829 447V457Q1829 504 1846.5 536.5Q1864 569 1894.5 585.5Q1925 602 1963 602Q2020 602 2049.5 572.5Q2079 543 2087 495L2209 524Q2196 577 2164.5 620.5Q2133 664 2082 689Q2031 714 1960 714Z M2268 700V0H2394V387H2412L2576 204H2740L2511 444L2748 700H2586L2412 503H2394V700Z"/>
|
||||||
|
<g fill="none" stroke="currentColor">
|
||||||
|
<circle cx="1396" cy="452" r="200" stroke-width="104"/>
|
||||||
|
<path d="M1376 412 L1416 452 L1376 492" stroke-width="54" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="70 0 2678 714" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<path fill="#F4F6F8" d="M70 700V0H196V387H214L378 204H542L313 444L550 700H388L214 503H196V700Z M589 700V204H713V269H731Q743 243 776 219.5Q809 196 876 196Q934 196 977.5 222.5Q1021 249 1045 295.5Q1069 342 1069 404V700H943V414Q943 358 915.5 330Q888 302 837 302Q779 302 747 340.5Q715 379 715 448V700Z M1960 714Q1888 714 1829.5 684Q1771 654 1737 597Q1703 540 1703 459V445Q1703 364 1737 307Q1771 250 1829.5 220Q1888 190 1960 190Q2031 190 2082 215Q2133 240 2164.5 283.5Q2196 327 2206 382L2084 408Q2080 378 2066 354Q2052 330 2026.5 316Q2001 302 1963 302Q1925 302 1894.5 318.5Q1864 335 1846.5 367.5Q1829 400 1829 447V457Q1829 504 1846.5 536.5Q1864 569 1894.5 585.5Q1925 602 1963 602Q2020 602 2049.5 572.5Q2079 543 2087 495L2209 524Q2196 577 2164.5 620.5Q2133 664 2082 689Q2031 714 1960 714Z M2268 700V0H2394V387H2412L2576 204H2740L2511 444L2748 700H2586L2412 503H2394V700Z"/>
|
||||||
|
<g fill="none" stroke="#2EC4F1">
|
||||||
|
<circle cx="1396" cy="452" r="200" stroke-width="104"/>
|
||||||
|
<path d="M1376 412 L1416 452 L1376 492" stroke-width="54" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="70 0 2678 714" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<path fill="#101318" d="M70 700V0H196V387H214L378 204H542L313 444L550 700H388L214 503H196V700Z M589 700V204H713V269H731Q743 243 776 219.5Q809 196 876 196Q934 196 977.5 222.5Q1021 249 1045 295.5Q1069 342 1069 404V700H943V414Q943 358 915.5 330Q888 302 837 302Q779 302 747 340.5Q715 379 715 448V700Z M1960 714Q1888 714 1829.5 684Q1771 654 1737 597Q1703 540 1703 459V445Q1703 364 1737 307Q1771 250 1829.5 220Q1888 190 1960 190Q2031 190 2082 215Q2133 240 2164.5 283.5Q2196 327 2206 382L2084 408Q2080 378 2066 354Q2052 330 2026.5 316Q2001 302 1963 302Q1925 302 1894.5 318.5Q1864 335 1846.5 367.5Q1829 400 1829 447V457Q1829 504 1846.5 536.5Q1864 569 1894.5 585.5Q1925 602 1963 602Q2020 602 2049.5 572.5Q2079 543 2087 495L2209 524Q2196 577 2164.5 620.5Q2133 664 2082 689Q2031 714 1960 714Z M2268 700V0H2394V387H2412L2576 204H2740L2511 444L2748 700H2586L2412 503H2394V700Z"/>
|
||||||
|
<g fill="none" stroke="#0B7FAD">
|
||||||
|
<circle cx="1396" cy="452" r="200" stroke-width="104"/>
|
||||||
|
<path d="M1376 412 L1416 452 L1376 492" stroke-width="54" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"name": "knock",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"license": "MIT",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"check": "svelte-check --tsconfig ./tsconfig.json",
|
||||||
|
"tauri": "tauri"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@sveltejs/vite-plugin-svelte": "^7.3.2",
|
||||||
|
"@tailwindcss/vite": "^4.3.5",
|
||||||
|
"@tauri-apps/cli": "^2.12.6",
|
||||||
|
"@tsconfig/svelte": "^5.0.9",
|
||||||
|
"svelte": "^5.59.2",
|
||||||
|
"svelte-check": "^4.7.8",
|
||||||
|
"tailwindcss": "^4.3.5",
|
||||||
|
"typescript": "^6.0.3",
|
||||||
|
"vite": "^8.4.0"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/autocomplete": "^6.20.4",
|
||||||
|
"@codemirror/commands": "^6.11.2",
|
||||||
|
"@codemirror/lang-html": "^6.4.12",
|
||||||
|
"@codemirror/lang-javascript": "^6.2.5",
|
||||||
|
"@codemirror/lang-json": "^6.0.2",
|
||||||
|
"@codemirror/lang-xml": "^6.1.0",
|
||||||
|
"@codemirror/language": "^6.13.1",
|
||||||
|
"@codemirror/lint": "^6.9.8",
|
||||||
|
"@codemirror/search": "^6.7.3",
|
||||||
|
"@codemirror/state": "^6.7.6",
|
||||||
|
"@codemirror/view": "^6.44.2",
|
||||||
|
"@fontsource/jetbrains-mono": "^5.3.0",
|
||||||
|
"@fontsource/space-grotesk": "^5.3.0",
|
||||||
|
"@joshicodes/cock": "^1.7.1",
|
||||||
|
"@lezer/highlight": "^1.2.5",
|
||||||
|
"@tauri-apps/api": "^2.12.5",
|
||||||
|
"@tauri-apps/plugin-deep-link": "^2.6.3",
|
||||||
|
"@tauri-apps/plugin-dialog": "^2.8.4",
|
||||||
|
"@tauri-apps/plugin-opener": "^2.7.3",
|
||||||
|
"cm6-graphql": "^1.0.0",
|
||||||
|
"graphql": "^17.1.0",
|
||||||
|
"jsonpath-plus": "^11.3.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<rect width="16" height="16" rx="3.5" fill="#101318"/>
|
||||||
|
<g transform="translate(1.5 1.5) scale(0.13)" fill="none" stroke="#2EC4F1" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="50" cy="50" r="36" stroke-width="16"/>
|
||||||
|
<path d="M46 40 L55 50 L46 60" stroke-width="15"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 420 B |
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="70 0 2678 714" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<path fill="#101318" d="M70 700V0H196V387H214L378 204H542L313 444L550 700H388L214 503H196V700Z M589 700V204H713V269H731Q743 243 776 219.5Q809 196 876 196Q934 196 977.5 222.5Q1021 249 1045 295.5Q1069 342 1069 404V700H943V414Q943 358 915.5 330Q888 302 837 302Q779 302 747 340.5Q715 379 715 448V700Z M1960 714Q1888 714 1829.5 684Q1771 654 1737 597Q1703 540 1703 459V445Q1703 364 1737 307Q1771 250 1829.5 220Q1888 190 1960 190Q2031 190 2082 215Q2133 240 2164.5 283.5Q2196 327 2206 382L2084 408Q2080 378 2066 354Q2052 330 2026.5 316Q2001 302 1963 302Q1925 302 1894.5 318.5Q1864 335 1846.5 367.5Q1829 400 1829 447V457Q1829 504 1846.5 536.5Q1864 569 1894.5 585.5Q1925 602 1963 602Q2020 602 2049.5 572.5Q2079 543 2087 495L2209 524Q2196 577 2164.5 620.5Q2133 664 2082 689Q2031 714 1960 714Z M2268 700V0H2394V387H2412L2576 204H2740L2511 444L2748 700H2586L2412 503H2394V700Z"/>
|
||||||
|
<g fill="none" stroke="#0B7FAD">
|
||||||
|
<circle cx="1396" cy="452" r="200" stroke-width="104"/>
|
||||||
|
<path d="M1376 412 L1416 452 L1376 492" stroke-width="54" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="70 0 2678 714" role="img" aria-label="Knock">
|
||||||
|
<title>Knock</title>
|
||||||
|
<path fill="#F4F6F8" d="M70 700V0H196V387H214L378 204H542L313 444L550 700H388L214 503H196V700Z M589 700V204H713V269H731Q743 243 776 219.5Q809 196 876 196Q934 196 977.5 222.5Q1021 249 1045 295.5Q1069 342 1069 404V700H943V414Q943 358 915.5 330Q888 302 837 302Q779 302 747 340.5Q715 379 715 448V700Z M1960 714Q1888 714 1829.5 684Q1771 654 1737 597Q1703 540 1703 459V445Q1703 364 1737 307Q1771 250 1829.5 220Q1888 190 1960 190Q2031 190 2082 215Q2133 240 2164.5 283.5Q2196 327 2206 382L2084 408Q2080 378 2066 354Q2052 330 2026.5 316Q2001 302 1963 302Q1925 302 1894.5 318.5Q1864 335 1846.5 367.5Q1829 400 1829 447V457Q1829 504 1846.5 536.5Q1864 569 1894.5 585.5Q1925 602 1963 602Q2020 602 2049.5 572.5Q2079 543 2087 495L2209 524Q2196 577 2164.5 620.5Q2133 664 2082 689Q2031 714 1960 714Z M2268 700V0H2394V387H2412L2576 204H2740L2511 444L2748 700H2586L2412 503H2394V700Z"/>
|
||||||
|
<g fill="none" stroke="#2EC4F1">
|
||||||
|
<circle cx="1396" cy="452" r="200" stroke-width="104"/>
|
||||||
|
<path d="M1376 412 L1416 452 L1376 492" stroke-width="54" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,36 @@
|
|||||||
|
[package]
|
||||||
|
name = "knock-app"
|
||||||
|
description = "knock, a desktop API client"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
default-run = "knock-app"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "knock_app_lib"
|
||||||
|
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
tauri-build = { version = "2", features = [] }
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
knock-core.workspace = true
|
||||||
|
anyhow.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
serde_yaml_ng.workspace = true
|
||||||
|
indexmap.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
uuid.workspace = true
|
||||||
|
chrono.workspace = true
|
||||||
|
url.workspace = true
|
||||||
|
base64.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
tauri = { version = "2", features = [] }
|
||||||
|
tauri-plugin-dialog = "2"
|
||||||
|
tauri-plugin-opener = "2"
|
||||||
|
tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
|
||||||
|
tauri-plugin-deep-link = "2"
|
||||||
|
rusqlite = { version = "0.37", features = ["bundled"] }
|
||||||
|
notify = "8"
|
||||||
|
futures-util = "0.3"
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
fn main() {
|
||||||
|
tauri_build::build()
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
|
"identifier": "default",
|
||||||
|
"description": "Main window",
|
||||||
|
"windows": ["main"],
|
||||||
|
"permissions": [
|
||||||
|
"core:default",
|
||||||
|
"core:window:allow-start-dragging",
|
||||||
|
"core:window:allow-minimize",
|
||||||
|
"core:window:allow-toggle-maximize",
|
||||||
|
"core:window:allow-close",
|
||||||
|
"core:window:allow-is-maximized",
|
||||||
|
"core:window:allow-start-resize-dragging",
|
||||||
|
"dialog:default",
|
||||||
|
"opener:default",
|
||||||
|
"deep-link:default"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 5.3 KiB |
|
After Width: | Height: | Size: 721 B |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 3.1 KiB |
|
After Width: | Height: | Size: 5.8 KiB |
|
After Width: | Height: | Size: 659 B |
|
After Width: | Height: | Size: 6.3 KiB |
|
After Width: | Height: | Size: 1004 B |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 11 KiB |
@@ -0,0 +1,623 @@
|
|||||||
|
use crate::db;
|
||||||
|
use crate::state::AppState;
|
||||||
|
use crate::watch;
|
||||||
|
use indexmap::IndexMap;
|
||||||
|
use knock_core::collection::{Collection, EnvEntry, FolderNode, Problem};
|
||||||
|
use knock_core::model::*;
|
||||||
|
use knock_core::prepare::{ContextInput, RequestContext};
|
||||||
|
use knock_core::run::{execute, RunOutput};
|
||||||
|
use knock_core::secrets::{self, SecretStore};
|
||||||
|
use knock_core::vars::{VarInfo, DYNAMIC_VARS};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tauri::{AppHandle, Manager, State};
|
||||||
|
|
||||||
|
type Res<T> = Result<T, String>;
|
||||||
|
|
||||||
|
fn err(e: impl std::fmt::Display) -> String {
|
||||||
|
e.to_string()
|
||||||
|
}
|
||||||
|
fn errx(e: anyhow::Error) -> String {
|
||||||
|
format!("{e:#}")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- collections
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct CollectionView {
|
||||||
|
pub id: String,
|
||||||
|
pub root: String,
|
||||||
|
pub name: String,
|
||||||
|
pub tree: FolderNode,
|
||||||
|
pub environments: Vec<EnvEntry>,
|
||||||
|
pub problems: Vec<Problem>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view(c: &Collection) -> CollectionView {
|
||||||
|
CollectionView {
|
||||||
|
id: c.manifest.id.clone(),
|
||||||
|
root: c.root.display().to_string(),
|
||||||
|
name: c.manifest.name.clone(),
|
||||||
|
tree: c.tree.clone(),
|
||||||
|
environments: c.environments.clone(),
|
||||||
|
problems: c.problems.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remember_recent(state: &AppState, root: &str) {
|
||||||
|
let db = state.db.lock().unwrap();
|
||||||
|
let mut recent: Vec<String> = db::kv_get(&db, "recent")
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.and_then(|s| serde_json::from_str(&s).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
recent.retain(|r| r != root);
|
||||||
|
recent.insert(0, root.to_string());
|
||||||
|
recent.truncate(12);
|
||||||
|
let _ = db::kv_set(&db, "recent", &serde_json::to_string(&recent).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn register(app: &AppHandle, state: &AppState, c: Collection) -> Res<CollectionView> {
|
||||||
|
let v = view(&c);
|
||||||
|
if let Ok(Some(json)) = db::jar_load(&state.db.lock().unwrap(), &v.id) {
|
||||||
|
state.engine.load_jar(&v.id, &json);
|
||||||
|
}
|
||||||
|
let root = c.root.clone();
|
||||||
|
state.collections.write().unwrap().insert(v.id.clone(), c);
|
||||||
|
remember_recent(state, &v.root);
|
||||||
|
watch::start(app, state, &v.id, &root);
|
||||||
|
Ok(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn collection_open(app: AppHandle, state: State<'_, AppState>, path: String) -> Res<CollectionView> {
|
||||||
|
let c = Collection::open(&path).map_err(errx)?;
|
||||||
|
register(&app, &state, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn collection_create(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
path: String,
|
||||||
|
name: String,
|
||||||
|
) -> Res<CollectionView> {
|
||||||
|
let c = Collection::create(&path, &name).map_err(errx)?;
|
||||||
|
register(&app, &state, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn collection_get(state: State<'_, AppState>, id: String) -> Res<CollectionView> {
|
||||||
|
state.with_collection(&id, |c| Ok(view(c))).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn collection_close(state: State<'_, AppState>, id: String) -> Res<()> {
|
||||||
|
state.collections.write().unwrap().remove(&id);
|
||||||
|
state.watchers.lock().unwrap().remove(&id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn recent_collections(state: State<'_, AppState>) -> Res<Vec<String>> {
|
||||||
|
let db = state.db.lock().unwrap();
|
||||||
|
Ok(db::kv_get(&db, "recent")
|
||||||
|
.map_err(errx)?
|
||||||
|
.and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|p| PathBuf::from(p).join("knock.yaml").exists())
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn recent_forget(state: State<'_, AppState>, path: String) -> Res<()> {
|
||||||
|
let db = state.db.lock().unwrap();
|
||||||
|
let mut recent: Vec<String> = db::kv_get(&db, "recent")
|
||||||
|
.map_err(errx)?
|
||||||
|
.and_then(|s| serde_json::from_str(&s).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
recent.retain(|r| r != &path);
|
||||||
|
db::kv_set(&db, "recent", &serde_json::to_string(&recent).unwrap()).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- tree edits
|
||||||
|
|
||||||
|
fn after_edit(state: &AppState, col: &str) -> Res<CollectionView> {
|
||||||
|
state.reload(col).map_err(errx)?;
|
||||||
|
state.with_collection(col, |c| Ok(view(c))).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct EditResult {
|
||||||
|
pub id: String,
|
||||||
|
pub collection: CollectionView,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn request_get(state: State<'_, AppState>, col: String, id: String) -> Res<Request> {
|
||||||
|
state.with_collection(&col, |c| c.request(&id)).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn request_save(state: State<'_, AppState>, col: String, id: String, request: Request) -> Res<CollectionView> {
|
||||||
|
state.with_collection(&col, |c| c.save_request(&id, &request)).map_err(errx)?;
|
||||||
|
after_edit(&state, &col)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn request_create(
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
col: String,
|
||||||
|
folder: String,
|
||||||
|
request: Request,
|
||||||
|
) -> Res<EditResult> {
|
||||||
|
let id = state.with_collection(&col, |c| c.create_request(&folder, &request)).map_err(errx)?;
|
||||||
|
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn folder_create(state: State<'_, AppState>, col: String, parent: String, name: String) -> Res<EditResult> {
|
||||||
|
let id = state.with_collection(&col, |c| c.create_folder(&parent, &name)).map_err(errx)?;
|
||||||
|
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn node_rename(state: State<'_, AppState>, col: String, id: String, name: String) -> Res<EditResult> {
|
||||||
|
let id = state.with_collection(&col, |c| c.rename(&id, &name)).map_err(errx)?;
|
||||||
|
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn node_duplicate(state: State<'_, AppState>, col: String, id: String) -> Res<EditResult> {
|
||||||
|
let id = state.with_collection(&col, |c| c.duplicate(&id)).map_err(errx)?;
|
||||||
|
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn node_delete(state: State<'_, AppState>, col: String, id: String) -> Res<CollectionView> {
|
||||||
|
state.with_collection(&col, |c| c.delete(&id)).map_err(errx)?;
|
||||||
|
after_edit(&state, &col)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn node_move(
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
col: String,
|
||||||
|
id: String,
|
||||||
|
folder: String,
|
||||||
|
index: Option<usize>,
|
||||||
|
) -> Res<EditResult> {
|
||||||
|
let id = state.with_collection(&col, |c| c.move_node(&id, &folder, index)).map_err(errx)?;
|
||||||
|
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn folder_get(state: State<'_, AppState>, col: String, id: String) -> Res<FolderMeta> {
|
||||||
|
state.with_collection(&col, |c| c.folder_meta(&id)).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn folder_save(state: State<'_, AppState>, col: String, id: String, meta: FolderMeta) -> Res<CollectionView> {
|
||||||
|
state.with_collection(&col, |c| c.save_folder_meta(&id, &meta)).map_err(errx)?;
|
||||||
|
after_edit(&state, &col)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn manifest_get(state: State<'_, AppState>, col: String) -> Res<Manifest> {
|
||||||
|
state.with_collection(&col, |c| Ok(c.manifest.clone())).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn manifest_save(state: State<'_, AppState>, col: String, manifest: Manifest) -> Res<CollectionView> {
|
||||||
|
state.with_collection(&col, |c| c.save_manifest(&manifest)).map_err(errx)?;
|
||||||
|
after_edit(&state, &col)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- environments
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn env_get(state: State<'_, AppState>, col: String, id: String) -> Res<Environment> {
|
||||||
|
state.with_collection(&col, |c| c.environment(&id)).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn env_save(state: State<'_, AppState>, col: String, id: String, env: Environment) -> Res<CollectionView> {
|
||||||
|
state.with_collection(&col, |c| c.save_environment(&id, &env)).map_err(errx)?;
|
||||||
|
after_edit(&state, &col)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn env_delete(state: State<'_, AppState>, col: String, id: String) -> Res<CollectionView> {
|
||||||
|
state.with_collection(&col, |c| c.delete_environment(&id)).map_err(errx)?;
|
||||||
|
after_edit(&state, &col)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct SecretStatus {
|
||||||
|
pub name: String,
|
||||||
|
pub source: Option<secrets::SecretSource>,
|
||||||
|
pub value: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where each secret of an environment currently comes from. Values are
|
||||||
|
/// returned so the UI can reveal them on demand; it masks by default.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn env_secrets(state: State<'_, AppState>, col: String, env: String) -> Res<Vec<SecretStatus>> {
|
||||||
|
let (e, file) = state
|
||||||
|
.with_collection(&col, |c| Ok((c.environment(&env)?, c.secrets_file(&env)?)))
|
||||||
|
.map_err(errx)?;
|
||||||
|
let store = SecretStore::new(&col, Some(&env), file.vars, true);
|
||||||
|
Ok(e.vars
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, v)| v.secret)
|
||||||
|
.map(|(k, _)| {
|
||||||
|
let found = store.find(k);
|
||||||
|
SecretStatus {
|
||||||
|
name: k.clone(),
|
||||||
|
source: found.as_ref().map(|f| f.1),
|
||||||
|
value: found.map(|f| f.0),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn secret_set(
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
col: String,
|
||||||
|
env: Option<String>,
|
||||||
|
name: String,
|
||||||
|
value: Option<String>,
|
||||||
|
target: String,
|
||||||
|
) -> Res<()> {
|
||||||
|
match target.as_str() {
|
||||||
|
"file" => {
|
||||||
|
let env = env.ok_or("secrets files belong to an environment")?;
|
||||||
|
state
|
||||||
|
.with_collection(&col, |c| {
|
||||||
|
let mut f = c.secrets_file(&env)?;
|
||||||
|
match &value {
|
||||||
|
Some(v) => {
|
||||||
|
f.vars.insert(name.clone(), v.clone());
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
f.vars.shift_remove(&name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.save_secrets_file(&env, &f)
|
||||||
|
})
|
||||||
|
.map_err(errx)
|
||||||
|
}
|
||||||
|
_ => match value {
|
||||||
|
Some(v) => secrets::keyring_set(&col, env.as_deref(), &name, &v).map_err(|e| {
|
||||||
|
format!("could not write to the system keyring ({e:#}). Is a Secret Service (KWallet, GNOME Keyring) running? You can store it in the secrets file instead.")
|
||||||
|
}),
|
||||||
|
None => secrets::keyring_delete(&col, env.as_deref(), &name).map_err(errx),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- variables
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ScopeArgs {
|
||||||
|
pub col: Option<String>,
|
||||||
|
pub request_id: Option<String>,
|
||||||
|
pub request: Request,
|
||||||
|
pub env: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_context(state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestContext> {
|
||||||
|
let globals = db::globals_load(&state.db.lock().unwrap()).unwrap_or_default();
|
||||||
|
match &a.col {
|
||||||
|
Some(col) => {
|
||||||
|
let c = state.collection(col)?;
|
||||||
|
let file = a.env.as_deref().map(|e| c.secrets_file(e).unwrap_or_default()).unwrap_or_default();
|
||||||
|
let store = SecretStore::new(&c.manifest.id, a.env.as_deref(), file.vars, true);
|
||||||
|
let rid = a.request_id.clone().unwrap_or_else(|| "__unsaved__.yaml".into());
|
||||||
|
RequestContext::build(ContextInput {
|
||||||
|
collection: &c,
|
||||||
|
request_id: &rid,
|
||||||
|
request: &a.request,
|
||||||
|
env: a.env.as_deref(),
|
||||||
|
runtime: state.runtime_vars(col),
|
||||||
|
globals,
|
||||||
|
secrets: Arc::new(store),
|
||||||
|
oauth: Some(Arc::new(crate::oauth::TokenLookup::new(state, &c, a.env.as_deref()))),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let mut ctx = RequestContext::standalone(&a.request, std::env::temp_dir());
|
||||||
|
ctx.resolver.layers.push(knock_core::vars::Layer::new(
|
||||||
|
knock_core::vars::Scope::Global,
|
||||||
|
"global",
|
||||||
|
globals,
|
||||||
|
));
|
||||||
|
ctx.resolver.push_front(knock_core::vars::Layer::new(
|
||||||
|
knock_core::vars::Scope::Runtime,
|
||||||
|
"runtime",
|
||||||
|
state.runtime_vars(""),
|
||||||
|
));
|
||||||
|
Ok(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct VarsView {
|
||||||
|
pub vars: Vec<VarInfo>,
|
||||||
|
pub dynamic: Vec<(String, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn vars_list(state: State<'_, AppState>, args: ScopeArgs) -> Res<VarsView> {
|
||||||
|
let ctx = build_context(&state, &args).map_err(errx)?;
|
||||||
|
Ok(VarsView {
|
||||||
|
vars: ctx.resolver.names(),
|
||||||
|
dynamic: DYNAMIC_VARS.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn runtime_list(state: State<'_, AppState>, col: Option<String>) -> Res<IndexMap<String, String>> {
|
||||||
|
Ok(state.runtime_vars(col.as_deref().unwrap_or("")))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn runtime_set(
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
col: Option<String>,
|
||||||
|
name: String,
|
||||||
|
value: Option<String>,
|
||||||
|
persist: bool,
|
||||||
|
) -> Res<()> {
|
||||||
|
state.set_runtime(col.as_deref().unwrap_or(""), &name, value, persist);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn globals_get(state: State<'_, AppState>) -> Res<IndexMap<String, String>> {
|
||||||
|
db::globals_load(&state.db.lock().unwrap()).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn globals_save(state: State<'_, AppState>, vars: IndexMap<String, String>) -> Res<()> {
|
||||||
|
db::globals_save(&state.db.lock().unwrap(), &vars).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- sending
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct SendArgs {
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub scope: ScopeArgs,
|
||||||
|
pub tab: String,
|
||||||
|
/// Store up to this many bytes of the body in history (0 = none).
|
||||||
|
#[serde(default)]
|
||||||
|
pub history_body_limit: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct SendResult {
|
||||||
|
pub output: RunOutput,
|
||||||
|
pub body_id: Option<String>,
|
||||||
|
pub history_id: Option<i64>,
|
||||||
|
pub body_file: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn request_send(app: AppHandle, args: SendArgs) -> Res<SendResult> {
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
let ctx = build_context(&state, &args.scope).map_err(errx)?;
|
||||||
|
let engine = state.engine.clone();
|
||||||
|
let req = args.scope.request.clone();
|
||||||
|
let host = crate::oauth::Host::new(app.clone(), args.scope.col.clone(), args.scope.env.clone());
|
||||||
|
let task = tokio::spawn(async move {
|
||||||
|
let out = execute(&engine, &req, &ctx, Some(&host)).await;
|
||||||
|
(out, ctx)
|
||||||
|
});
|
||||||
|
state.inflight.lock().unwrap().insert(args.tab.clone(), task.abort_handle());
|
||||||
|
let joined = task.await;
|
||||||
|
state.inflight.lock().unwrap().remove(&args.tab);
|
||||||
|
let (mut out, ctx) = match joined {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) if e.is_cancelled() => return Err("cancelled".into()),
|
||||||
|
Err(e) => return Err(err(e)),
|
||||||
|
};
|
||||||
|
|
||||||
|
let col_key = args.scope.col.clone().unwrap_or_default();
|
||||||
|
for x in &out.extracted {
|
||||||
|
if let Some(v) = &x.value {
|
||||||
|
state.set_runtime(&col_key, &x.var, Some(v.clone()), x.persist);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(col) = &args.scope.col {
|
||||||
|
let json = state.engine.save_jar(col);
|
||||||
|
let _ = db::jar_save(&state.db.lock().unwrap(), col, &json);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut body_id = None;
|
||||||
|
let mut body_file = None;
|
||||||
|
let mut stored_body: Option<Vec<u8>> = None;
|
||||||
|
if let Some(resp) = out.response.as_mut() {
|
||||||
|
let body = std::mem::take(&mut resp.body);
|
||||||
|
if args.history_body_limit > 0 && body.len() <= args.history_body_limit && resp.body_file.is_none() {
|
||||||
|
stored_body = Some(body.clone());
|
||||||
|
}
|
||||||
|
body_file = resp.body_file.as_ref().map(|p| p.display().to_string());
|
||||||
|
body_id = Some(state.store_body(body, resp.body_file.clone()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// History never contains secrets in clear text.
|
||||||
|
let mask = |s: &str| ctx.resolver.mask(s);
|
||||||
|
let mut hist_req = args.scope.request.clone();
|
||||||
|
if let Some(sent) = &out.request {
|
||||||
|
hist_req.url = mask(&sent.url);
|
||||||
|
}
|
||||||
|
let req_json = mask(&serde_json::to_string(&hist_req).unwrap_or_default());
|
||||||
|
let meta = out.response.as_ref().map(|r| mask(&serde_json::to_string(r).unwrap_or_default()));
|
||||||
|
let history_id = {
|
||||||
|
let db = state.db.lock().unwrap();
|
||||||
|
db::history_add(
|
||||||
|
&db,
|
||||||
|
db::NewHistory {
|
||||||
|
collection: &col_key,
|
||||||
|
request_id: args.scope.request_id.as_deref(),
|
||||||
|
name: &args.scope.request.name,
|
||||||
|
method: out.request.as_ref().map(|r| r.method.as_str()).unwrap_or(args.scope.request.method()),
|
||||||
|
url: &out.request.as_ref().map(|r| mask(&r.url)).unwrap_or_else(|| args.scope.request.url.clone()),
|
||||||
|
status: out.response.as_ref().map(|r| r.status),
|
||||||
|
duration_ms: out.response.as_ref().map(|r| r.timings.total_ms),
|
||||||
|
size: out.response.as_ref().map(|r| r.size),
|
||||||
|
error: out.error.as_deref(),
|
||||||
|
request_json: &req_json,
|
||||||
|
response_meta: meta.as_deref(),
|
||||||
|
response_body: stored_body.as_deref(),
|
||||||
|
},
|
||||||
|
500 * 1024 * 1024,
|
||||||
|
)
|
||||||
|
.ok()
|
||||||
|
};
|
||||||
|
Ok(SendResult { output: out, body_id, history_id, body_file })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn request_cancel(state: State<'_, AppState>, tab: String) -> Res<()> {
|
||||||
|
if let Some(h) = state.inflight.lock().unwrap().remove(&tab) {
|
||||||
|
h.abort();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Raw body bytes; the frontend decodes them itself.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn response_body(state: State<'_, AppState>, id: String) -> Res<tauri::ipc::Response> {
|
||||||
|
let guard = state.responses.lock().unwrap();
|
||||||
|
let b = guard.0.get(&id).ok_or("response is no longer available")?;
|
||||||
|
Ok(tauri::ipc::Response::new(b.body.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn response_save(state: State<'_, AppState>, id: String, path: String) -> Res<()> {
|
||||||
|
let guard = state.responses.lock().unwrap();
|
||||||
|
let b = guard.0.get(&id).ok_or("response is no longer available")?;
|
||||||
|
match &b.file {
|
||||||
|
Some(f) => std::fs::copy(f, &path).map(|_| ()).map_err(err),
|
||||||
|
None => std::fs::write(&path, &b.body).map_err(err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct Preview {
|
||||||
|
pub request: Option<knock_core::run::SentRequest>,
|
||||||
|
pub auth: knock_core::auth::AuthDebug,
|
||||||
|
pub missing: Vec<String>,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What would be sent, without sending: resolved URL, headers, body and auth.
|
||||||
|
/// OAuth tokens are not fetched here.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn request_preview(app: AppHandle, args: ScopeArgs) -> Res<Preview> {
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
let ctx = build_context(&state, &args).map_err(errx)?;
|
||||||
|
let mut p = match knock_core::prepare::prepare(&args.request, &ctx) {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(e) => {
|
||||||
|
return Ok(Preview { request: None, auth: Default::default(), missing: vec![], error: Some(errx(e)) })
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone());
|
||||||
|
let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false).await;
|
||||||
|
Ok(Preview {
|
||||||
|
request: Some(knock_core::run::SentRequest {
|
||||||
|
method: p.method.clone(),
|
||||||
|
url: p.url.clone(),
|
||||||
|
headers: p.headers.clone(),
|
||||||
|
body: match &p.body {
|
||||||
|
knock_core::prepare::PreparedBody::Bytes { preview, .. } => preview.clone(),
|
||||||
|
_ => String::new(),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
missing: p.missing.clone(),
|
||||||
|
auth,
|
||||||
|
error: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- cookies
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn cookies_list(state: State<'_, AppState>, col: String) -> Res<Vec<knock_core::http::CookieInfo>> {
|
||||||
|
Ok(state.engine.cookies(&col))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn cookie_delete(
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
col: String,
|
||||||
|
domain: Option<String>,
|
||||||
|
path: Option<String>,
|
||||||
|
name: Option<String>,
|
||||||
|
) -> Res<()> {
|
||||||
|
match (domain, path, name) {
|
||||||
|
(Some(d), Some(p), Some(n)) => state.engine.delete_cookie(&col, &d, &p, &n),
|
||||||
|
_ => state.engine.clear_cookies(&col),
|
||||||
|
}
|
||||||
|
let json = state.engine.save_jar(&col);
|
||||||
|
db::jar_save(&state.db.lock().unwrap(), &col, &json).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- history
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn history_list(state: State<'_, AppState>, query: String, limit: Option<u32>) -> Res<Vec<db::HistoryEntry>> {
|
||||||
|
db::history_list(&state.db.lock().unwrap(), &query, limit.unwrap_or(300)).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct HistoryView {
|
||||||
|
pub request: Request,
|
||||||
|
pub response: Option<serde_json::Value>,
|
||||||
|
pub body_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn history_get(state: State<'_, AppState>, id: i64) -> Res<HistoryView> {
|
||||||
|
let d = db::history_get(&state.db.lock().unwrap(), id)
|
||||||
|
.map_err(errx)?
|
||||||
|
.ok_or("history entry not found")?;
|
||||||
|
let request: Request = serde_json::from_str(&d.request_json).map_err(err)?;
|
||||||
|
let response = d.response_meta.and_then(|m| serde_json::from_str(&m).ok());
|
||||||
|
let body_id = d.response_body.map(|b| state.store_body(b, None));
|
||||||
|
Ok(HistoryView { request, response, body_id })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn history_delete(state: State<'_, AppState>, id: Option<i64>) -> Res<()> {
|
||||||
|
db::history_delete(&state.db.lock().unwrap(), id).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- misc
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn setting_get(state: State<'_, AppState>, key: String) -> Res<Option<String>> {
|
||||||
|
db::kv_get(&state.db.lock().unwrap(), &format!("setting.{key}")).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn setting_set(state: State<'_, AppState>, key: String, value: String) -> Res<()> {
|
||||||
|
db::kv_set(&state.db.lock().unwrap(), &format!("setting.{key}"), &value).map_err(errx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn path_params(url: String) -> Vec<String> {
|
||||||
|
knock_core::prepare::path_param_names(&url)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn app_version() -> String {
|
||||||
|
env!("CARGO_PKG_VERSION").to_string()
|
||||||
|
}
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
//! Local SQLite store: history, cookie jars, persisted runtime variables and
|
||||||
|
//! globals. Nothing in here is ever written to a collection folder.
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use indexmap::IndexMap;
|
||||||
|
use rusqlite::{params, Connection, OptionalExtension};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub fn open(path: &Path) -> Result<Connection> {
|
||||||
|
let conn = Connection::open(path)?;
|
||||||
|
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||||
|
conn.pragma_update(None, "synchronous", "NORMAL")?;
|
||||||
|
conn.execute_batch(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS history (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
at TEXT NOT NULL,
|
||||||
|
collection TEXT NOT NULL DEFAULT '',
|
||||||
|
request_id TEXT,
|
||||||
|
name TEXT NOT NULL DEFAULT '',
|
||||||
|
method TEXT NOT NULL,
|
||||||
|
url TEXT NOT NULL,
|
||||||
|
status INTEGER,
|
||||||
|
duration_ms REAL,
|
||||||
|
size INTEGER,
|
||||||
|
error TEXT,
|
||||||
|
request TEXT NOT NULL,
|
||||||
|
response_meta TEXT,
|
||||||
|
response_body BLOB
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS history_at ON history(at DESC);
|
||||||
|
CREATE TABLE IF NOT EXISTS cookie_jars (
|
||||||
|
collection TEXT PRIMARY KEY,
|
||||||
|
json TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS runtime_vars (
|
||||||
|
collection TEXT NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (collection, name)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS globals (
|
||||||
|
name TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS kv (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"#,
|
||||||
|
)?;
|
||||||
|
Ok(conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct HistoryEntry {
|
||||||
|
pub id: i64,
|
||||||
|
pub at: String,
|
||||||
|
pub collection: String,
|
||||||
|
pub request_id: Option<String>,
|
||||||
|
pub name: String,
|
||||||
|
pub method: String,
|
||||||
|
pub url: String,
|
||||||
|
pub status: Option<u16>,
|
||||||
|
pub duration_ms: Option<f64>,
|
||||||
|
pub size: Option<u64>,
|
||||||
|
pub error: Option<String>,
|
||||||
|
pub has_body: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NewHistory<'a> {
|
||||||
|
pub collection: &'a str,
|
||||||
|
pub request_id: Option<&'a str>,
|
||||||
|
pub name: &'a str,
|
||||||
|
pub method: &'a str,
|
||||||
|
pub url: &'a str,
|
||||||
|
pub status: Option<u16>,
|
||||||
|
pub duration_ms: Option<f64>,
|
||||||
|
pub size: Option<u64>,
|
||||||
|
pub error: Option<&'a str>,
|
||||||
|
pub request_json: &'a str,
|
||||||
|
pub response_meta: Option<&'a str>,
|
||||||
|
pub response_body: Option<&'a [u8]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn history_add(c: &Connection, h: NewHistory<'_>, total_limit: u64) -> Result<i64> {
|
||||||
|
c.execute(
|
||||||
|
"INSERT INTO history (at, collection, request_id, name, method, url, status, duration_ms, size, error, request, response_meta, response_body)
|
||||||
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
|
||||||
|
params![
|
||||||
|
chrono::Utc::now().to_rfc3339(),
|
||||||
|
h.collection,
|
||||||
|
h.request_id,
|
||||||
|
h.name,
|
||||||
|
h.method,
|
||||||
|
h.url,
|
||||||
|
h.status,
|
||||||
|
h.duration_ms,
|
||||||
|
h.size,
|
||||||
|
h.error,
|
||||||
|
h.request_json,
|
||||||
|
h.response_meta,
|
||||||
|
h.response_body,
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
let id = c.last_insert_rowid();
|
||||||
|
// Keep stored bodies under the total budget by dropping the oldest ones.
|
||||||
|
let total: i64 = c.query_row(
|
||||||
|
"SELECT COALESCE(SUM(LENGTH(response_body)), 0) FROM history",
|
||||||
|
[],
|
||||||
|
|r| r.get(0),
|
||||||
|
)?;
|
||||||
|
if total as u64 > total_limit {
|
||||||
|
c.execute(
|
||||||
|
"UPDATE history SET response_body = NULL WHERE id IN (
|
||||||
|
SELECT id FROM history WHERE response_body IS NOT NULL ORDER BY id ASC LIMIT 50)",
|
||||||
|
[],
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
c.execute(
|
||||||
|
"DELETE FROM history WHERE id NOT IN (SELECT id FROM history ORDER BY id DESC LIMIT 5000)",
|
||||||
|
[],
|
||||||
|
)?;
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn history_list(c: &Connection, query: &str, limit: u32) -> Result<Vec<HistoryEntry>> {
|
||||||
|
let like = format!("%{}%", query.replace('%', "\\%").replace('_', "\\_"));
|
||||||
|
let mut stmt = c.prepare(
|
||||||
|
"SELECT id, at, collection, request_id, name, method, url, status, duration_ms, size, error, response_body IS NOT NULL
|
||||||
|
FROM history
|
||||||
|
WHERE ?1 = '%%' OR url LIKE ?1 ESCAPE '\\' OR name LIKE ?1 ESCAPE '\\' OR method LIKE ?1 ESCAPE '\\' OR CAST(status AS TEXT) LIKE ?1 ESCAPE '\\'
|
||||||
|
ORDER BY id DESC LIMIT ?2",
|
||||||
|
)?;
|
||||||
|
let rows = stmt.query_map(params![like, limit], |r| {
|
||||||
|
Ok(HistoryEntry {
|
||||||
|
id: r.get(0)?,
|
||||||
|
at: r.get(1)?,
|
||||||
|
collection: r.get(2)?,
|
||||||
|
request_id: r.get(3)?,
|
||||||
|
name: r.get(4)?,
|
||||||
|
method: r.get(5)?,
|
||||||
|
url: r.get(6)?,
|
||||||
|
status: r.get(7)?,
|
||||||
|
duration_ms: r.get(8)?,
|
||||||
|
size: r.get(9)?,
|
||||||
|
error: r.get(10)?,
|
||||||
|
has_body: r.get(11)?,
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
Ok(rows.collect::<Result<_, _>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct HistoryDetail {
|
||||||
|
pub request_json: String,
|
||||||
|
pub response_meta: Option<String>,
|
||||||
|
pub response_body: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn history_get(c: &Connection, id: i64) -> Result<Option<HistoryDetail>> {
|
||||||
|
Ok(c
|
||||||
|
.query_row(
|
||||||
|
"SELECT request, response_meta, response_body FROM history WHERE id = ?1",
|
||||||
|
[id],
|
||||||
|
|r| {
|
||||||
|
Ok(HistoryDetail {
|
||||||
|
request_json: r.get(0)?,
|
||||||
|
response_meta: r.get(1)?,
|
||||||
|
response_body: r.get(2)?,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn history_delete(c: &Connection, id: Option<i64>) -> Result<()> {
|
||||||
|
match id {
|
||||||
|
Some(id) => c.execute("DELETE FROM history WHERE id = ?1", [id])?,
|
||||||
|
None => c.execute("DELETE FROM history", [])?,
|
||||||
|
};
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn jar_load(c: &Connection, collection: &str) -> Result<Option<String>> {
|
||||||
|
Ok(c
|
||||||
|
.query_row("SELECT json FROM cookie_jars WHERE collection = ?1", [collection], |r| r.get(0))
|
||||||
|
.optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn jar_save(c: &Connection, collection: &str, json: &str) -> Result<()> {
|
||||||
|
c.execute(
|
||||||
|
"INSERT INTO cookie_jars (collection, json) VALUES (?1, ?2)
|
||||||
|
ON CONFLICT(collection) DO UPDATE SET json = excluded.json",
|
||||||
|
params![collection, json],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn runtime_load(c: &Connection, collection: &str) -> Result<IndexMap<String, String>> {
|
||||||
|
let mut stmt = c.prepare("SELECT name, value FROM runtime_vars WHERE collection = ?1 ORDER BY name")?;
|
||||||
|
let rows = stmt.query_map([collection], |r| Ok((r.get(0)?, r.get(1)?)))?;
|
||||||
|
Ok(rows.collect::<Result<_, _>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn runtime_set(c: &Connection, collection: &str, name: &str, value: Option<&str>) -> Result<()> {
|
||||||
|
match value {
|
||||||
|
Some(v) => c.execute(
|
||||||
|
"INSERT INTO runtime_vars (collection, name, value) VALUES (?1, ?2, ?3)
|
||||||
|
ON CONFLICT(collection, name) DO UPDATE SET value = excluded.value",
|
||||||
|
params![collection, name, v],
|
||||||
|
)?,
|
||||||
|
None => c.execute(
|
||||||
|
"DELETE FROM runtime_vars WHERE collection = ?1 AND name = ?2",
|
||||||
|
params![collection, name],
|
||||||
|
)?,
|
||||||
|
};
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn globals_load(c: &Connection) -> Result<IndexMap<String, String>> {
|
||||||
|
let mut stmt = c.prepare("SELECT name, value FROM globals ORDER BY name")?;
|
||||||
|
let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
|
||||||
|
Ok(rows.collect::<Result<_, _>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn globals_save(c: &Connection, vars: &IndexMap<String, String>) -> Result<()> {
|
||||||
|
c.execute("DELETE FROM globals", [])?;
|
||||||
|
for (k, v) in vars {
|
||||||
|
c.execute("INSERT INTO globals (name, value) VALUES (?1, ?2)", params![k, v])?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kv_get(c: &Connection, key: &str) -> Result<Option<String>> {
|
||||||
|
Ok(c
|
||||||
|
.query_row("SELECT value FROM kv WHERE key = ?1", [key], |r| r.get(0))
|
||||||
|
.optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kv_set(c: &Connection, key: &str, value: &str) -> Result<()> {
|
||||||
|
c.execute(
|
||||||
|
"INSERT INTO kv (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||||
|
params![key, value],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
mod commands;
|
||||||
|
mod db;
|
||||||
|
mod oauth;
|
||||||
|
mod state;
|
||||||
|
mod watch;
|
||||||
|
|
||||||
|
use tauri::Manager;
|
||||||
|
|
||||||
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
|
pub fn run() {
|
||||||
|
tauri::Builder::default()
|
||||||
|
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||||||
|
if let Some(w) = app.get_webview_window("main") {
|
||||||
|
let _ = w.unminimize();
|
||||||
|
let _ = w.set_focus();
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.plugin(tauri_plugin_deep_link::init())
|
||||||
|
.plugin(tauri_plugin_dialog::init())
|
||||||
|
.plugin(tauri_plugin_opener::init())
|
||||||
|
.setup(|app| {
|
||||||
|
let dir = app.path().app_data_dir()?;
|
||||||
|
app.manage(state::AppState::new(dir)?);
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
commands::collection_open,
|
||||||
|
commands::collection_create,
|
||||||
|
commands::collection_get,
|
||||||
|
commands::collection_close,
|
||||||
|
commands::recent_collections,
|
||||||
|
commands::recent_forget,
|
||||||
|
commands::request_get,
|
||||||
|
commands::request_save,
|
||||||
|
commands::request_create,
|
||||||
|
commands::folder_create,
|
||||||
|
commands::node_rename,
|
||||||
|
commands::node_duplicate,
|
||||||
|
commands::node_delete,
|
||||||
|
commands::node_move,
|
||||||
|
commands::folder_get,
|
||||||
|
commands::folder_save,
|
||||||
|
commands::manifest_get,
|
||||||
|
commands::manifest_save,
|
||||||
|
commands::env_get,
|
||||||
|
commands::env_save,
|
||||||
|
commands::env_delete,
|
||||||
|
commands::env_secrets,
|
||||||
|
commands::secret_set,
|
||||||
|
commands::vars_list,
|
||||||
|
commands::runtime_list,
|
||||||
|
commands::runtime_set,
|
||||||
|
commands::globals_get,
|
||||||
|
commands::globals_save,
|
||||||
|
commands::request_send,
|
||||||
|
commands::request_cancel,
|
||||||
|
commands::request_preview,
|
||||||
|
commands::response_body,
|
||||||
|
commands::response_save,
|
||||||
|
commands::cookies_list,
|
||||||
|
commands::cookie_delete,
|
||||||
|
commands::history_list,
|
||||||
|
commands::history_get,
|
||||||
|
commands::history_delete,
|
||||||
|
commands::setting_get,
|
||||||
|
commands::setting_set,
|
||||||
|
commands::path_params,
|
||||||
|
commands::app_version,
|
||||||
|
])
|
||||||
|
.run(tauri::generate_context!())
|
||||||
|
.expect("error while running knock");
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// WebKitGTK's DMA-BUF renderer breaks on a number of Wayland setups
|
||||||
|
// (blank window, explicit-sync errors). Opt back in with KNOCK_DMABUF=1.
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
if std::env::var_os("KNOCK_DMABUF").is_none()
|
||||||
|
&& std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none()
|
||||||
|
{
|
||||||
|
std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
||||||
|
}
|
||||||
|
knock_app_lib::run()
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
//! OAuth glue between the core flow code and the app (browser, keyring,
|
||||||
|
//! flow log). Filled in with the OAuth milestone.
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
use knock_core::auth::{AuthHost, OauthResult, Step, StepStatus};
|
||||||
|
use knock_core::model::AuthConfig;
|
||||||
|
use knock_core::vars::{OauthLookup, Resolver};
|
||||||
|
use knock_core::Collection;
|
||||||
|
use tauri::AppHandle;
|
||||||
|
|
||||||
|
pub struct Host {
|
||||||
|
#[allow(dead_code)]
|
||||||
|
app: AppHandle,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
col: Option<String>,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
env: Option<String>,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
interactive: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Host {
|
||||||
|
pub fn new(app: AppHandle, col: Option<String>, env: Option<String>) -> Self {
|
||||||
|
Self { app, col, env, interactive: true }
|
||||||
|
}
|
||||||
|
pub fn preview(app: AppHandle, col: Option<String>, env: Option<String>) -> Self {
|
||||||
|
Self { app, col, env, interactive: false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthHost for Host {
|
||||||
|
fn oauth2_token(
|
||||||
|
&self,
|
||||||
|
_cfg: &AuthConfig,
|
||||||
|
_resolver: &Resolver,
|
||||||
|
_force_refresh: bool,
|
||||||
|
) -> futures_util::future::BoxFuture<'_, OauthResult> {
|
||||||
|
Box::pin(async move {
|
||||||
|
OauthResult {
|
||||||
|
steps: vec![Step::new("token", "Get token", StepStatus::Error, "OAuth 2.0 is not wired up yet")],
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TokenLookup;
|
||||||
|
|
||||||
|
impl TokenLookup {
|
||||||
|
pub fn new(_state: &AppState, _c: &Collection, _env: Option<&str>) -> Self {
|
||||||
|
Self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OauthLookup for TokenLookup {
|
||||||
|
fn oauth_value(&self, _config: &str, _field: &str) -> Option<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
use crate::db;
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use indexmap::IndexMap;
|
||||||
|
use knock_core::http::Engine;
|
||||||
|
use knock_core::Collection;
|
||||||
|
use rusqlite::Connection;
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::{Arc, Mutex, RwLock};
|
||||||
|
|
||||||
|
pub struct StoredBody {
|
||||||
|
pub body: Vec<u8>,
|
||||||
|
pub file: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AppState {
|
||||||
|
pub data_dir: PathBuf,
|
||||||
|
pub collections: RwLock<HashMap<String, Collection>>,
|
||||||
|
pub engine: Arc<Engine>,
|
||||||
|
pub db: Mutex<Connection>,
|
||||||
|
/// Runtime variables per collection id ("" for loose requests).
|
||||||
|
pub runtime: Mutex<HashMap<String, IndexMap<String, String>>>,
|
||||||
|
pub responses: Mutex<(HashMap<String, StoredBody>, VecDeque<String>)>,
|
||||||
|
pub inflight: Mutex<HashMap<String, tokio::task::AbortHandle>>,
|
||||||
|
pub watchers: Mutex<HashMap<String, notify::RecommendedWatcher>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const KEEP_RESPONSES: usize = 40;
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub fn new(data_dir: PathBuf) -> Result<Self> {
|
||||||
|
std::fs::create_dir_all(&data_dir)?;
|
||||||
|
let db = db::open(&data_dir.join("knock.db"))?;
|
||||||
|
Ok(Self {
|
||||||
|
engine: Arc::new(Engine::new(data_dir.join("responses"))),
|
||||||
|
data_dir,
|
||||||
|
collections: RwLock::default(),
|
||||||
|
db: Mutex::new(db),
|
||||||
|
runtime: Mutex::default(),
|
||||||
|
responses: Mutex::default(),
|
||||||
|
inflight: Mutex::default(),
|
||||||
|
watchers: Mutex::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn collection(&self, id: &str) -> Result<Collection> {
|
||||||
|
self.collections
|
||||||
|
.read()
|
||||||
|
.unwrap()
|
||||||
|
.get(id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| anyhow!("collection is not open"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_collection<T>(&self, id: &str, f: impl FnOnce(&Collection) -> Result<T>) -> Result<T> {
|
||||||
|
let guard = self.collections.read().unwrap();
|
||||||
|
let c = guard.get(id).ok_or_else(|| anyhow!("collection is not open"))?;
|
||||||
|
f(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reload(&self, id: &str) -> Result<()> {
|
||||||
|
let mut guard = self.collections.write().unwrap();
|
||||||
|
if let Some(c) = guard.get_mut(id) {
|
||||||
|
c.reload()?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn runtime_vars(&self, collection: &str) -> IndexMap<String, String> {
|
||||||
|
let mut rt = self.runtime.lock().unwrap();
|
||||||
|
if !rt.contains_key(collection) {
|
||||||
|
let persisted = db::runtime_load(&self.db.lock().unwrap(), collection).unwrap_or_default();
|
||||||
|
rt.insert(collection.to_string(), persisted);
|
||||||
|
}
|
||||||
|
rt[collection].clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_runtime(&self, collection: &str, name: &str, value: Option<String>, persist: bool) {
|
||||||
|
self.runtime_vars(collection);
|
||||||
|
let mut rt = self.runtime.lock().unwrap();
|
||||||
|
let map = rt.get_mut(collection).unwrap();
|
||||||
|
match &value {
|
||||||
|
Some(v) => {
|
||||||
|
map.insert(name.to_string(), v.clone());
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
map.shift_remove(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if persist || value.is_none() {
|
||||||
|
let _ = db::runtime_set(&self.db.lock().unwrap(), collection, name, value.as_deref());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn store_body(&self, body: Vec<u8>, file: Option<PathBuf>) -> String {
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let mut guard = self.responses.lock().unwrap();
|
||||||
|
let (map, order) = &mut *guard;
|
||||||
|
map.insert(id.clone(), StoredBody { body, file });
|
||||||
|
order.push_back(id.clone());
|
||||||
|
while order.len() > KEEP_RESPONSES {
|
||||||
|
if let Some(old) = order.pop_front() {
|
||||||
|
if let Some(b) = map.remove(&old) {
|
||||||
|
if let Some(f) = b.file {
|
||||||
|
let _ = std::fs::remove_file(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
id
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
//! Reloads a collection when its files change outside knock (git pull, an
|
||||||
|
//! editor) and tells the frontend which files changed.
|
||||||
|
|
||||||
|
use crate::state::AppState;
|
||||||
|
use notify::{RecursiveMode, Watcher};
|
||||||
|
use serde::Serialize;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::Duration;
|
||||||
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize)]
|
||||||
|
struct Changed {
|
||||||
|
collection: String,
|
||||||
|
paths: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start(app: &AppHandle, state: &AppState, id: &str, root: &Path) {
|
||||||
|
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<PathBuf>();
|
||||||
|
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||||
|
if let Ok(ev) = res {
|
||||||
|
if matches!(ev.kind, notify::EventKind::Access(_)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for p in ev.paths {
|
||||||
|
let _ = tx.send(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let Ok(mut watcher) = watcher else { return };
|
||||||
|
if watcher.watch(root, RecursiveMode::Recursive).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.watchers.lock().unwrap().insert(id.to_string(), watcher);
|
||||||
|
|
||||||
|
let app = app.clone();
|
||||||
|
let id = id.to_string();
|
||||||
|
let root = root.to_path_buf();
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let Some(first) = rx.recv().await else { return };
|
||||||
|
let mut paths = vec![first];
|
||||||
|
// Debounce: a git checkout touches many files at once.
|
||||||
|
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||||
|
while let Ok(p) = rx.try_recv() {
|
||||||
|
paths.push(p);
|
||||||
|
}
|
||||||
|
let rel: Vec<String> = paths
|
||||||
|
.iter()
|
||||||
|
.filter_map(|p| p.strip_prefix(&root).ok())
|
||||||
|
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||||
|
.filter(|p| {
|
||||||
|
(p.ends_with(".yaml") || p.ends_with(".yml") || !p.contains('.'))
|
||||||
|
&& !p.ends_with(".tmp")
|
||||||
|
&& !p.starts_with(".git")
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if rel.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
if !state.collections.read().unwrap().contains_key(&id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let _ = state.reload(&id);
|
||||||
|
let mut rel = rel;
|
||||||
|
rel.sort();
|
||||||
|
rel.dedup();
|
||||||
|
let _ = app.emit("collection-changed", Changed { collection: id.clone(), paths: rel });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
|
"productName": "knock",
|
||||||
|
"mainBinaryName": "knock-app",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"identifier": "de.joshicodes.knock",
|
||||||
|
"build": {
|
||||||
|
"beforeDevCommand": "npm run dev",
|
||||||
|
"devUrl": "http://localhost:1420",
|
||||||
|
"beforeBuildCommand": "npm run build",
|
||||||
|
"frontendDist": "../dist"
|
||||||
|
},
|
||||||
|
"app": {
|
||||||
|
"withGlobalTauri": false,
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"label": "main",
|
||||||
|
"title": "knock",
|
||||||
|
"width": 1360,
|
||||||
|
"height": 860,
|
||||||
|
"minWidth": 820,
|
||||||
|
"minHeight": 520,
|
||||||
|
"decorations": false,
|
||||||
|
"backgroundColor": "#15181E"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"security": {
|
||||||
|
"csp": "default-src 'self' ipc: http://ipc.localhost; img-src 'self' asset: http://asset.localhost blob: data:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; frame-src blob: data:; connect-src ipc: http://ipc.localhost"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"plugins": {
|
||||||
|
"deep-link": {
|
||||||
|
"desktop": { "schemes": ["knock"] }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"bundle": {
|
||||||
|
"active": true,
|
||||||
|
"targets": ["deb", "rpm", "appimage"],
|
||||||
|
"category": "DeveloperTool",
|
||||||
|
"shortDescription": "API client for REST, GraphQL and WebSocket",
|
||||||
|
"longDescription": "knock is an offline desktop API client that stores collections as plain YAML files.",
|
||||||
|
"license": "MIT",
|
||||||
|
"icon": [
|
||||||
|
"icons/32x32.png",
|
||||||
|
"icons/128x128.png",
|
||||||
|
"icons/[email protected]",
|
||||||
|
"icons/icon.icns",
|
||||||
|
"icons/icon.ico"
|
||||||
|
],
|
||||||
|
"linux": {
|
||||||
|
"deb": { "depends": ["libwebkit2gtk-4.1-0", "libgtk-3-0"] },
|
||||||
|
"rpm": { "depends": ["webkit2gtk4.1"] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { listen } from '@tauri-apps/api/event';
|
||||||
|
import { open as openDialog } from '@tauri-apps/plugin-dialog';
|
||||||
|
import { Toaster, CommandPalette, type Command } from '@joshicodes/cock';
|
||||||
|
import Titlebar from '$lib/views/Titlebar.svelte';
|
||||||
|
import Sidebar from '$lib/views/Sidebar.svelte';
|
||||||
|
import TabStrip from '$lib/views/TabStrip.svelte';
|
||||||
|
import RequestView from '$lib/views/request/RequestView.svelte';
|
||||||
|
import FolderView from '$lib/views/settings/FolderView.svelte';
|
||||||
|
import CollectionSettings from '$lib/views/settings/CollectionSettings.svelte';
|
||||||
|
import EnvironmentView from '$lib/views/settings/EnvironmentView.svelte';
|
||||||
|
import AppSettings from '$lib/views/settings/AppSettings.svelte';
|
||||||
|
import Welcome from '$lib/views/Welcome.svelte';
|
||||||
|
import DialogHost from '$lib/views/dialogs/DialogHost.svelte';
|
||||||
|
import { ws } from '$lib/state/workspace.svelte';
|
||||||
|
import { ui } from '$lib/state/ui.svelte';
|
||||||
|
import { dialogs } from '$lib/state/dialogs.svelte';
|
||||||
|
import { sendTab } from '$lib/send.svelte';
|
||||||
|
import type { TreeNode } from '$lib/types';
|
||||||
|
import { onDeepLink } from '$lib/deeplink';
|
||||||
|
|
||||||
|
let ready = $state(false);
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
ws.restore().finally(() => (ready = true));
|
||||||
|
const un = listen<{ collection: string; paths: string[] }>('collection-changed', (e) => {
|
||||||
|
ws.onDiskChange(e.payload.collection, e.payload.paths);
|
||||||
|
});
|
||||||
|
const unLink = onDeepLink();
|
||||||
|
return () => {
|
||||||
|
un.then((f) => f());
|
||||||
|
unLink.then((f) => f?.());
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ctrl+Enter from inside editors that do not know about tabs.
|
||||||
|
let seenSend = 0;
|
||||||
|
$effect(() => {
|
||||||
|
if (ui.sendRequest !== seenSend) {
|
||||||
|
seenSend = ui.sendRequest;
|
||||||
|
const t = ws.active;
|
||||||
|
if (t?.draft?.type !== 'ws') sendTab(t);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function openCollection() {
|
||||||
|
const dir = await openDialog({ directory: true, title: 'Open collection folder' });
|
||||||
|
if (typeof dir === 'string') await ws.open(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onKey(e: KeyboardEvent) {
|
||||||
|
const mod = e.ctrlKey || e.metaKey;
|
||||||
|
if (!mod) {
|
||||||
|
if (e.key === 'F2' || e.key === 'Escape') return;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const k = e.key.toLowerCase();
|
||||||
|
if (k === 'enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (ws.active?.draft?.type === 'ws') ui.sendRequest += 1;
|
||||||
|
else sendTab();
|
||||||
|
} else if (k === 's' && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
ws.save();
|
||||||
|
} else if (k === 't') {
|
||||||
|
e.preventDefault();
|
||||||
|
ws.newScratch();
|
||||||
|
} else if (k === 'n' && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
ws.newScratch();
|
||||||
|
} else if (k === 'w') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (ws.activeKey) ws.closeTab(ws.activeKey);
|
||||||
|
} else if (k === 'l') {
|
||||||
|
e.preventDefault();
|
||||||
|
ui.focusUrlRequest += 1;
|
||||||
|
} else if (k === 'e') {
|
||||||
|
e.preventDefault();
|
||||||
|
ui.envMenuRequest += 1;
|
||||||
|
} else if (k === 'o') {
|
||||||
|
e.preventDefault();
|
||||||
|
openCollection();
|
||||||
|
} else if (k === 'p' || (k === 'f' && e.shiftKey)) {
|
||||||
|
e.preventDefault();
|
||||||
|
ui.sidebarFilterRequest += 1;
|
||||||
|
} else if (k === 'j' && e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
ui.toggleJsonModeRequest += 1;
|
||||||
|
} else if (k === 'tab') {
|
||||||
|
e.preventDefault();
|
||||||
|
const i = ws.tabs.findIndex((t) => t.key === ws.activeKey);
|
||||||
|
const next = ws.tabs[(i + (e.shiftKey ? -1 : 1) + ws.tabs.length) % ws.tabs.length];
|
||||||
|
if (next) ws.activate(next.key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let commands = $derived.by((): Command[] => {
|
||||||
|
const out: Command[] = [];
|
||||||
|
for (const c of ws.collections) {
|
||||||
|
const walk = (nodes: TreeNode[], path: string) => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
if (n.node === 'folder') walk(n.children, `${path}${n.name} / `);
|
||||||
|
else
|
||||||
|
out.push({
|
||||||
|
id: `req:${c.id}:${n.id}`,
|
||||||
|
label: `${n.type === 'http' ? (n.method ?? 'GET') : n.type.toUpperCase()} ${n.name}`,
|
||||||
|
group: `Requests · ${c.name}`,
|
||||||
|
keywords: [path, n.id],
|
||||||
|
onselect: () => ws.openRequest(c.id, n.id, false)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(c.tree.children, '');
|
||||||
|
for (const e of c.environments) {
|
||||||
|
out.push({
|
||||||
|
id: `env:${c.id}:${e.id}`,
|
||||||
|
label: `Use environment ${e.name}`,
|
||||||
|
group: `Environments · ${c.name}`,
|
||||||
|
onselect: () => ws.setEnv(c.id, e.id)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(
|
||||||
|
{ id: 'a:new', label: 'New request', group: 'Actions', hint: 'Ctrl+T', onselect: () => ws.newScratch() },
|
||||||
|
{ id: 'a:gql', label: 'New GraphQL request', group: 'Actions', onselect: () => ws.newScratch('graphql') },
|
||||||
|
{ id: 'a:ws', label: 'New WebSocket', group: 'Actions', onselect: () => ws.newScratch('ws') },
|
||||||
|
{ id: 'a:open', label: 'Open collection…', group: 'Actions', hint: 'Ctrl+O', onselect: openCollection },
|
||||||
|
{ id: 'a:create', label: 'New collection…', group: 'Actions', onselect: () => dialogs.newCollection() },
|
||||||
|
{ id: 'a:import', label: 'Import from Postman, Bruno, Insomnia, OpenAPI or cURL…', group: 'Actions', onselect: () => dialogs.importer() },
|
||||||
|
{ id: 'a:layout', label: 'Toggle response below / beside', group: 'Actions', onselect: () => ws.setLayout(ws.layout === 'columns' ? 'rows' : 'columns') },
|
||||||
|
{ id: 'a:mask', label: ws.maskSecrets ? 'Show secrets' : 'Mask secrets', group: 'Actions', onselect: () => ws.setMask(!ws.maskSecrets) },
|
||||||
|
{ id: 'a:settings', label: 'Settings', group: 'Actions', onselect: () => ws.openSpecial('settings', null, null, 'Settings') }
|
||||||
|
);
|
||||||
|
if (ws.focusCol) {
|
||||||
|
const col = ws.focusCol;
|
||||||
|
out.push(
|
||||||
|
{ id: 'a:envs', label: 'Manage environments', group: 'Actions', onselect: () => ws.openSpecial('environment', col, ws.env(col) ?? ws.collection(col)?.environments[0]?.id ?? null, 'Environments') },
|
||||||
|
{ id: 'a:run', label: 'Run collection', group: 'Actions', onselect: () => dialogs.runner(col, '') },
|
||||||
|
{ id: 'a:colset', label: 'Collection settings', group: 'Actions', onselect: () => ws.openSpecial('collection', col, null, ws.collection(col)?.name ?? 'Collection') }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Sidebar resize
|
||||||
|
let resizing = false;
|
||||||
|
function startResize(e: PointerEvent) {
|
||||||
|
resizing = true;
|
||||||
|
(e.target as HTMLElement).setPointerCapture(e.pointerId);
|
||||||
|
}
|
||||||
|
function onResize(e: PointerEvent) {
|
||||||
|
if (resizing) ws.setSidebarWidth(Math.max(200, Math.min(560, e.clientX)));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:window onkeydown={onKey} />
|
||||||
|
|
||||||
|
<div class="flex h-full flex-col bg-panel text-fg">
|
||||||
|
<Titlebar />
|
||||||
|
<div class="flex min-h-0 flex-1">
|
||||||
|
<Sidebar />
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
|
<div
|
||||||
|
class="w-1 shrink-0 cursor-col-resize border-r border-line hover:bg-cyan/40"
|
||||||
|
onpointerdown={startResize}
|
||||||
|
onpointermove={onResize}
|
||||||
|
onpointerup={() => (resizing = false)}
|
||||||
|
></div>
|
||||||
|
<main class="flex min-w-0 flex-1 flex-col">
|
||||||
|
{#if ws.tabs.length}
|
||||||
|
<TabStrip />
|
||||||
|
{/if}
|
||||||
|
<div class="min-h-0 flex-1">
|
||||||
|
{#if ws.active}
|
||||||
|
{@const t = ws.active}
|
||||||
|
{#key t.key}
|
||||||
|
{#if t.kind === 'request'}
|
||||||
|
<RequestView tab={t} />
|
||||||
|
{:else if t.kind === 'folder' && t.col && t.id}
|
||||||
|
<FolderView col={t.col} id={t.id} />
|
||||||
|
{:else if t.kind === 'collection' && t.col}
|
||||||
|
<CollectionSettings col={t.col} />
|
||||||
|
{:else if t.kind === 'environment' && t.col}
|
||||||
|
<EnvironmentView col={t.col} bind:env={t.id} />
|
||||||
|
{:else if t.kind === 'settings'}
|
||||||
|
<AppSettings />
|
||||||
|
{/if}
|
||||||
|
{/key}
|
||||||
|
{:else if ready}
|
||||||
|
<Welcome />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CommandPalette bind:open={ws.paletteOpen} {commands} placeholder="Find a request, environment or action" />
|
||||||
|
<DialogHost />
|
||||||
|
<Toaster position="bottom-right" />
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
@import 'tailwindcss';
|
||||||
|
@import '@joshicodes/cock/theme.css';
|
||||||
|
@import '@fontsource/space-grotesk/500.css';
|
||||||
|
@import '@fontsource/space-grotesk/700.css';
|
||||||
|
@import '@fontsource/jetbrains-mono/500.css';
|
||||||
|
|
||||||
|
@source './';
|
||||||
|
|
||||||
|
/* Brand tokens from DESIGN.md. Dark is the reference; light keeps the same
|
||||||
|
roles with values that hold contrast on paper. */
|
||||||
|
:root,
|
||||||
|
[data-ck-theme='light'] {
|
||||||
|
--knock-cyan: #2ec4f1;
|
||||||
|
--knock-cyan-deep: #0b7fad;
|
||||||
|
--on-accent: #101318;
|
||||||
|
|
||||||
|
--k-titlebar: #e8eaee;
|
||||||
|
--k-sidebar: #f2f3f5;
|
||||||
|
--k-panel: #ffffff;
|
||||||
|
--k-input: #f2f3f5;
|
||||||
|
--k-hover: #e6e8ec;
|
||||||
|
--k-line: #dcdfe5;
|
||||||
|
|
||||||
|
--k-text-strong: #101318;
|
||||||
|
--k-text: #1e222a;
|
||||||
|
--k-text-soft: #3a404b;
|
||||||
|
--k-text-muted: #5b6270;
|
||||||
|
--k-text-subtle: #6b7280;
|
||||||
|
|
||||||
|
--method-get: #0b7fad;
|
||||||
|
--method-post: #9a5b00;
|
||||||
|
--method-put: #5b3fd9;
|
||||||
|
--method-patch: #b0307a;
|
||||||
|
--method-delete: #c62828;
|
||||||
|
--status-ok: #1b7f3b;
|
||||||
|
|
||||||
|
--ck-bg: #ffffff;
|
||||||
|
--ck-fg: #1e222a;
|
||||||
|
--ck-accent: #0b7fad;
|
||||||
|
--ck-accent-hover: #096e96;
|
||||||
|
--ck-accent-fg: #ffffff;
|
||||||
|
--ck-tint: 0%;
|
||||||
|
--ck-danger: #c62828;
|
||||||
|
--ck-success: #1b7f3b;
|
||||||
|
--ck-warning: #9a5b00;
|
||||||
|
--ck-font-sans: 'Space Grotesk', system-ui, sans-serif;
|
||||||
|
--ck-font-mono: 'JetBrains Mono', ui-monospace, monospace;
|
||||||
|
--ck-radius-scale: 0.75;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark,
|
||||||
|
[data-ck-theme='dark'] {
|
||||||
|
--k-titlebar: #0e1014;
|
||||||
|
--k-sidebar: #111419;
|
||||||
|
--k-panel: #15181e;
|
||||||
|
--k-input: #1e222a;
|
||||||
|
--k-hover: #232833;
|
||||||
|
--k-line: #232833;
|
||||||
|
|
||||||
|
--k-text-strong: #f4f6f8;
|
||||||
|
--k-text: #e3e7ec;
|
||||||
|
--k-text-soft: #c9ced6;
|
||||||
|
--k-text-muted: #a9b0bc;
|
||||||
|
--k-text-subtle: #8a93a2;
|
||||||
|
|
||||||
|
--method-get: #2ec4f1;
|
||||||
|
--method-post: #f5b85c;
|
||||||
|
--method-put: #b8a1ff;
|
||||||
|
--method-patch: #f59fd0;
|
||||||
|
--method-delete: #ff5c5c;
|
||||||
|
--status-ok: #7cf29a;
|
||||||
|
|
||||||
|
--ck-bg: #15181e;
|
||||||
|
--ck-fg: #e3e7ec;
|
||||||
|
--ck-accent: #2ec4f1;
|
||||||
|
--ck-accent-hover: #5ad2f5;
|
||||||
|
--ck-accent-fg: #101318;
|
||||||
|
--ck-tint: 0%;
|
||||||
|
--ck-danger: #ff5c5c;
|
||||||
|
--ck-success: #7cf29a;
|
||||||
|
--ck-warning: #f5b85c;
|
||||||
|
--ck-code-bg: #1e222a;
|
||||||
|
--ck-code-line: #232833;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cock derives surfaces by mixing; Knock has exact layers, so pin them. */
|
||||||
|
:root,
|
||||||
|
.dark,
|
||||||
|
[data-ck-theme] {
|
||||||
|
--ck-canvas: var(--k-panel);
|
||||||
|
--ck-surface: var(--k-input);
|
||||||
|
--ck-muted: var(--k-hover);
|
||||||
|
--ck-fg-muted: var(--k-text-muted);
|
||||||
|
--ck-fg-subtle: var(--k-text-subtle);
|
||||||
|
}
|
||||||
|
|
||||||
|
@theme inline {
|
||||||
|
--color-titlebar: var(--k-titlebar);
|
||||||
|
--color-sidebar: var(--k-sidebar);
|
||||||
|
--color-panel: var(--k-panel);
|
||||||
|
--color-input: var(--k-input);
|
||||||
|
--color-hover: var(--k-hover);
|
||||||
|
--color-line: var(--k-line);
|
||||||
|
--color-strong: var(--k-text-strong);
|
||||||
|
--color-soft: var(--k-text-soft);
|
||||||
|
--color-get: var(--method-get);
|
||||||
|
--color-post: var(--method-post);
|
||||||
|
--color-put: var(--method-put);
|
||||||
|
--color-patch: var(--method-patch);
|
||||||
|
--color-delete: var(--method-delete);
|
||||||
|
--color-ok: var(--status-ok);
|
||||||
|
--color-cyan: var(--knock-cyan);
|
||||||
|
--color-cyan-deep: var(--knock-cyan-deep);
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
html,
|
||||||
|
body,
|
||||||
|
#app {
|
||||||
|
height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 500;
|
||||||
|
user-select: none;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
input,
|
||||||
|
textarea,
|
||||||
|
[contenteditable],
|
||||||
|
.selectable,
|
||||||
|
.cm-editor {
|
||||||
|
user-select: text;
|
||||||
|
-webkit-user-select: text;
|
||||||
|
}
|
||||||
|
code,
|
||||||
|
pre,
|
||||||
|
.mono {
|
||||||
|
font-family: var(--ck-font-mono);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Section label: COLLECTIONS, HEADERS, … */
|
||||||
|
.k-label {
|
||||||
|
font-size: 10.5px;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--k-text-subtle);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Plain inline field used inside tables and bars. Cock's Input is used for
|
||||||
|
forms; dense editors need something with less chrome. */
|
||||||
|
.k-field {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--k-text);
|
||||||
|
font-family: var(--ck-font-mono);
|
||||||
|
font-size: 12.5px;
|
||||||
|
padding: 4px 6px;
|
||||||
|
border-radius: 3px;
|
||||||
|
outline: none;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
}
|
||||||
|
.k-field:hover {
|
||||||
|
border-color: var(--k-line);
|
||||||
|
}
|
||||||
|
.k-field:focus {
|
||||||
|
border-color: var(--knock-cyan-deep);
|
||||||
|
background: var(--k-input);
|
||||||
|
}
|
||||||
|
.k-field::placeholder {
|
||||||
|
color: var(--k-text-subtle);
|
||||||
|
}
|
||||||
|
|
||||||
|
.k-scroll {
|
||||||
|
overflow: auto;
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: var(--k-hover) transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* CodeMirror chrome follows the panel, not Cock's code panel. */
|
||||||
|
.cm-editor {
|
||||||
|
height: 100%;
|
||||||
|
font-size: 12.5px;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
.cm-editor .cm-scroller {
|
||||||
|
font-family: var(--ck-font-mono);
|
||||||
|
line-height: 1.55;
|
||||||
|
}
|
||||||
|
.cm-editor.cm-focused {
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
.cm-gutters {
|
||||||
|
background: transparent !important;
|
||||||
|
border-right: 1px solid var(--k-line) !important;
|
||||||
|
color: var(--k-text-subtle) !important;
|
||||||
|
}
|
||||||
|
.cm-activeLine,
|
||||||
|
.cm-activeLineGutter {
|
||||||
|
background: color-mix(in oklab, var(--k-hover) 55%, transparent) !important;
|
||||||
|
}
|
||||||
|
.cm-tooltip {
|
||||||
|
background: var(--k-input) !important;
|
||||||
|
border: 1px solid var(--k-line) !important;
|
||||||
|
color: var(--k-text);
|
||||||
|
}
|
||||||
|
.cm-tooltip-autocomplete ul li[aria-selected] {
|
||||||
|
background: var(--ck-accent-soft) !important;
|
||||||
|
color: var(--k-text-strong) !important;
|
||||||
|
}
|
||||||
|
.cm-var {
|
||||||
|
color: var(--knock-cyan);
|
||||||
|
background: color-mix(in oklab, var(--knock-cyan) 12%, transparent);
|
||||||
|
border-radius: 3px;
|
||||||
|
padding: 0 1px;
|
||||||
|
}
|
||||||
|
:where([data-ck-theme='light']) .cm-var,
|
||||||
|
:root:not(.dark) .cm-var {
|
||||||
|
color: var(--knock-cyan-deep);
|
||||||
|
}
|
||||||
|
.cm-var-missing {
|
||||||
|
color: var(--method-delete);
|
||||||
|
background: color-mix(in oklab, var(--method-delete) 12%, transparent);
|
||||||
|
text-decoration: underline wavy color-mix(in oklab, var(--method-delete) 60%, transparent);
|
||||||
|
text-underline-offset: 3px;
|
||||||
|
}
|
||||||
|
.cm-selectionBackground,
|
||||||
|
.cm-content ::selection {
|
||||||
|
background: color-mix(in oklab, var(--knock-cyan) 22%, transparent) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.k-var-tip {
|
||||||
|
padding: 6px 9px;
|
||||||
|
max-width: 420px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.k-var-tip-name {
|
||||||
|
font-family: var(--ck-font-mono);
|
||||||
|
color: var(--k-text-subtle);
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.k-var-tip-value {
|
||||||
|
font-family: var(--ck-font-mono);
|
||||||
|
color: var(--k-text-strong);
|
||||||
|
word-break: break-all;
|
||||||
|
margin: 2px 0;
|
||||||
|
}
|
||||||
|
.k-var-tip-value.missing {
|
||||||
|
color: var(--method-delete);
|
||||||
|
}
|
||||||
|
.k-var-tip-meta {
|
||||||
|
color: var(--k-text-muted);
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import type {
|
||||||
|
CollectionView,
|
||||||
|
CookieInfo,
|
||||||
|
Environment,
|
||||||
|
FolderMeta,
|
||||||
|
HistoryEntry,
|
||||||
|
Manifest,
|
||||||
|
Preview,
|
||||||
|
Request,
|
||||||
|
SendResult,
|
||||||
|
VarInfo
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
export interface ScopeArgs {
|
||||||
|
col: string | null;
|
||||||
|
request_id: string | null;
|
||||||
|
request: Request;
|
||||||
|
env: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EditResult {
|
||||||
|
id: string;
|
||||||
|
collection: CollectionView;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
collectionOpen: (path: string) => invoke<CollectionView>('collection_open', { path }),
|
||||||
|
collectionCreate: (path: string, name: string) =>
|
||||||
|
invoke<CollectionView>('collection_create', { path, name }),
|
||||||
|
collectionGet: (id: string) => invoke<CollectionView>('collection_get', { id }),
|
||||||
|
collectionClose: (id: string) => invoke<void>('collection_close', { id }),
|
||||||
|
recent: () => invoke<string[]>('recent_collections'),
|
||||||
|
recentForget: (path: string) => invoke<void>('recent_forget', { path }),
|
||||||
|
|
||||||
|
requestGet: (col: string, id: string) => invoke<Request>('request_get', { col, id }),
|
||||||
|
requestSave: (col: string, id: string, request: Request) =>
|
||||||
|
invoke<CollectionView>('request_save', { col, id, request }),
|
||||||
|
requestCreate: (col: string, folder: string, request: Request) =>
|
||||||
|
invoke<EditResult>('request_create', { col, folder, request }),
|
||||||
|
folderCreate: (col: string, parent: string, name: string) =>
|
||||||
|
invoke<EditResult>('folder_create', { col, parent, name }),
|
||||||
|
rename: (col: string, id: string, name: string) =>
|
||||||
|
invoke<EditResult>('node_rename', { col, id, name }),
|
||||||
|
duplicate: (col: string, id: string) => invoke<EditResult>('node_duplicate', { col, id }),
|
||||||
|
remove: (col: string, id: string) => invoke<CollectionView>('node_delete', { col, id }),
|
||||||
|
move: (col: string, id: string, folder: string, index: number | null) =>
|
||||||
|
invoke<EditResult>('node_move', { col, id, folder, index }),
|
||||||
|
folderGet: (col: string, id: string) => invoke<FolderMeta>('folder_get', { col, id }),
|
||||||
|
folderSave: (col: string, id: string, meta: FolderMeta) =>
|
||||||
|
invoke<CollectionView>('folder_save', { col, id, meta }),
|
||||||
|
manifestGet: (col: string) => invoke<Manifest>('manifest_get', { col }),
|
||||||
|
manifestSave: (col: string, manifest: Manifest) =>
|
||||||
|
invoke<CollectionView>('manifest_save', { col, manifest }),
|
||||||
|
|
||||||
|
envGet: (col: string, id: string) => invoke<Environment>('env_get', { col, id }),
|
||||||
|
envSave: (col: string, id: string, env: Environment) =>
|
||||||
|
invoke<CollectionView>('env_save', { col, id, env }),
|
||||||
|
envDelete: (col: string, id: string) => invoke<CollectionView>('env_delete', { col, id }),
|
||||||
|
envSecrets: (col: string, env: string) =>
|
||||||
|
invoke<{ name: string; source: 'envvar' | 'keyring' | 'file' | null; value: string | null }[]>(
|
||||||
|
'env_secrets',
|
||||||
|
{ col, env }
|
||||||
|
),
|
||||||
|
secretSet: (
|
||||||
|
col: string,
|
||||||
|
env: string | null,
|
||||||
|
name: string,
|
||||||
|
value: string | null,
|
||||||
|
target: 'keyring' | 'file'
|
||||||
|
) => invoke<void>('secret_set', { col, env, name, value, target }),
|
||||||
|
|
||||||
|
varsList: (args: ScopeArgs) =>
|
||||||
|
invoke<{ vars: VarInfo[]; dynamic: [string, string][] }>('vars_list', { args }),
|
||||||
|
runtimeList: (col: string | null) => invoke<Record<string, string>>('runtime_list', { col }),
|
||||||
|
runtimeSet: (col: string | null, name: string, value: string | null, persist: boolean) =>
|
||||||
|
invoke<void>('runtime_set', { col, name, value, persist }),
|
||||||
|
globalsGet: () => invoke<Record<string, string>>('globals_get'),
|
||||||
|
globalsSave: (vars: Record<string, string>) => invoke<void>('globals_save', { vars }),
|
||||||
|
|
||||||
|
send: (args: ScopeArgs & { tab: string; history_body_limit: number }) =>
|
||||||
|
invoke<SendResult>('request_send', { args }),
|
||||||
|
cancel: (tab: string) => invoke<void>('request_cancel', { tab }),
|
||||||
|
preview: (args: ScopeArgs) => invoke<Preview>('request_preview', { args }),
|
||||||
|
responseBody: (id: string) => invoke<ArrayBuffer>('response_body', { id }),
|
||||||
|
responseSave: (id: string, path: string) => invoke<void>('response_save', { id, path }),
|
||||||
|
|
||||||
|
cookies: (col: string) => invoke<CookieInfo[]>('cookies_list', { col }),
|
||||||
|
cookieDelete: (col: string, c?: { domain: string; path: string; name: string }) =>
|
||||||
|
invoke<void>('cookie_delete', { col, domain: c?.domain, path: c?.path, name: c?.name }),
|
||||||
|
|
||||||
|
history: (query: string, limit?: number) =>
|
||||||
|
invoke<HistoryEntry[]>('history_list', { query, limit }),
|
||||||
|
historyGet: (id: number) =>
|
||||||
|
invoke<{ request: Request; response: SendResult['output']['response']; body_id: string | null }>(
|
||||||
|
'history_get',
|
||||||
|
{ id }
|
||||||
|
),
|
||||||
|
historyDelete: (id: number | null) => invoke<void>('history_delete', { id }),
|
||||||
|
|
||||||
|
settingGet: (key: string) => invoke<string | null>('setting_get', { key }),
|
||||||
|
settingSet: (key: string, value: string) => invoke<void>('setting_set', { key, value }),
|
||||||
|
pathParams: (url: string) => invoke<string[]>('path_params', { url }),
|
||||||
|
version: () => invoke<string>('app_version')
|
||||||
|
};
|
||||||
|
|
||||||
|
export function errorText(e: unknown): string {
|
||||||
|
if (typeof e === 'string') return e;
|
||||||
|
if (e instanceof Error) return e.message;
|
||||||
|
return JSON.stringify(e);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { errorText } from './api';
|
||||||
|
import { normalizeRequest } from './request';
|
||||||
|
import type { Tab } from './state/workspace.svelte';
|
||||||
|
import type { Request } from './types';
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import { toast } from '@joshicodes/cock';
|
||||||
|
|
||||||
|
export function looksLikeCurl(text: string): boolean {
|
||||||
|
return /^\s*curl(\.exe)?\s/i.test(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function parseCurl(text: string): Promise<Request> {
|
||||||
|
return normalizeRequest(await invoke<Request>('import_curl', { text }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pasting a cURL command into the URL bar replaces the whole request. */
|
||||||
|
export async function onPasteCurl(e: ClipboardEvent, tab: Tab) {
|
||||||
|
const text = e.clipboardData?.getData('text/plain') ?? '';
|
||||||
|
if (!looksLikeCurl(text) || !tab.draft) return;
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
try {
|
||||||
|
const parsed = await parseCurl(text);
|
||||||
|
const keep = { name: tab.draft.name };
|
||||||
|
tab.draft = { ...parsed, ...keep };
|
||||||
|
toast.success('Imported cURL command');
|
||||||
|
} catch (err) {
|
||||||
|
toast.error('Could not parse cURL command', { description: errorText(err) });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { onOpenUrl } from '@tauri-apps/plugin-deep-link';
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
|
||||||
|
/** knock://callback?... from an OAuth provider goes to the waiting flow. */
|
||||||
|
export function onDeepLink(): Promise<(() => void) | undefined> {
|
||||||
|
return onOpenUrl((urls) => {
|
||||||
|
for (const url of urls) invoke('oauth_deep_link', { url }).catch(() => {});
|
||||||
|
}).catch(() => undefined);
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { EditorState, type Extension } from '@codemirror/state';
|
||||||
|
import { EditorView } from '@codemirror/view';
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { extensions, type Lang } from './cm';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
value: string;
|
||||||
|
lang?: Lang;
|
||||||
|
readonly?: boolean;
|
||||||
|
singleLine?: boolean;
|
||||||
|
lineNumbers?: boolean;
|
||||||
|
placeholder?: string;
|
||||||
|
vars?: boolean;
|
||||||
|
jsonc?: boolean;
|
||||||
|
class?: string;
|
||||||
|
onsubmit?: () => void;
|
||||||
|
onchange?: (v: string) => void;
|
||||||
|
onview?: (v: EditorView) => void;
|
||||||
|
extra?: Extension[];
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
value = $bindable(),
|
||||||
|
lang = 'text',
|
||||||
|
readonly = false,
|
||||||
|
singleLine = false,
|
||||||
|
lineNumbers = true,
|
||||||
|
placeholder,
|
||||||
|
vars = true,
|
||||||
|
jsonc = false,
|
||||||
|
class: klass = '',
|
||||||
|
onsubmit,
|
||||||
|
onchange,
|
||||||
|
onview,
|
||||||
|
extra
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
let host: HTMLDivElement;
|
||||||
|
let view: EditorView | undefined;
|
||||||
|
let jsoncNow = () => jsonc;
|
||||||
|
|
||||||
|
function build() {
|
||||||
|
view?.destroy();
|
||||||
|
view = new EditorView({
|
||||||
|
parent: host,
|
||||||
|
state: EditorState.create({
|
||||||
|
doc: value ?? '',
|
||||||
|
extensions: [
|
||||||
|
extensions({
|
||||||
|
lang,
|
||||||
|
readonly,
|
||||||
|
singleLine,
|
||||||
|
lineNumbers,
|
||||||
|
placeholder,
|
||||||
|
vars,
|
||||||
|
onSubmit: () => onsubmit?.(),
|
||||||
|
jsonc: () => jsoncNow(),
|
||||||
|
extra
|
||||||
|
}),
|
||||||
|
EditorView.updateListener.of((u) => {
|
||||||
|
if (!u.docChanged) return;
|
||||||
|
const text = u.state.doc.toString();
|
||||||
|
if (text !== value) {
|
||||||
|
value = text;
|
||||||
|
onchange?.(text);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
]
|
||||||
|
})
|
||||||
|
});
|
||||||
|
onview?.(view);
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
build();
|
||||||
|
return () => view?.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Rebuild when the language or mode changes.
|
||||||
|
let shape = $derived(`${lang}|${readonly}|${singleLine}|${lineNumbers}|${vars}`);
|
||||||
|
let lastShape = '';
|
||||||
|
let lastExtra: Extension[] | undefined;
|
||||||
|
$effect(() => {
|
||||||
|
const s = shape;
|
||||||
|
const x = extra;
|
||||||
|
if (!view) return;
|
||||||
|
if ((lastShape && s !== lastShape) || (lastExtra !== undefined && x !== lastExtra)) build();
|
||||||
|
lastShape = s;
|
||||||
|
lastExtra = x;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Push outside changes (tab switch, URL rewrite from the params table) into the editor.
|
||||||
|
$effect(() => {
|
||||||
|
const v = value ?? '';
|
||||||
|
if (view && v !== view.state.doc.toString()) {
|
||||||
|
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: v } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
jsonc;
|
||||||
|
jsoncNow = () => jsonc;
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div bind:this={host} class="k-cm {singleLine ? 'k-cm-line' : 'h-full'} {klass}"></div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.k-cm-line :global(.cm-editor) {
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
.k-cm-line :global(.cm-content) {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.k-cm-line :global(.cm-line) {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.k-cm-line :global(.cm-scroller) {
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
import { autocompletion, closeBrackets, closeBracketsKeymap, completionKeymap, type CompletionContext } from '@codemirror/autocomplete';
|
||||||
|
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
|
||||||
|
import { json, jsonParseLinter } from '@codemirror/lang-json';
|
||||||
|
import { xml } from '@codemirror/lang-xml';
|
||||||
|
import { html } from '@codemirror/lang-html';
|
||||||
|
import { javascript } from '@codemirror/lang-javascript';
|
||||||
|
import {
|
||||||
|
bracketMatching,
|
||||||
|
foldGutter,
|
||||||
|
foldKeymap,
|
||||||
|
HighlightStyle,
|
||||||
|
indentOnInput,
|
||||||
|
syntaxHighlighting
|
||||||
|
} from '@codemirror/language';
|
||||||
|
import { linter, lintGutter, type Diagnostic } from '@codemirror/lint';
|
||||||
|
import { highlightSelectionMatches, search, searchKeymap } from '@codemirror/search';
|
||||||
|
import { EditorState, StateEffect, type Extension } from '@codemirror/state';
|
||||||
|
import {
|
||||||
|
Decoration,
|
||||||
|
EditorView,
|
||||||
|
hoverTooltip,
|
||||||
|
keymap,
|
||||||
|
lineNumbers,
|
||||||
|
MatchDecorator,
|
||||||
|
placeholder as cmPlaceholder,
|
||||||
|
ViewPlugin,
|
||||||
|
type DecorationSet,
|
||||||
|
type ViewUpdate,
|
||||||
|
drawSelection,
|
||||||
|
highlightActiveLine,
|
||||||
|
highlightActiveLineGutter
|
||||||
|
} from '@codemirror/view';
|
||||||
|
import { tags as t } from '@lezer/highlight';
|
||||||
|
import type { VarInfo } from '$lib/types';
|
||||||
|
import { varsStore } from '$lib/state/vars.svelte';
|
||||||
|
|
||||||
|
export type Lang = 'json' | 'jsonc' | 'xml' | 'html' | 'javascript' | 'graphql' | 'text';
|
||||||
|
|
||||||
|
export const highlight = HighlightStyle.define([
|
||||||
|
{ tag: t.propertyName, color: 'var(--method-get)' },
|
||||||
|
{ tag: [t.string, t.special(t.string)], color: 'var(--status-ok)' },
|
||||||
|
{ tag: [t.number, t.integer, t.float], color: 'var(--method-post)' },
|
||||||
|
{ tag: [t.bool, t.null, t.atom], color: 'var(--method-put)' },
|
||||||
|
{ tag: [t.keyword, t.operatorKeyword, t.definitionKeyword, t.modifier], color: 'var(--method-put)' },
|
||||||
|
{ tag: [t.tagName, t.typeName], color: 'var(--method-patch)' },
|
||||||
|
{ tag: [t.attributeName], color: 'var(--method-post)' },
|
||||||
|
{ tag: [t.attributeValue], color: 'var(--status-ok)' },
|
||||||
|
{ tag: [t.comment, t.lineComment, t.blockComment], color: 'var(--k-text-subtle)', fontStyle: 'italic' },
|
||||||
|
{ tag: [t.punctuation, t.bracket, t.separator, t.brace, t.squareBracket], color: 'var(--k-text-muted)' },
|
||||||
|
{ tag: [t.variableName, t.function(t.variableName)], color: 'var(--k-text)' },
|
||||||
|
{ tag: t.invalid, color: 'var(--method-delete)' }
|
||||||
|
]);
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- variables
|
||||||
|
|
||||||
|
export const refreshVars = StateEffect.define<null>();
|
||||||
|
|
||||||
|
function isDefined(name: string, vars: Map<string, VarInfo>): boolean {
|
||||||
|
if (name.startsWith('$')) return true;
|
||||||
|
if (name.startsWith('secret.') || name.startsWith('oauth.')) return true;
|
||||||
|
return vars.has(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isMissing(name: string): boolean {
|
||||||
|
return varsStore.ready && !isDefined(name, varsStore.map);
|
||||||
|
}
|
||||||
|
|
||||||
|
const varMatcher = new MatchDecorator({
|
||||||
|
regexp: /\{\{\s*([^{}]+?)\s*\}\}/g,
|
||||||
|
decoration: (m) =>
|
||||||
|
Decoration.mark({
|
||||||
|
class: isMissing(m[1]) ? 'cm-var-missing' : 'cm-var',
|
||||||
|
attributes: { 'data-var': m[1] }
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Editors that want a redraw when the variable set changes. */
|
||||||
|
export const liveViews = new Set<EditorView>();
|
||||||
|
|
||||||
|
const varHighlighter = ViewPlugin.fromClass(
|
||||||
|
class {
|
||||||
|
decorations: DecorationSet;
|
||||||
|
constructor(readonly view: EditorView) {
|
||||||
|
this.decorations = varMatcher.createDeco(view);
|
||||||
|
liveViews.add(view);
|
||||||
|
}
|
||||||
|
update(u: ViewUpdate) {
|
||||||
|
if (u.transactions.some((tr) => tr.effects.some((e) => e.is(refreshVars)))) {
|
||||||
|
this.decorations = varMatcher.createDeco(u.view);
|
||||||
|
} else {
|
||||||
|
this.decorations = varMatcher.updateDeco(u, this.decorations);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
destroy() {
|
||||||
|
liveViews.delete(this.view);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ decorations: (v) => v.decorations }
|
||||||
|
);
|
||||||
|
|
||||||
|
export function redrawVars() {
|
||||||
|
for (const v of liveViews) v.dispatch({ effects: refreshVars.of(null) });
|
||||||
|
}
|
||||||
|
|
||||||
|
const varHover = hoverTooltip((view, pos) => {
|
||||||
|
const line = view.state.doc.lineAt(pos);
|
||||||
|
const re = /\{\{\s*([^{}]+?)\s*\}\}/g;
|
||||||
|
let m: RegExpExecArray | null;
|
||||||
|
while ((m = re.exec(line.text))) {
|
||||||
|
const from = line.from + m.index;
|
||||||
|
const to = from + m[0].length;
|
||||||
|
if (pos < from || pos > to) continue;
|
||||||
|
const name = m[1];
|
||||||
|
return {
|
||||||
|
pos: from,
|
||||||
|
end: to,
|
||||||
|
above: true,
|
||||||
|
create: () => ({ dom: varTooltip(name) })
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
export function varTooltip(name: string): HTMLElement {
|
||||||
|
const dom = document.createElement('div');
|
||||||
|
dom.className = 'k-var-tip';
|
||||||
|
const info = varsStore.map.get(name);
|
||||||
|
const title = document.createElement('div');
|
||||||
|
title.className = 'k-var-tip-name';
|
||||||
|
title.textContent = name;
|
||||||
|
dom.append(title);
|
||||||
|
const val = document.createElement('div');
|
||||||
|
val.className = 'k-var-tip-value';
|
||||||
|
const meta = document.createElement('div');
|
||||||
|
meta.className = 'k-var-tip-meta';
|
||||||
|
if (name.startsWith('$')) {
|
||||||
|
val.textContent = varsStore.dynamic.find(([n]) => name.startsWith(n.replace('(...)', '')))?.[1] ?? 'dynamic value';
|
||||||
|
meta.textContent = 'generated when sent';
|
||||||
|
} else if (name.startsWith('secret.')) {
|
||||||
|
val.textContent = '••••••';
|
||||||
|
meta.textContent = 'secret, from keyring or secrets file';
|
||||||
|
} else if (name.startsWith('oauth.')) {
|
||||||
|
val.textContent = 'token from the OAuth store';
|
||||||
|
meta.textContent = 'oauth';
|
||||||
|
} else if (!info) {
|
||||||
|
val.textContent = 'not defined';
|
||||||
|
val.classList.add('missing');
|
||||||
|
meta.textContent = varsStore.ready ? 'will be sent as literal text' : '';
|
||||||
|
} else {
|
||||||
|
val.textContent = info.secret && varsStore.mask ? '••••••' : info.value ?? '';
|
||||||
|
meta.textContent = `${info.scope}${info.source && info.source !== info.scope ? ' · ' + info.source : ''}${info.problem ? ' · ' + info.problem : ''}`;
|
||||||
|
}
|
||||||
|
dom.append(val, meta);
|
||||||
|
return dom;
|
||||||
|
}
|
||||||
|
|
||||||
|
function varCompletions(ctx: CompletionContext) {
|
||||||
|
const before = ctx.matchBefore(/\{\{[\w.$-]*/);
|
||||||
|
if (!before) return null;
|
||||||
|
const options = [
|
||||||
|
...[...varsStore.map.values()].map((v) => ({
|
||||||
|
label: v.name,
|
||||||
|
detail: v.scope ?? '',
|
||||||
|
info: v.secret && varsStore.mask ? '••••••' : (v.value ?? ''),
|
||||||
|
apply: v.name + '}}',
|
||||||
|
type: 'variable'
|
||||||
|
})),
|
||||||
|
...varsStore.dynamic.map(([n, d]) => ({
|
||||||
|
label: n,
|
||||||
|
detail: 'dynamic',
|
||||||
|
info: d,
|
||||||
|
apply: (n.endsWith('(...)') ? n.replace('...', '') : n) + '}}',
|
||||||
|
type: 'function'
|
||||||
|
}))
|
||||||
|
];
|
||||||
|
return { from: before.from + 2, options, validFor: /^[\w.$-]*$/ };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function variables(): Extension {
|
||||||
|
return [varHighlighter, varHover];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- json lint
|
||||||
|
|
||||||
|
/** Lints JSON after replacing `{{var}}` placeholders so templates stay valid. */
|
||||||
|
function templateJsonLinter(jsonc: () => boolean) {
|
||||||
|
const base = jsonParseLinter();
|
||||||
|
return (view: EditorView): Diagnostic[] => {
|
||||||
|
const text = view.state.doc.toString();
|
||||||
|
if (!text.trim()) return [];
|
||||||
|
const masked = maskTemplate(text, jsonc());
|
||||||
|
if (masked === text) return base(view);
|
||||||
|
const tmp = new EditorView({ state: EditorState.create({ doc: masked }) });
|
||||||
|
try {
|
||||||
|
return base(tmp);
|
||||||
|
} finally {
|
||||||
|
tmp.destroy();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same length as the input, so diagnostic positions still line up. */
|
||||||
|
export function maskTemplate(text: string, jsonc: boolean): string {
|
||||||
|
let out = text.replace(/\{\{[^{}]*\}\}/g, (m, offset: number) => {
|
||||||
|
// Inside a string keep characters; bare placeholder becomes a number.
|
||||||
|
const before = text.slice(0, offset);
|
||||||
|
const quotes = (before.match(/(?<!\\)"/g) ?? []).length;
|
||||||
|
if (quotes % 2 === 1) return 'x'.repeat(m.length);
|
||||||
|
return '0'.padEnd(m.length, ' ');
|
||||||
|
});
|
||||||
|
if (jsonc) {
|
||||||
|
out = out
|
||||||
|
.replace(/\/\/[^\n]*/g, (m) => ' '.repeat(m.length))
|
||||||
|
.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '))
|
||||||
|
.replace(/,(\s*[}\]])/g, ' $1');
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- assemble
|
||||||
|
|
||||||
|
export interface EditorOptions {
|
||||||
|
lang: Lang;
|
||||||
|
readonly?: boolean;
|
||||||
|
singleLine?: boolean;
|
||||||
|
lineNumbers?: boolean;
|
||||||
|
placeholder?: string;
|
||||||
|
vars?: boolean;
|
||||||
|
onSubmit?: () => void;
|
||||||
|
jsonc?: () => boolean;
|
||||||
|
extra?: Extension[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function language(lang: Lang): Extension {
|
||||||
|
switch (lang) {
|
||||||
|
case 'json':
|
||||||
|
case 'jsonc':
|
||||||
|
return json();
|
||||||
|
case 'xml':
|
||||||
|
return xml();
|
||||||
|
case 'html':
|
||||||
|
return html();
|
||||||
|
case 'javascript':
|
||||||
|
return javascript();
|
||||||
|
default:
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extensions(o: EditorOptions): Extension[] {
|
||||||
|
const ext: Extension[] = [
|
||||||
|
syntaxHighlighting(highlight),
|
||||||
|
language(o.lang),
|
||||||
|
drawSelection(),
|
||||||
|
EditorView.lineWrapping
|
||||||
|
];
|
||||||
|
if (o.singleLine) {
|
||||||
|
ext.push(
|
||||||
|
EditorState.transactionFilter.of((tr) => (tr.newDoc.lines > 1 ? [] : tr)),
|
||||||
|
EditorView.domEventHandlers({
|
||||||
|
paste: (e, view) => {
|
||||||
|
const text = e.clipboardData?.getData('text/plain');
|
||||||
|
if (text && text.includes('\n')) {
|
||||||
|
e.preventDefault();
|
||||||
|
view.dispatch(view.state.replaceSelection(text.replace(/\s*\n\s*/g, ' ')));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
ext.push(
|
||||||
|
history(),
|
||||||
|
bracketMatching(),
|
||||||
|
closeBrackets(),
|
||||||
|
indentOnInput(),
|
||||||
|
highlightSelectionMatches(),
|
||||||
|
search({ top: true }),
|
||||||
|
keymap.of([...closeBracketsKeymap, ...searchKeymap, ...foldKeymap, ...historyKeymap, indentWithTab])
|
||||||
|
);
|
||||||
|
if (o.lineNumbers !== false) {
|
||||||
|
ext.push(lineNumbers(), foldGutter(), highlightActiveLine(), highlightActiveLineGutter());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (o.singleLine) ext.push(history(), keymap.of(historyKeymap));
|
||||||
|
ext.push(keymap.of([...completionKeymap, ...defaultKeymap]));
|
||||||
|
if (o.onSubmit) {
|
||||||
|
const submit = o.onSubmit;
|
||||||
|
ext.unshift(
|
||||||
|
keymap.of([
|
||||||
|
{
|
||||||
|
key: 'Mod-Enter',
|
||||||
|
run: () => {
|
||||||
|
submit();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
...(o.singleLine
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
key: 'Enter',
|
||||||
|
run: () => {
|
||||||
|
submit();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
: [])
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (o.placeholder) ext.push(cmPlaceholder(o.placeholder));
|
||||||
|
if (o.readonly) ext.push(EditorState.readOnly.of(true), EditorView.editable.of(true));
|
||||||
|
if (o.vars !== false) {
|
||||||
|
ext.push(variables(), autocompletion({ override: [varCompletions], icons: false }));
|
||||||
|
}
|
||||||
|
if ((o.lang === 'json' || o.lang === 'jsonc') && !o.readonly) {
|
||||||
|
ext.push(lintGutter(), linter(templateJsonLinter(o.jsonc ?? (() => o.lang === 'jsonc')), { delay: 300 }));
|
||||||
|
}
|
||||||
|
if (o.extra) ext.push(...o.extra);
|
||||||
|
return ext;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/**
|
||||||
|
* Subsequence match with a score that prefers contiguous runs and word starts.
|
||||||
|
* Returns null when not every query character occurs in order.
|
||||||
|
*/
|
||||||
|
export function fuzzy(query: string, text: string): { score: number; hits: number[] } | null {
|
||||||
|
const q = query.toLowerCase().replace(/\s+/g, '');
|
||||||
|
if (!q) return { score: 0, hits: [] };
|
||||||
|
const s = text.toLowerCase();
|
||||||
|
const hits: number[] = [];
|
||||||
|
let score = 0;
|
||||||
|
let qi = 0;
|
||||||
|
let prev = -2;
|
||||||
|
for (let i = 0; i < s.length && qi < q.length; i++) {
|
||||||
|
if (s[i] !== q[qi]) continue;
|
||||||
|
hits.push(i);
|
||||||
|
const wordStart = i === 0 || /[\s/_\-.:]/.test(s[i - 1]);
|
||||||
|
score += 1 + (i === prev + 1 ? 3 : 0) + (wordStart ? 2 : 0);
|
||||||
|
prev = i;
|
||||||
|
qi++;
|
||||||
|
}
|
||||||
|
if (qi < q.length) return null;
|
||||||
|
// Shorter texts with the same hits rank higher.
|
||||||
|
return { score: score - s.length * 0.01, hits };
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
export const HEADER_NAMES = [
|
||||||
|
'Accept',
|
||||||
|
'Accept-Encoding',
|
||||||
|
'Accept-Language',
|
||||||
|
'Authorization',
|
||||||
|
'Cache-Control',
|
||||||
|
'Connection',
|
||||||
|
'Content-Encoding',
|
||||||
|
'Content-Type',
|
||||||
|
'Cookie',
|
||||||
|
'DNT',
|
||||||
|
'Forwarded',
|
||||||
|
'Host',
|
||||||
|
'If-Match',
|
||||||
|
'If-Modified-Since',
|
||||||
|
'If-None-Match',
|
||||||
|
'Origin',
|
||||||
|
'Pragma',
|
||||||
|
'Prefer',
|
||||||
|
'Range',
|
||||||
|
'Referer',
|
||||||
|
'User-Agent',
|
||||||
|
'X-API-Key',
|
||||||
|
'X-Correlation-ID',
|
||||||
|
'X-Forwarded-For',
|
||||||
|
'X-Forwarded-Host',
|
||||||
|
'X-Forwarded-Proto',
|
||||||
|
'X-Request-ID',
|
||||||
|
'X-Requested-With'
|
||||||
|
];
|
||||||
|
|
||||||
|
const MIME = [
|
||||||
|
'application/json',
|
||||||
|
'application/xml',
|
||||||
|
'application/x-www-form-urlencoded',
|
||||||
|
'multipart/form-data',
|
||||||
|
'text/plain',
|
||||||
|
'text/html',
|
||||||
|
'text/csv',
|
||||||
|
'application/octet-stream',
|
||||||
|
'application/graphql-response+json',
|
||||||
|
'application/problem+json',
|
||||||
|
'*/*'
|
||||||
|
];
|
||||||
|
|
||||||
|
export function headerValues(name: string): string[] {
|
||||||
|
switch (name.toLowerCase()) {
|
||||||
|
case 'accept':
|
||||||
|
case 'content-type':
|
||||||
|
return MIME;
|
||||||
|
case 'accept-encoding':
|
||||||
|
return ['gzip, deflate, br, zstd', 'gzip', 'identity'];
|
||||||
|
case 'cache-control':
|
||||||
|
return ['no-cache', 'no-store', 'max-age=0', 'must-revalidate'];
|
||||||
|
case 'connection':
|
||||||
|
return ['keep-alive', 'close'];
|
||||||
|
case 'authorization':
|
||||||
|
return ['Bearer {{token}}', 'Basic '];
|
||||||
|
case 'prefer':
|
||||||
|
return ['return=minimal', 'return=representation', 'respond-async'];
|
||||||
|
case 'accept-language':
|
||||||
|
return ['en-US,en;q=0.9', 'de-DE,de;q=0.9'];
|
||||||
|
default:
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Modal, Button, toast } from '@joshicodes/cock';
|
||||||
|
import CodeEditor from '$lib/editor/CodeEditor.svelte';
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import JsonForm from './JsonForm.svelte';
|
||||||
|
import { detectIndent, hasComments, parse, ParseError, serialize, type JNode } from './ast';
|
||||||
|
import type { Schema } from './schema';
|
||||||
|
import type { Tab } from '$lib/state/workspace.svelte';
|
||||||
|
import { ui } from '$lib/state/ui.svelte';
|
||||||
|
import { responseText } from '$lib/response';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
text: string;
|
||||||
|
jsonc?: boolean;
|
||||||
|
tab?: Tab;
|
||||||
|
/** Hide the schema and response helpers (used for GraphQL variables, WS messages). */
|
||||||
|
compact?: boolean;
|
||||||
|
}
|
||||||
|
let { text = $bindable(), jsonc = $bindable(false), tab, compact = false }: Props = $props();
|
||||||
|
|
||||||
|
let mode = $state<'form' | 'code'>((localStorage.getItem('knock.jsonMode') as 'form' | 'code') ?? 'form');
|
||||||
|
let tree = $state<JNode | null>(null);
|
||||||
|
let error = $state<ParseError | null>(null);
|
||||||
|
let lastText: string | null = null;
|
||||||
|
let allowCommentLoss = $state(false);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
localStorage.setItem('knock.jsonMode', mode);
|
||||||
|
});
|
||||||
|
|
||||||
|
let seenToggle = ui.toggleJsonModeRequest;
|
||||||
|
$effect(() => {
|
||||||
|
if (ui.toggleJsonModeRequest !== seenToggle) {
|
||||||
|
seenToggle = ui.toggleJsonModeRequest;
|
||||||
|
mode = mode === 'form' ? 'code' : 'form';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Re-parse only when the text changed from outside the form.
|
||||||
|
$effect(() => {
|
||||||
|
const t = text ?? '';
|
||||||
|
if (t === lastText) return;
|
||||||
|
lastText = t;
|
||||||
|
try {
|
||||||
|
tree = parse(t, { comments: jsonc || hasComments(t) });
|
||||||
|
error = null;
|
||||||
|
} catch (e) {
|
||||||
|
error = e instanceof ParseError ? e : new ParseError(String(e), 0, 1, 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let commentsPresent = $derived(hasComments(text ?? ''));
|
||||||
|
let formLocked = $derived(!!error || (commentsPresent && !allowCommentLoss));
|
||||||
|
|
||||||
|
function fromForm() {
|
||||||
|
const next = serialize(tree, detectIndent(text ?? ''));
|
||||||
|
lastText = next;
|
||||||
|
text = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function format(indent: string) {
|
||||||
|
try {
|
||||||
|
const t = parse(text ?? '', { comments: true });
|
||||||
|
const next = serialize(t, indent);
|
||||||
|
text = next;
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Cannot format invalid JSON', { description: String((e as Error).message) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fromResponse() {
|
||||||
|
const body = tab ? responseText(tab) : null;
|
||||||
|
if (!body) return toast.info('Send the request first; the last response is used.');
|
||||||
|
try {
|
||||||
|
const t = parse(body);
|
||||||
|
text = serialize(t, ' ');
|
||||||
|
} catch {
|
||||||
|
toast.error('The last response is not JSON');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ schema
|
||||||
|
|
||||||
|
let schemaOpen = $state(false);
|
||||||
|
let schemaText = $state('');
|
||||||
|
let schema = $derived.by((): Schema | null => {
|
||||||
|
const s = tab?.draft?.schema;
|
||||||
|
return s && typeof s === 'object' && !Array.isArray(s) ? (s as Schema) : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
function openSchema() {
|
||||||
|
schemaText = schema ? JSON.stringify(schema, null, 2) : '';
|
||||||
|
schemaOpen = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveSchema() {
|
||||||
|
if (!tab?.draft) return;
|
||||||
|
if (!schemaText.trim()) {
|
||||||
|
tab.draft.schema = undefined;
|
||||||
|
schemaOpen = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const s = JSON.parse(schemaText);
|
||||||
|
tab.draft.schema = s;
|
||||||
|
schemaOpen = false;
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Schema is not valid JSON', { description: (e as Error).message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="flex h-full flex-col">
|
||||||
|
<div class="flex shrink-0 items-center gap-1 border-b border-line px-3 py-1">
|
||||||
|
<div class="flex rounded border border-line p-0.5" role="radiogroup" aria-label="Editor">
|
||||||
|
<button role="radio" aria-checked={mode === 'form'} class="rounded-sm px-2 py-0.5 text-[12px] {mode === 'form' ? 'bg-hover text-strong' : 'text-fg-muted hover:text-fg'}" onclick={() => (mode = 'form')}>Form</button>
|
||||||
|
<button role="radio" aria-checked={mode === 'code'} class="rounded-sm px-2 py-0.5 text-[12px] {mode === 'code' ? 'bg-hover text-strong' : 'text-fg-muted hover:text-fg'}" onclick={() => (mode = 'code')}>Code</button>
|
||||||
|
</div>
|
||||||
|
<span class="ml-1 text-[11px] text-fg-subtle">Ctrl+Shift+J</span>
|
||||||
|
<span class="flex-1"></span>
|
||||||
|
{#if mode === 'code'}
|
||||||
|
<label class="flex items-center gap-1.5 px-1.5 text-[12px] text-fg-muted" title="Allow // and /* */ comments; they are stripped before sending">
|
||||||
|
<input type="checkbox" class="size-3.5 accent-[var(--knock-cyan)]" bind:checked={jsonc} /> Comments
|
||||||
|
</label>
|
||||||
|
<button class="rounded px-2 py-0.5 text-[12px] text-fg-muted hover:bg-hover hover:text-fg" onclick={() => format(' ')}>Format</button>
|
||||||
|
<button class="rounded px-2 py-0.5 text-[12px] text-fg-muted hover:bg-hover hover:text-fg" onclick={() => format('')}>Minify</button>
|
||||||
|
{/if}
|
||||||
|
{#if !compact}
|
||||||
|
<button class="rounded px-2 py-0.5 text-[12px] text-fg-muted hover:bg-hover hover:text-fg" onclick={fromResponse} title="Use the last response as body">From response</button>
|
||||||
|
<button class="flex items-center gap-1 rounded px-2 py-0.5 text-[12px] {schema ? 'text-accent' : 'text-fg-muted'} hover:bg-hover hover:text-fg" onclick={openSchema}>
|
||||||
|
Schema{#if schema}<Icon name="check" size={11} />{/if}
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="relative min-h-0 flex-1">
|
||||||
|
{#if mode === 'code'}
|
||||||
|
<CodeEditor bind:value={text} lang={jsonc ? 'jsonc' : 'json'} {jsonc} onsubmit={() => (ui.sendRequest += 1)} />
|
||||||
|
{:else if formLocked}
|
||||||
|
<div class="p-4">
|
||||||
|
{#if error}
|
||||||
|
<p class="text-delete">The body is not valid JSON: {error.message}.</p>
|
||||||
|
<p class="mt-1 text-fg-muted">Fix it in the code view; the form comes back as soon as it parses.</p>
|
||||||
|
<button class="mt-3 rounded border border-line bg-input px-3 py-1.5 hover:border-border-strong" onclick={() => (mode = 'code')}>Open code view</button>
|
||||||
|
{:else}
|
||||||
|
<p class="text-fg">This body has comments.</p>
|
||||||
|
<p class="mt-1 text-fg-muted">The form cannot keep comments. Editing here removes them from the text.</p>
|
||||||
|
<div class="mt-3 flex gap-2">
|
||||||
|
<button class="rounded border border-line bg-input px-3 py-1.5 hover:border-border-strong" onclick={() => (mode = 'code')}>Keep comments, use code view</button>
|
||||||
|
<button class="rounded px-3 py-1.5 text-fg-muted hover:text-fg" onclick={() => (allowCommentLoss = true)}>Edit in form anyway</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{#if error}
|
||||||
|
<div class="pointer-events-none absolute inset-0 top-28 opacity-30">
|
||||||
|
<div class="mono whitespace-pre p-4 text-[12px] text-fg-subtle">{(text ?? '').slice(0, 2000)}</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<div class="k-scroll h-full">
|
||||||
|
<JsonForm bind:root={tree} {schema} onchange={fromForm} />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Modal bind:open={schemaOpen} title="Body schema" description="Paste a JSON Schema (or an OpenAPI schema object). The form then suggests fields, marks required ones, offers enums and validates while you type." size="lg">
|
||||||
|
<div class="h-[50vh] rounded border border-line">
|
||||||
|
<CodeEditor bind:value={schemaText} lang="json" vars={false} />
|
||||||
|
</div>
|
||||||
|
{#snippet footer()}
|
||||||
|
<div class="flex w-full items-center gap-2">
|
||||||
|
{#if schema}<Button variant="ghost" onclick={() => ((schemaText = ''), saveSchema())}>Remove schema</Button>{/if}
|
||||||
|
<span class="flex-1"></span>
|
||||||
|
<Button variant="ghost" onclick={() => (schemaOpen = false)}>Cancel</Button>
|
||||||
|
<Button onclick={saveSchema}>Use schema</Button>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</Modal>
|
||||||
@@ -0,0 +1,452 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { ContextMenu, MenuItem, MenuSeparator, Popover, Switch, toast } from '@joshicodes/cock';
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import VarInput from '$lib/ui/VarInput.svelte';
|
||||||
|
import { dialogs } from '$lib/state/dialogs.svelte';
|
||||||
|
import {
|
||||||
|
KINDS,
|
||||||
|
clone,
|
||||||
|
convert,
|
||||||
|
empty,
|
||||||
|
fromValue,
|
||||||
|
nid,
|
||||||
|
parse,
|
||||||
|
pathTo,
|
||||||
|
serialize,
|
||||||
|
type JEntry,
|
||||||
|
type JNode,
|
||||||
|
type Kind
|
||||||
|
} from './ast';
|
||||||
|
import { SchemaCtx, validate, type Schema } from './schema';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
root: JNode | null;
|
||||||
|
schema?: Schema | null;
|
||||||
|
onchange: () => void;
|
||||||
|
}
|
||||||
|
let { root = $bindable(), schema = null, onchange }: Props = $props();
|
||||||
|
|
||||||
|
let collapsed = $state(new Set<number>());
|
||||||
|
let ctx = $derived(schema ? new SchemaCtx(schema) : null);
|
||||||
|
let issues = $derived(ctx && root ? validate(ctx, root) : null);
|
||||||
|
|
||||||
|
interface Row {
|
||||||
|
node: JNode;
|
||||||
|
entry: JEntry | null;
|
||||||
|
parent: JNode | null;
|
||||||
|
index: number;
|
||||||
|
depth: number;
|
||||||
|
schema: Schema | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
let rows = $derived.by(() => {
|
||||||
|
const out: Row[] = [];
|
||||||
|
const walk = (node: JNode, entry: JEntry | null, parent: JNode | null, index: number, depth: number, s: Schema | undefined) => {
|
||||||
|
out.push({ node, entry, parent, index, depth, schema: s });
|
||||||
|
if (collapsed.has(node.id)) return;
|
||||||
|
if (node.kind === 'object') node.entries.forEach((e, i) => walk(e.value, e, node, i, depth + 1, ctx?.child(s, e.key)));
|
||||||
|
else if (node.kind === 'array') node.items.forEach((it, i) => walk(it, null, node, i, depth + 1, ctx?.child(s, i)));
|
||||||
|
};
|
||||||
|
if (root) walk(root, null, null, 0, 0, ctx?.resolve(ctx.root));
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
|
||||||
|
function changed() {
|
||||||
|
onchange();
|
||||||
|
}
|
||||||
|
|
||||||
|
function replaceNode(r: Row, next: JNode) {
|
||||||
|
if (!r.parent) root = next;
|
||||||
|
else if (r.parent.kind === 'object') r.parent.entries[r.index].value = next;
|
||||||
|
else if (r.parent.kind === 'array') r.parent.items[r.index] = next;
|
||||||
|
changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setKind(r: Row, kind: Kind) {
|
||||||
|
const res = convert(r.node, kind);
|
||||||
|
if (res.loss && !(await dialogs.confirm('Change type?', res.loss, 'Change anyway'))) return;
|
||||||
|
replaceNode(r, res.node);
|
||||||
|
}
|
||||||
|
|
||||||
|
let focusId = $state<number | null>(null);
|
||||||
|
function focusKey(node: HTMLElement, id: number) {
|
||||||
|
if (focusId === id) {
|
||||||
|
queueMicrotask(() => node.querySelector('input')?.focus());
|
||||||
|
focusId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertAfter(r: Row, kind: Kind = 'string', key = '') {
|
||||||
|
if (!r.parent) return addChild(r, kind, key);
|
||||||
|
const node = empty(kind);
|
||||||
|
if (r.parent.kind === 'object') {
|
||||||
|
const entry = { id: nid(), key, value: node };
|
||||||
|
r.parent.entries.splice(r.index + 1, 0, entry);
|
||||||
|
} else if (r.parent.kind === 'array') {
|
||||||
|
r.parent.items.splice(r.index + 1, 0, node);
|
||||||
|
}
|
||||||
|
focusId = node.id;
|
||||||
|
changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
function addChild(r: Row, kind: Kind = 'string', key = '', value?: JNode) {
|
||||||
|
const node = value ?? empty(kind);
|
||||||
|
if (r.node.kind === 'object') r.node.entries.push({ id: nid(), key, value: node });
|
||||||
|
else if (r.node.kind === 'array') r.node.items.push(node);
|
||||||
|
else return;
|
||||||
|
collapsed.delete(r.node.id);
|
||||||
|
collapsed = new Set(collapsed);
|
||||||
|
focusId = node.id;
|
||||||
|
changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
function addSuggested(r: Row, key: string) {
|
||||||
|
const s = ctx?.child(r.schema, key);
|
||||||
|
addChild(r, 'string', key, fromValue(ctx?.sample(s) ?? ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
function duplicate(r: Row) {
|
||||||
|
if (!r.parent) return;
|
||||||
|
const copy = clone(r.node);
|
||||||
|
if (r.parent.kind === 'object') r.parent.entries.splice(r.index + 1, 0, { id: nid(), key: r.entry!.key, value: copy });
|
||||||
|
else if (r.parent.kind === 'array') r.parent.items.splice(r.index + 1, 0, copy);
|
||||||
|
changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
function remove(r: Row) {
|
||||||
|
if (!r.parent) {
|
||||||
|
root = null;
|
||||||
|
} else if (r.parent.kind === 'object') r.parent.entries.splice(r.index, 1);
|
||||||
|
else if (r.parent.kind === 'array') r.parent.items.splice(r.index, 1);
|
||||||
|
changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pasteChild(r: Row) {
|
||||||
|
const text = await navigator.clipboard.readText().catch(() => '');
|
||||||
|
let node: JNode | null = null;
|
||||||
|
try {
|
||||||
|
node = parse(text, { comments: true });
|
||||||
|
} catch {
|
||||||
|
node = text ? { id: nid(), kind: 'string', value: text } : null;
|
||||||
|
}
|
||||||
|
if (!node) return;
|
||||||
|
const target = r.node.kind === 'object' || r.node.kind === 'array' ? r : null;
|
||||||
|
if (!target) {
|
||||||
|
replaceNode(r, { ...node, id: r.node.id });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (r.node.kind === 'object' && node.kind === 'object') {
|
||||||
|
// Merge keys into the object instead of nesting it under an empty key.
|
||||||
|
for (const e of node.entries) r.node.entries.push(e);
|
||||||
|
changed();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
addChild(r, 'string', r.node.kind === 'object' ? 'pasted' : '', node);
|
||||||
|
}
|
||||||
|
|
||||||
|
function copy(text: string) {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
toast.success('Copied');
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------- drag
|
||||||
|
|
||||||
|
let drag = $state<Row | null>(null);
|
||||||
|
let dropTarget = $state<{ id: number; after: boolean } | null>(null);
|
||||||
|
|
||||||
|
function onDrop(r: Row) {
|
||||||
|
const d = drag;
|
||||||
|
const t = dropTarget;
|
||||||
|
drag = null;
|
||||||
|
dropTarget = null;
|
||||||
|
if (!d || !t || !d.parent || d.parent !== r.parent || d.node.id === r.node.id) return;
|
||||||
|
const list: unknown[] = d.parent.kind === 'object' ? d.parent.entries : d.parent.kind === 'array' ? d.parent.items : [];
|
||||||
|
const [moved] = list.splice(d.index, 1);
|
||||||
|
let to = list.indexOf(r.parent!.kind === 'object' ? r.entry : r.node);
|
||||||
|
if (t.after) to += 1;
|
||||||
|
list.splice(to, 0, moved);
|
||||||
|
changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------- display
|
||||||
|
|
||||||
|
function summary(n: JNode) {
|
||||||
|
if (n.kind === 'object') return `${n.entries.length} ${n.entries.length === 1 ? 'key' : 'keys'}`;
|
||||||
|
if (n.kind === 'array') return `${n.items.length} ${n.items.length === 1 ? 'item' : 'items'}`;
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function enumOf(r: Row): unknown[] | null {
|
||||||
|
const s = ctx?.resolve(r.schema);
|
||||||
|
return s?.enum?.length ? s.enum : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function suggestions(r: Row): string[] {
|
||||||
|
if (!ctx || r.node.kind !== 'object') return [];
|
||||||
|
const have = new Set(r.node.entries.map((e) => e.key));
|
||||||
|
return Object.keys(ctx.properties(r.schema)).filter((k) => !have.has(k));
|
||||||
|
}
|
||||||
|
|
||||||
|
function requiredKeys(r: Row): Set<string> {
|
||||||
|
const s = r.parent ? ctx?.resolve(rows.find((x) => x.node === r.parent)?.schema) : undefined;
|
||||||
|
return new Set(s?.required ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
|
let menuRow = $state<Row | null>(null);
|
||||||
|
let popoverOpen = $state<Record<number, boolean>>({});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if !root}
|
||||||
|
<div class="flex flex-col items-start gap-2 p-4">
|
||||||
|
<p class="text-fg-muted">The body is empty. Start with</p>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button class="rounded border border-line bg-input px-3 py-1.5 hover:border-border-strong" onclick={() => ((root = empty('object')), changed())}>an object <span class="mono text-fg-subtle">{'{ }'}</span></button>
|
||||||
|
<button class="rounded border border-line bg-input px-3 py-1.5 hover:border-border-strong" onclick={() => ((root = empty('array')), changed())}>an array <span class="mono text-fg-subtle">[ ]</span></button>
|
||||||
|
{#if ctx}
|
||||||
|
<button class="rounded border border-line bg-input px-3 py-1.5 hover:border-border-strong" onclick={() => ((root = fromValue(ctx!.sample(ctx!.root))), changed())}>the schema sample</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<ContextMenu label="Field actions" class="min-h-full pb-10">
|
||||||
|
{#snippet children()}
|
||||||
|
<div class="py-1 text-[12.5px]" role="tree">
|
||||||
|
{#each rows as r (r.node.id)}
|
||||||
|
{@const n = r.node}
|
||||||
|
{@const errs = issues?.nodes.get(n.id)}
|
||||||
|
{@const missing = issues?.missing.get(n.id)}
|
||||||
|
{@const isContainer = n.kind === 'object' || n.kind === 'array'}
|
||||||
|
{@const en = enumOf(r)}
|
||||||
|
<div
|
||||||
|
role="treeitem"
|
||||||
|
aria-selected="false"
|
||||||
|
tabindex="-1"
|
||||||
|
class="group relative flex min-h-[30px] items-center gap-1 pr-2 hover:bg-hover/40 {dropTarget?.id === n.id ? (dropTarget.after ? 'shadow-[inset_0_-2px_0_var(--knock-cyan)]' : 'shadow-[inset_0_2px_0_var(--knock-cyan)]') : ''}"
|
||||||
|
style:padding-left="{6 + r.depth * 18}px"
|
||||||
|
use:focusKey={n.id}
|
||||||
|
oncontextmenu={() => (menuRow = r)}
|
||||||
|
ondragover={(e) => {
|
||||||
|
if (!drag || drag.parent !== r.parent || drag === r) return;
|
||||||
|
e.preventDefault();
|
||||||
|
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
|
||||||
|
dropTarget = { id: n.id, after: e.clientY > rect.top + rect.height / 2 };
|
||||||
|
}}
|
||||||
|
ondrop={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
onDrop(r);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#if r.parent}
|
||||||
|
<span
|
||||||
|
class="grid w-3.5 cursor-grab place-items-center text-fg-subtle opacity-0 group-hover:opacity-100"
|
||||||
|
draggable="true"
|
||||||
|
role="button"
|
||||||
|
tabindex="-1"
|
||||||
|
title="Drag to reorder"
|
||||||
|
ondragstart={() => (drag = r)}
|
||||||
|
ondragend={() => {
|
||||||
|
drag = null;
|
||||||
|
dropTarget = null;
|
||||||
|
}}><Icon name="grip" size={12} /></span
|
||||||
|
>
|
||||||
|
{:else}
|
||||||
|
<span class="w-3.5"></span>
|
||||||
|
{/if}
|
||||||
|
{#if isContainer}
|
||||||
|
<button
|
||||||
|
class="grid size-4 place-items-center text-fg-subtle hover:text-fg"
|
||||||
|
onclick={() => {
|
||||||
|
if (collapsed.has(n.id)) collapsed.delete(n.id);
|
||||||
|
else collapsed.add(n.id);
|
||||||
|
collapsed = new Set(collapsed);
|
||||||
|
}}
|
||||||
|
aria-label={collapsed.has(n.id) ? 'Expand' : 'Collapse'}
|
||||||
|
>
|
||||||
|
<Icon name={collapsed.has(n.id) ? 'chevron-right' : 'chevron-down'} size={12} />
|
||||||
|
</button>
|
||||||
|
{:else}
|
||||||
|
<span class="w-4"></span>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- key -->
|
||||||
|
<div class="flex w-[34%] min-w-[90px] max-w-[300px] shrink-0 items-center">
|
||||||
|
{#if r.entry}
|
||||||
|
<VarInput
|
||||||
|
value={r.entry.key}
|
||||||
|
placeholder="key"
|
||||||
|
suggestions={r.parent && ctx ? suggestions(rows.find((x) => x.node === r.parent)!) : []}
|
||||||
|
oninput={(v) => {
|
||||||
|
r.entry!.key = v;
|
||||||
|
changed();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{#if requiredKeys(r).has(r.entry.key)}<span class="px-0.5 text-delete" title="required">*</span>{/if}
|
||||||
|
{:else if r.parent}
|
||||||
|
<span class="mono px-[7px] text-fg-subtle">{r.index}</span>
|
||||||
|
{:else}
|
||||||
|
<span class="k-label px-[7px]">root</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<select
|
||||||
|
class="k-field mono !w-[86px] shrink-0 !px-1 text-[11.5px] !text-fg-muted"
|
||||||
|
value={n.kind}
|
||||||
|
onchange={(e) => setKind(r, (e.currentTarget as HTMLSelectElement).value as Kind)}
|
||||||
|
title="Type"
|
||||||
|
>
|
||||||
|
{#each KINDS as k}<option value={k}>{k}</option>{/each}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- value -->
|
||||||
|
<div class="flex min-w-0 flex-1 items-center gap-1">
|
||||||
|
{#if en && (n.kind === 'string' || n.kind === 'number' || n.kind === 'boolean')}
|
||||||
|
<select
|
||||||
|
class="k-field mono"
|
||||||
|
value={JSON.stringify(n.kind === 'string' ? n.value : n.kind === 'number' ? Number(n.raw) : n.value)}
|
||||||
|
onchange={(e) => replaceNode(r, { ...fromValue(JSON.parse((e.currentTarget as HTMLSelectElement).value)), id: n.id })}
|
||||||
|
>
|
||||||
|
{#each en as opt}<option value={JSON.stringify(opt)}>{typeof opt === 'string' ? opt : JSON.stringify(opt)}</option>{/each}
|
||||||
|
</select>
|
||||||
|
{:else if n.kind === 'string'}
|
||||||
|
{#if n.value.includes('\n') || n.value.length > 160}
|
||||||
|
<Popover bind:open={() => !!popoverOpen[n.id], (v) => (popoverOpen[n.id] = v)} placement="bottom-start">
|
||||||
|
{#snippet trigger(attrs)}
|
||||||
|
<button {...attrs} class="mono flex min-w-0 flex-1 items-center gap-1.5 rounded px-[7px] py-[5px] text-left text-soft hover:bg-input">
|
||||||
|
<span class="truncate">{n.value.split('\n')[0]}</span>
|
||||||
|
<span class="shrink-0 text-[11px] text-fg-subtle">{n.value.split('\n').length} lines</span>
|
||||||
|
</button>
|
||||||
|
{/snippet}
|
||||||
|
<textarea
|
||||||
|
class="k-field mono h-64 w-[560px] resize !border-line !bg-input leading-relaxed"
|
||||||
|
value={n.value}
|
||||||
|
oninput={(e) => {
|
||||||
|
n.value = (e.currentTarget as HTMLTextAreaElement).value;
|
||||||
|
changed();
|
||||||
|
}}
|
||||||
|
></textarea>
|
||||||
|
</Popover>
|
||||||
|
{:else}
|
||||||
|
<VarInput
|
||||||
|
value={n.value}
|
||||||
|
placeholder="text"
|
||||||
|
oninput={(v) => {
|
||||||
|
n.value = v;
|
||||||
|
changed();
|
||||||
|
}}
|
||||||
|
onkeydown={(e) => {
|
||||||
|
if (e.key === 'Enter' && e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
n.value += '\n';
|
||||||
|
popoverOpen[n.id] = true;
|
||||||
|
changed();
|
||||||
|
} else if (e.key === 'Enter' && !e.ctrlKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
insertAfter(r);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button class="px-1 text-fg-subtle opacity-0 hover:text-fg group-hover:opacity-100" title="Multi-line (Shift+Enter)" onclick={() => ((n.value += '\n'), (popoverOpen[n.id] = true), changed())}>
|
||||||
|
<Icon name="wrap" size={12} />
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
{:else if n.kind === 'number'}
|
||||||
|
<input
|
||||||
|
class="k-field mono {/^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$/.test(n.raw) ? '' : '!border-delete'}"
|
||||||
|
value={n.raw}
|
||||||
|
inputmode="decimal"
|
||||||
|
spellcheck="false"
|
||||||
|
oninput={(e) => {
|
||||||
|
n.raw = (e.currentTarget as HTMLInputElement).value.trim();
|
||||||
|
changed();
|
||||||
|
}}
|
||||||
|
onkeydown={(e) => {
|
||||||
|
if (e.key === 'Enter' && !e.ctrlKey) insertAfter(r);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{#if /^-?\d{16,}$/.test(n.raw) && !Number.isSafeInteger(Number(n.raw))}
|
||||||
|
<span class="shrink-0 text-[11px] text-fg-subtle" title="Kept as written, never rounded">exact</span>
|
||||||
|
{/if}
|
||||||
|
{:else if n.kind === 'boolean'}
|
||||||
|
<div class="px-[7px]">
|
||||||
|
<Switch size="sm" checked={n.value} onchange={(v) => ((n.value = v), changed())} aria-label="Value">{n.value ? 'true' : 'false'}</Switch>
|
||||||
|
</div>
|
||||||
|
{:else if n.kind === 'null'}
|
||||||
|
<span class="mono px-[7px] text-fg-subtle">null</span>
|
||||||
|
{:else if n.kind === 'variable'}
|
||||||
|
<VarInput
|
||||||
|
value={`{{${n.name}}}`}
|
||||||
|
oninput={(v) => {
|
||||||
|
const m = /^\{\{\s*(.*?)\s*\}?\}?$/.exec(v);
|
||||||
|
n.name = (m ? m[1] : v).replace(/[{}]/g, '');
|
||||||
|
changed();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span class="shrink-0 text-[11px] text-fg-subtle" title="Inserted without quotes">raw</span>
|
||||||
|
{:else}
|
||||||
|
<span class="px-[7px] text-fg-subtle">{summary(n)}</span>
|
||||||
|
{#if missing?.length}
|
||||||
|
<span class="text-[11px] text-post">missing {missing.join(', ')}</span>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if errs}
|
||||||
|
<span class="shrink-0 text-[11px] text-delete" title={errs.join('\n')}><Icon name="alert" size={12} /></span>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="flex shrink-0 items-center opacity-0 group-focus-within:opacity-100 group-hover:opacity-100">
|
||||||
|
{#if isContainer}
|
||||||
|
<button class="grid size-6 place-items-center rounded text-fg-subtle hover:bg-hover hover:text-fg" title={n.kind === 'object' ? 'Add field' : 'Add item'} onclick={() => addChild(r)}>
|
||||||
|
<Icon name="plus" size={12} />
|
||||||
|
</button>
|
||||||
|
{:else if r.parent}
|
||||||
|
<button class="grid size-6 place-items-center rounded text-fg-subtle hover:bg-hover hover:text-fg" title="Add after" onclick={() => insertAfter(r)}>
|
||||||
|
<Icon name="plus" size={12} />
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
{#if r.parent}
|
||||||
|
<button class="grid size-6 place-items-center rounded text-fg-subtle hover:bg-hover hover:text-fg" title="Duplicate" onclick={() => duplicate(r)}>
|
||||||
|
<Icon name="copy" size={12} />
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
<button class="grid size-6 place-items-center rounded text-fg-subtle hover:bg-hover hover:text-delete" title="Delete" onclick={() => remove(r)}>
|
||||||
|
<Icon name="trash" size={12} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{#if isContainer && !collapsed.has(n.id) && n.kind === 'object' && ctx && suggestions(r).length}
|
||||||
|
<div class="flex flex-wrap items-center gap-1 py-1" style:padding-left="{6 + (r.depth + 1) * 18 + 36}px">
|
||||||
|
<span class="text-[11px] text-fg-subtle">Schema:</span>
|
||||||
|
{#each suggestions(r) as key}
|
||||||
|
{@const req = ctx.resolve(r.schema)?.required?.includes(key)}
|
||||||
|
<button class="mono rounded border border-dashed border-line px-1.5 py-0.5 text-[11px] {req ? 'text-post' : 'text-fg-muted'} hover:border-border-strong hover:text-fg" onclick={() => addSuggested(r, key)} title={ctx.child(r.schema, key)?.description ?? ''}>
|
||||||
|
+ {key}
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
{#snippet menu()}
|
||||||
|
{#if menuRow}
|
||||||
|
{@const r = menuRow}
|
||||||
|
{#if r.node.kind === 'object' || r.node.kind === 'array'}
|
||||||
|
<MenuItem onselect={() => addChild(r)}>Add {r.node.kind === 'object' ? 'field' : 'item'}</MenuItem>
|
||||||
|
<MenuItem onselect={() => pasteChild(r)}>Paste as child</MenuItem>
|
||||||
|
{:else}
|
||||||
|
<MenuItem onselect={() => pasteChild(r)}>Paste over value</MenuItem>
|
||||||
|
{/if}
|
||||||
|
{#if r.parent}
|
||||||
|
<MenuItem onselect={() => insertAfter(r)}>Insert after</MenuItem>
|
||||||
|
<MenuItem onselect={() => duplicate(r)}>Duplicate</MenuItem>
|
||||||
|
{/if}
|
||||||
|
<MenuSeparator />
|
||||||
|
<MenuItem onselect={() => copy(serialize(r.node, ' '))}>Copy value</MenuItem>
|
||||||
|
<MenuItem onselect={() => root && copy(pathTo(root, r.node.id) ?? '$')}>Copy path</MenuItem>
|
||||||
|
<MenuSeparator />
|
||||||
|
<MenuItem variant="danger" onselect={() => remove(r)}>Delete</MenuItem>
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
</ContextMenu>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import { toast } from '@joshicodes/cock';
|
||||||
|
import { pathTo, serialize, type JNode } from './ast';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
root: JNode;
|
||||||
|
/** Text search; matching rows are revealed and highlighted. */
|
||||||
|
search?: string;
|
||||||
|
onuse?: (node: JNode) => void;
|
||||||
|
}
|
||||||
|
let { root, search = '', onuse }: Props = $props();
|
||||||
|
|
||||||
|
const ROW = 22;
|
||||||
|
let collapsed = $state(new Set<number>());
|
||||||
|
let scrollTop = $state(0);
|
||||||
|
let height = $state(400);
|
||||||
|
let scroller: HTMLDivElement | undefined = $state();
|
||||||
|
let selected = $state<number | null>(null);
|
||||||
|
|
||||||
|
// Big documents start with everything below depth 2 collapsed.
|
||||||
|
$effect(() => {
|
||||||
|
root;
|
||||||
|
const next = new Set<number>();
|
||||||
|
let count = 0;
|
||||||
|
const walk = (n: JNode, depth: number) => {
|
||||||
|
count++;
|
||||||
|
const kids = n.kind === 'object' ? n.entries.map((e) => e.value) : n.kind === 'array' ? n.items : [];
|
||||||
|
if (depth >= 2 && kids.length && count > 2000) next.add(n.id);
|
||||||
|
for (const k of kids) walk(k, depth + 1);
|
||||||
|
};
|
||||||
|
walk(root, 0);
|
||||||
|
collapsed = next;
|
||||||
|
});
|
||||||
|
|
||||||
|
interface Row {
|
||||||
|
node: JNode;
|
||||||
|
key: string | null;
|
||||||
|
index: number | null;
|
||||||
|
depth: number;
|
||||||
|
closing?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
let matches = $derived.by(() => {
|
||||||
|
const q = search.trim().toLowerCase();
|
||||||
|
const hits = new Set<number>();
|
||||||
|
const ancestors = new Set<number>();
|
||||||
|
if (!q) return { hits, ancestors };
|
||||||
|
const walk = (n: JNode, key: string | null): boolean => {
|
||||||
|
let found = false;
|
||||||
|
if (key !== null && key.toLowerCase().includes(q)) found = true;
|
||||||
|
if ((n.kind === 'string' && n.value.toLowerCase().includes(q)) || (n.kind === 'number' && n.raw.includes(q)) || (n.kind === 'boolean' && String(n.value) === q) || (n.kind === 'null' && q === 'null')) found = true;
|
||||||
|
if (found) hits.add(n.id);
|
||||||
|
let childFound = false;
|
||||||
|
if (n.kind === 'object') for (const e of n.entries) childFound = walk(e.value, e.key) || childFound;
|
||||||
|
else if (n.kind === 'array') n.items.forEach((it) => (childFound = walk(it, null) || childFound));
|
||||||
|
if (childFound) ancestors.add(n.id);
|
||||||
|
return found || childFound;
|
||||||
|
};
|
||||||
|
walk(root, null);
|
||||||
|
return { hits, ancestors };
|
||||||
|
});
|
||||||
|
|
||||||
|
let rows = $derived.by(() => {
|
||||||
|
const out: Row[] = [];
|
||||||
|
const searching = matches.hits.size > 0;
|
||||||
|
const walk = (n: JNode, key: string | null, index: number | null, depth: number) => {
|
||||||
|
out.push({ node: n, key, index, depth });
|
||||||
|
const open = searching ? matches.ancestors.has(n.id) || !collapsed.has(n.id) : !collapsed.has(n.id);
|
||||||
|
if (n.kind === 'object' && open && n.entries.length) {
|
||||||
|
for (const e of n.entries) walk(e.value, e.key, null, depth + 1);
|
||||||
|
out.push({ node: n, key: null, index: null, depth, closing: true });
|
||||||
|
} else if (n.kind === 'array' && open && n.items.length) {
|
||||||
|
n.items.forEach((it, i) => walk(it, null, i, depth + 1));
|
||||||
|
out.push({ node: n, key: null, index: null, depth, closing: true });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(root, null, null, 0);
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
|
||||||
|
let first = $derived(Math.max(0, Math.floor(scrollTop / ROW) - 20));
|
||||||
|
let last = $derived(Math.min(rows.length, Math.ceil((scrollTop + height) / ROW) + 20));
|
||||||
|
|
||||||
|
let hitRows = $derived(rows.map((r, i) => (!r.closing && matches.hits.has(r.node.id) ? i : -1)).filter((i) => i >= 0));
|
||||||
|
let hitCursor = $state(0);
|
||||||
|
export function nextHit(dir = 1) {
|
||||||
|
if (!hitRows.length || !scroller) return;
|
||||||
|
hitCursor = (hitCursor + dir + hitRows.length) % hitRows.length;
|
||||||
|
const i = hitRows[hitCursor];
|
||||||
|
scroller.scrollTop = Math.max(0, i * ROW - height / 2);
|
||||||
|
selected = rows[i].node.id;
|
||||||
|
}
|
||||||
|
export function hitCount() {
|
||||||
|
return hitRows.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle(n: JNode) {
|
||||||
|
const next = new Set(collapsed);
|
||||||
|
if (next.has(n.id)) next.delete(n.id);
|
||||||
|
else next.add(n.id);
|
||||||
|
collapsed = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function expandAll(open: boolean) {
|
||||||
|
const next = new Set<number>();
|
||||||
|
if (!open) {
|
||||||
|
const walk = (n: JNode, depth: number) => {
|
||||||
|
if ((n.kind === 'object' || n.kind === 'array') && depth > 0) next.add(n.id);
|
||||||
|
const kids = n.kind === 'object' ? n.entries.map((e) => e.value) : n.kind === 'array' ? n.items : [];
|
||||||
|
for (const k of kids) walk(k, depth + 1);
|
||||||
|
};
|
||||||
|
walk(root, 0);
|
||||||
|
}
|
||||||
|
collapsed = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function preview(n: JNode): string {
|
||||||
|
if (n.kind === 'object') return `{ ${n.entries.length} }`;
|
||||||
|
if (n.kind === 'array') return `[ ${n.items.length} ]`;
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyPath(n: JNode) {
|
||||||
|
navigator.clipboard.writeText(pathTo(root, n.id) ?? '$');
|
||||||
|
toast.success('Path copied');
|
||||||
|
}
|
||||||
|
function copyValue(n: JNode) {
|
||||||
|
navigator.clipboard.writeText(n.kind === 'string' ? n.value : serialize(n, ' '));
|
||||||
|
toast.success('Value copied');
|
||||||
|
}
|
||||||
|
|
||||||
|
const valueClass: Record<string, string> = {
|
||||||
|
string: 'text-ok',
|
||||||
|
number: 'text-post',
|
||||||
|
boolean: 'text-put',
|
||||||
|
null: 'text-put',
|
||||||
|
variable: 'text-get'
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div
|
||||||
|
bind:this={scroller}
|
||||||
|
bind:clientHeight={height}
|
||||||
|
class="k-scroll mono h-full text-[12.5px]"
|
||||||
|
onscroll={(e) => (scrollTop = (e.currentTarget as HTMLElement).scrollTop)}
|
||||||
|
>
|
||||||
|
<div style:height="{rows.length * ROW}px" class="relative">
|
||||||
|
{#each rows.slice(first, last) as r, i (first + i)}
|
||||||
|
{@const n = r.node}
|
||||||
|
{@const hit = !r.closing && matches.hits.has(n.id)}
|
||||||
|
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
|
<div
|
||||||
|
class="group absolute inset-x-0 flex items-center whitespace-nowrap pr-2 {selected === n.id && !r.closing ? 'bg-hover' : 'hover:bg-hover/40'}"
|
||||||
|
style:top="{(first + i) * ROW}px"
|
||||||
|
style:height="{ROW}px"
|
||||||
|
style:padding-left="{8 + r.depth * 16}px"
|
||||||
|
onclick={() => {
|
||||||
|
if (r.closing) return;
|
||||||
|
selected = n.id;
|
||||||
|
if (n.kind === 'object' || n.kind === 'array') toggle(n);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#if r.closing}
|
||||||
|
<span class="pl-4 text-fg-subtle">{n.kind === 'object' ? '}' : ']'}</span>
|
||||||
|
{:else}
|
||||||
|
{#if n.kind === 'object' || n.kind === 'array'}
|
||||||
|
<Icon name={collapsed.has(n.id) && !matches.ancestors.has(n.id) ? 'chevron-right' : 'chevron-down'} size={11} class="mr-1 text-fg-subtle" />
|
||||||
|
{:else}
|
||||||
|
<span class="mr-1 w-[11px]"></span>
|
||||||
|
{/if}
|
||||||
|
{#if r.key !== null}
|
||||||
|
<span class="text-get {hit ? 'bg-post/25' : ''}">"{r.key}"</span><span class="text-fg-subtle">: </span>
|
||||||
|
{:else if r.index !== null}
|
||||||
|
<span class="text-fg-subtle">{r.index}: </span>
|
||||||
|
{/if}
|
||||||
|
{#if n.kind === 'object' || n.kind === 'array'}
|
||||||
|
<span class="text-fg-subtle">{collapsed.has(n.id) && !matches.ancestors.has(n.id) ? preview(n) : n.kind === 'object' ? '{' : '['}</span>
|
||||||
|
{:else}
|
||||||
|
<span class="truncate {valueClass[n.kind]} {hit ? 'bg-post/25' : ''}">{serialize(n, '')}</span>
|
||||||
|
{/if}
|
||||||
|
<span class="ml-auto hidden shrink-0 items-center gap-2 pl-3 font-sans text-[11px] group-hover:flex">
|
||||||
|
<button class="text-fg-subtle hover:text-fg" onclick={(e) => (e.stopPropagation(), copyPath(n))}>path</button>
|
||||||
|
<button class="text-fg-subtle hover:text-fg" onclick={(e) => (e.stopPropagation(), copyValue(n))}>copy</button>
|
||||||
|
{#if onuse && (n.kind === 'object' || n.kind === 'array')}
|
||||||
|
<button class="text-accent hover:underline" onclick={(e) => (e.stopPropagation(), onuse(n))}>use as body</button>
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,462 @@
|
|||||||
|
// A JSON tree that keeps what JSON.parse throws away: key order with
|
||||||
|
// duplicates, number text (so 2^53+1 survives), and bare `{{var}}` values.
|
||||||
|
|
||||||
|
export type JNode =
|
||||||
|
| { id: number; kind: 'object'; entries: JEntry[] }
|
||||||
|
| { id: number; kind: 'array'; items: JNode[] }
|
||||||
|
| { id: number; kind: 'string'; value: string }
|
||||||
|
| { id: number; kind: 'number'; raw: string }
|
||||||
|
| { id: number; kind: 'boolean'; value: boolean }
|
||||||
|
| { id: number; kind: 'null' }
|
||||||
|
| { id: number; kind: 'variable'; name: string };
|
||||||
|
|
||||||
|
export interface JEntry {
|
||||||
|
id: number;
|
||||||
|
key: string;
|
||||||
|
value: JNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Kind = JNode['kind'];
|
||||||
|
export const KINDS: Kind[] = ['string', 'number', 'boolean', 'null', 'object', 'array', 'variable'];
|
||||||
|
|
||||||
|
let nextId = 1;
|
||||||
|
export const nid = () => nextId++;
|
||||||
|
|
||||||
|
export class ParseError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
public offset: number,
|
||||||
|
public line: number,
|
||||||
|
public column: number
|
||||||
|
) {
|
||||||
|
super(`${message} at line ${line}, column ${column}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const NUM = /-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/y;
|
||||||
|
|
||||||
|
export function parse(text: string, opts: { comments?: boolean } = {}): JNode | null {
|
||||||
|
let i = 0;
|
||||||
|
const n = text.length;
|
||||||
|
|
||||||
|
const fail = (msg: string): never => {
|
||||||
|
let line = 1;
|
||||||
|
let col = 1;
|
||||||
|
for (let k = 0; k < i && k < n; k++) {
|
||||||
|
if (text[k] === '\n') {
|
||||||
|
line++;
|
||||||
|
col = 1;
|
||||||
|
} else col++;
|
||||||
|
}
|
||||||
|
throw new ParseError(msg, i, line, col);
|
||||||
|
};
|
||||||
|
|
||||||
|
const ws = () => {
|
||||||
|
for (;;) {
|
||||||
|
while (i < n && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r')) i++;
|
||||||
|
if (opts.comments && text[i] === '/' && text[i + 1] === '/') {
|
||||||
|
while (i < n && text[i] !== '\n') i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (opts.comments && text[i] === '/' && text[i + 1] === '*') {
|
||||||
|
const end = text.indexOf('*/', i + 2);
|
||||||
|
if (end < 0) fail('unterminated comment');
|
||||||
|
i = end + 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const str = (): string => {
|
||||||
|
i++; // opening quote
|
||||||
|
let out = '';
|
||||||
|
let start = i;
|
||||||
|
for (;;) {
|
||||||
|
if (i >= n) fail('unterminated string');
|
||||||
|
const c = text.charCodeAt(i);
|
||||||
|
if (c === 34 /* " */) {
|
||||||
|
out += text.slice(start, i);
|
||||||
|
i++;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (c === 10 /* \n */) fail('line break in string');
|
||||||
|
if (c !== 92 /* \ */) {
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out += text.slice(start, i);
|
||||||
|
const e = text[i + 1];
|
||||||
|
i += 2;
|
||||||
|
switch (e) {
|
||||||
|
case '"':
|
||||||
|
out += '"';
|
||||||
|
break;
|
||||||
|
case '\\':
|
||||||
|
out += '\\';
|
||||||
|
break;
|
||||||
|
case '/':
|
||||||
|
out += '/';
|
||||||
|
break;
|
||||||
|
case 'b':
|
||||||
|
out += '\b';
|
||||||
|
break;
|
||||||
|
case 'f':
|
||||||
|
out += '\f';
|
||||||
|
break;
|
||||||
|
case 'n':
|
||||||
|
out += '\n';
|
||||||
|
break;
|
||||||
|
case 'r':
|
||||||
|
out += '\r';
|
||||||
|
break;
|
||||||
|
case 't':
|
||||||
|
out += '\t';
|
||||||
|
break;
|
||||||
|
case 'u': {
|
||||||
|
const hex = text.slice(i, i + 4);
|
||||||
|
if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail('bad unicode escape');
|
||||||
|
out += String.fromCharCode(parseInt(hex, 16));
|
||||||
|
i += 4;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
i -= 1;
|
||||||
|
fail('bad escape');
|
||||||
|
}
|
||||||
|
start = i;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const value = (): JNode => {
|
||||||
|
ws();
|
||||||
|
if (i >= n) fail('unexpected end');
|
||||||
|
const c = text[i];
|
||||||
|
if (c === '{') {
|
||||||
|
if (text[i + 1] === '{') {
|
||||||
|
const end = text.indexOf('}}', i + 2);
|
||||||
|
if (end < 0) fail('unterminated variable');
|
||||||
|
const name = text.slice(i + 2, end).trim();
|
||||||
|
i = end + 2;
|
||||||
|
return { id: nid(), kind: 'variable', name };
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
const entries: JEntry[] = [];
|
||||||
|
ws();
|
||||||
|
if (text[i] === '}') {
|
||||||
|
i++;
|
||||||
|
return { id: nid(), kind: 'object', entries };
|
||||||
|
}
|
||||||
|
for (;;) {
|
||||||
|
ws();
|
||||||
|
if (opts.comments && text[i] === '}') {
|
||||||
|
i++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (text[i] !== '"') fail('expected a key in double quotes');
|
||||||
|
const key = str();
|
||||||
|
ws();
|
||||||
|
if (text[i] !== ':') fail("expected ':'");
|
||||||
|
i++;
|
||||||
|
entries.push({ id: nid(), key, value: value() });
|
||||||
|
ws();
|
||||||
|
if (text[i] === ',') {
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (text[i] === '}') {
|
||||||
|
i++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
fail("expected ',' or '}'");
|
||||||
|
}
|
||||||
|
return { id: nid(), kind: 'object', entries };
|
||||||
|
}
|
||||||
|
if (c === '[') {
|
||||||
|
i++;
|
||||||
|
const items: JNode[] = [];
|
||||||
|
ws();
|
||||||
|
if (text[i] === ']') {
|
||||||
|
i++;
|
||||||
|
return { id: nid(), kind: 'array', items };
|
||||||
|
}
|
||||||
|
for (;;) {
|
||||||
|
ws();
|
||||||
|
if (opts.comments && text[i] === ']') {
|
||||||
|
i++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
items.push(value());
|
||||||
|
ws();
|
||||||
|
if (text[i] === ',') {
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (text[i] === ']') {
|
||||||
|
i++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
fail("expected ',' or ']'");
|
||||||
|
}
|
||||||
|
return { id: nid(), kind: 'array', items };
|
||||||
|
}
|
||||||
|
if (c === '"') return { id: nid(), kind: 'string', value: str() };
|
||||||
|
NUM.lastIndex = i;
|
||||||
|
const m = NUM.exec(text);
|
||||||
|
if (m && m[0].length) {
|
||||||
|
i += m[0].length;
|
||||||
|
return { id: nid(), kind: 'number', raw: m[0] };
|
||||||
|
}
|
||||||
|
if (text.startsWith('true', i)) {
|
||||||
|
i += 4;
|
||||||
|
return { id: nid(), kind: 'boolean', value: true };
|
||||||
|
}
|
||||||
|
if (text.startsWith('false', i)) {
|
||||||
|
i += 5;
|
||||||
|
return { id: nid(), kind: 'boolean', value: false };
|
||||||
|
}
|
||||||
|
if (text.startsWith('null', i)) {
|
||||||
|
i += 4;
|
||||||
|
return { id: nid(), kind: 'null' };
|
||||||
|
}
|
||||||
|
return fail('unexpected character');
|
||||||
|
};
|
||||||
|
|
||||||
|
ws();
|
||||||
|
if (i >= n) return null;
|
||||||
|
const root = value();
|
||||||
|
ws();
|
||||||
|
if (i < n) fail('unexpected text after the value');
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasComments(text: string): boolean {
|
||||||
|
let inStr = false;
|
||||||
|
for (let i = 0; i < text.length; i++) {
|
||||||
|
const c = text[i];
|
||||||
|
if (inStr) {
|
||||||
|
if (c === '\\') i++;
|
||||||
|
else if (c === '"') inStr = false;
|
||||||
|
} else if (c === '"') inStr = true;
|
||||||
|
else if (c === '/' && (text[i + 1] === '/' || text[i + 1] === '*')) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detectIndent(text: string): string {
|
||||||
|
const m = /\n([ \t]+)\S/.exec(text);
|
||||||
|
return m ? (m[1].startsWith('\t') ? '\t' : ' '.repeat(Math.min(m[1].length, 8))) : ' ';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serialize(node: JNode | null, indent = ' ', depth = 0): string {
|
||||||
|
if (!node) return '';
|
||||||
|
const pad = indent ? '\n' + indent.repeat(depth + 1) : '';
|
||||||
|
const end = indent ? '\n' + indent.repeat(depth) : '';
|
||||||
|
const sep = indent ? ': ' : ':';
|
||||||
|
switch (node.kind) {
|
||||||
|
case 'object':
|
||||||
|
if (!node.entries.length) return '{}';
|
||||||
|
return `{${node.entries.map((e) => `${pad}${JSON.stringify(e.key)}${sep}${serialize(e.value, indent, depth + 1)}`).join(',')}${end}}`;
|
||||||
|
case 'array':
|
||||||
|
if (!node.items.length) return '[]';
|
||||||
|
return `[${node.items.map((v) => `${pad}${serialize(v, indent, depth + 1)}`).join(',')}${end}]`;
|
||||||
|
case 'string':
|
||||||
|
return JSON.stringify(node.value);
|
||||||
|
case 'number':
|
||||||
|
return node.raw || '0';
|
||||||
|
case 'boolean':
|
||||||
|
return String(node.value);
|
||||||
|
case 'null':
|
||||||
|
return 'null';
|
||||||
|
case 'variable':
|
||||||
|
return `{{${node.name}}}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Builds a tree from a plain JS value (clipboard paste, response pick). */
|
||||||
|
export function fromValue(v: unknown): JNode {
|
||||||
|
if (v === null || v === undefined) return { id: nid(), kind: 'null' };
|
||||||
|
if (Array.isArray(v)) return { id: nid(), kind: 'array', items: v.map(fromValue) };
|
||||||
|
switch (typeof v) {
|
||||||
|
case 'string':
|
||||||
|
return { id: nid(), kind: 'string', value: v };
|
||||||
|
case 'number':
|
||||||
|
return { id: nid(), kind: 'number', raw: String(v) };
|
||||||
|
case 'bigint':
|
||||||
|
return { id: nid(), kind: 'number', raw: v.toString() };
|
||||||
|
case 'boolean':
|
||||||
|
return { id: nid(), kind: 'boolean', value: v };
|
||||||
|
case 'object':
|
||||||
|
return {
|
||||||
|
id: nid(),
|
||||||
|
kind: 'object',
|
||||||
|
entries: Object.entries(v as object).map(([key, value]) => ({ id: nid(), key, value: fromValue(value) }))
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
return { id: nid(), kind: 'string', value: String(v) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clone(node: JNode): JNode {
|
||||||
|
switch (node.kind) {
|
||||||
|
case 'object':
|
||||||
|
return { ...node, id: nid(), entries: node.entries.map((e) => ({ id: nid(), key: e.key, value: clone(e.value) })) };
|
||||||
|
case 'array':
|
||||||
|
return { ...node, id: nid(), items: node.items.map(clone) };
|
||||||
|
default:
|
||||||
|
return { ...node, id: nid() };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function empty(kind: Kind): JNode {
|
||||||
|
switch (kind) {
|
||||||
|
case 'object':
|
||||||
|
return { id: nid(), kind, entries: [] };
|
||||||
|
case 'array':
|
||||||
|
return { id: nid(), kind, items: [] };
|
||||||
|
case 'string':
|
||||||
|
return { id: nid(), kind, value: '' };
|
||||||
|
case 'number':
|
||||||
|
return { id: nid(), kind, raw: '0' };
|
||||||
|
case 'boolean':
|
||||||
|
return { id: nid(), kind, value: false };
|
||||||
|
case 'null':
|
||||||
|
return { id: nid(), kind };
|
||||||
|
case 'variable':
|
||||||
|
return { id: nid(), kind, name: '' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Converted {
|
||||||
|
node: JNode;
|
||||||
|
/** Set when information was dropped and the user should confirm. */
|
||||||
|
loss?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Changes the type of a node, keeping as much of the value as possible. */
|
||||||
|
export function convert(node: JNode, to: Kind): Converted {
|
||||||
|
if (node.kind === to) return { node };
|
||||||
|
const id = node.id;
|
||||||
|
const text = scalarText(node);
|
||||||
|
switch (to) {
|
||||||
|
case 'string':
|
||||||
|
if (node.kind === 'object' || node.kind === 'array')
|
||||||
|
return { node: { id, kind: 'string', value: serialize(node, '') } };
|
||||||
|
return { node: { id, kind: 'string', value: text ?? '' } };
|
||||||
|
case 'number': {
|
||||||
|
const t = (text ?? '').trim();
|
||||||
|
if (/^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$/.test(t)) return { node: { id, kind: 'number', raw: t } };
|
||||||
|
if (node.kind === 'boolean') return { node: { id, kind: 'number', raw: node.value ? '1' : '0' } };
|
||||||
|
return { node: { id, kind: 'number', raw: '0' }, loss: describeLoss(node, 'number') };
|
||||||
|
}
|
||||||
|
case 'boolean': {
|
||||||
|
const t = (text ?? '').trim().toLowerCase();
|
||||||
|
if (t === 'true' || t === '1') return { node: { id, kind: 'boolean', value: true } };
|
||||||
|
if (t === 'false' || t === '0' || t === '') return { node: { id, kind: 'boolean', value: false } };
|
||||||
|
return { node: { id, kind: 'boolean', value: true }, loss: describeLoss(node, 'boolean') };
|
||||||
|
}
|
||||||
|
case 'null':
|
||||||
|
return {
|
||||||
|
node: { id, kind: 'null' },
|
||||||
|
loss: node.kind === 'string' && node.value === '' ? undefined : describeLoss(node, 'null')
|
||||||
|
};
|
||||||
|
case 'variable': {
|
||||||
|
const m = /^\{\{\s*([^{}]+?)\s*\}\}$/.exec(text ?? '');
|
||||||
|
if (m) return { node: { id, kind: 'variable', name: m[1] } };
|
||||||
|
if (node.kind === 'string' && /^[\w.$-]*$/.test(node.value)) return { node: { id, kind: 'variable', name: node.value } };
|
||||||
|
return { node: { id, kind: 'variable', name: '' }, loss: describeLoss(node, 'variable') };
|
||||||
|
}
|
||||||
|
case 'object':
|
||||||
|
case 'array': {
|
||||||
|
if (node.kind === 'string') {
|
||||||
|
try {
|
||||||
|
const parsed = parse(node.value);
|
||||||
|
if (parsed && parsed.kind === to) return { node: { ...parsed, id } };
|
||||||
|
} catch {
|
||||||
|
/* not JSON text */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (to === 'array' && node.kind === 'object') {
|
||||||
|
return { node: { id, kind: 'array', items: node.entries.map((e) => e.value) }, loss: 'Keys are dropped.' };
|
||||||
|
}
|
||||||
|
if (to === 'object' && node.kind === 'array') {
|
||||||
|
return {
|
||||||
|
node: { id, kind: 'object', entries: node.items.map((v, i) => ({ id: nid(), key: String(i), value: v })) }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (to === 'array' && node.kind !== 'null' && !(node.kind === 'string' && node.value === '')) {
|
||||||
|
return { node: { id, kind: 'array', items: [{ ...node, id: nid() } as JNode] } };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
node: empty(to),
|
||||||
|
loss: node.kind === 'null' || (node.kind === 'string' && node.value === '') ? undefined : describeLoss(node, to)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scalarText(node: JNode): string | null {
|
||||||
|
switch (node.kind) {
|
||||||
|
case 'string':
|
||||||
|
return node.value;
|
||||||
|
case 'number':
|
||||||
|
return node.raw;
|
||||||
|
case 'boolean':
|
||||||
|
return String(node.value);
|
||||||
|
case 'null':
|
||||||
|
return 'null';
|
||||||
|
case 'variable':
|
||||||
|
return `{{${node.name}}}`;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function describeLoss(node: JNode, to: string): string {
|
||||||
|
const preview = node.kind === 'object' || node.kind === 'array' ? serialize(node, '').slice(0, 60) : scalarText(node);
|
||||||
|
return `${preview} cannot be turned into ${to}; the value would be lost.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** JSONPath of a node, for "copy path". */
|
||||||
|
export function pathTo(root: JNode, target: number): string | null {
|
||||||
|
const walk = (n: JNode, path: string): string | null => {
|
||||||
|
if (n.id === target) return path;
|
||||||
|
if (n.kind === 'object') {
|
||||||
|
for (const e of n.entries) {
|
||||||
|
const p = /^[A-Za-z_$][\w$]*$/.test(e.key) ? `${path}.${e.key}` : `${path}[${JSON.stringify(e.key)}]`;
|
||||||
|
if (e.id === target) return p;
|
||||||
|
const r = walk(e.value, p);
|
||||||
|
if (r) return r;
|
||||||
|
}
|
||||||
|
} else if (n.kind === 'array') {
|
||||||
|
for (let i = 0; i < n.items.length; i++) {
|
||||||
|
const r = walk(n.items[i], `${path}[${i}]`);
|
||||||
|
if (r) return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
return walk(root, '$');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plain JS value of a tree; variables become their template text. */
|
||||||
|
export function toValue(n: JNode): unknown {
|
||||||
|
switch (n.kind) {
|
||||||
|
case 'object':
|
||||||
|
return Object.fromEntries(n.entries.map((e) => [e.key, toValue(e.value)]));
|
||||||
|
case 'array':
|
||||||
|
return n.items.map(toValue);
|
||||||
|
case 'string':
|
||||||
|
return n.value;
|
||||||
|
case 'number': {
|
||||||
|
const x = Number(n.raw);
|
||||||
|
return Number.isSafeInteger(x) || !/^-?\d+$/.test(n.raw) ? x : n.raw;
|
||||||
|
}
|
||||||
|
case 'boolean':
|
||||||
|
return n.value;
|
||||||
|
case 'null':
|
||||||
|
return null;
|
||||||
|
case 'variable':
|
||||||
|
return `{{${n.name}}}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
// The subset of JSON Schema that helps while typing a body: properties,
|
||||||
|
// required, type, enum/const, items, $ref (local), allOf/oneOf/anyOf for
|
||||||
|
// suggestions, plus a handful of constraints for validation.
|
||||||
|
|
||||||
|
import type { JNode } from './ast';
|
||||||
|
|
||||||
|
export type Schema = {
|
||||||
|
$ref?: string;
|
||||||
|
type?: string | string[];
|
||||||
|
properties?: Record<string, Schema>;
|
||||||
|
required?: string[];
|
||||||
|
additionalProperties?: boolean | Schema;
|
||||||
|
items?: Schema | Schema[];
|
||||||
|
enum?: unknown[];
|
||||||
|
const?: unknown;
|
||||||
|
description?: string;
|
||||||
|
title?: string;
|
||||||
|
format?: string;
|
||||||
|
default?: unknown;
|
||||||
|
example?: unknown;
|
||||||
|
examples?: unknown[];
|
||||||
|
minimum?: number;
|
||||||
|
maximum?: number;
|
||||||
|
minLength?: number;
|
||||||
|
maxLength?: number;
|
||||||
|
pattern?: string;
|
||||||
|
minItems?: number;
|
||||||
|
maxItems?: number;
|
||||||
|
allOf?: Schema[];
|
||||||
|
oneOf?: Schema[];
|
||||||
|
anyOf?: Schema[];
|
||||||
|
nullable?: boolean;
|
||||||
|
[k: string]: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class SchemaCtx {
|
||||||
|
constructor(public root: Schema) {}
|
||||||
|
|
||||||
|
resolve(s: Schema | undefined, depth = 0): Schema | undefined {
|
||||||
|
if (!s || depth > 20) return s;
|
||||||
|
if (s.$ref && s.$ref.startsWith('#')) {
|
||||||
|
const target = this.pointer(s.$ref.slice(1));
|
||||||
|
const { $ref: _, ...rest } = s;
|
||||||
|
return this.resolve({ ...(target as Schema), ...rest }, depth + 1);
|
||||||
|
}
|
||||||
|
if (s.allOf?.length) {
|
||||||
|
const merged: Schema = { ...s, allOf: undefined };
|
||||||
|
for (const part of s.allOf) {
|
||||||
|
const p = this.resolve(part, depth + 1) ?? {};
|
||||||
|
merged.properties = { ...(merged.properties ?? {}), ...(p.properties ?? {}) };
|
||||||
|
merged.required = [...(merged.required ?? []), ...(p.required ?? [])];
|
||||||
|
merged.type ??= p.type;
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
private pointer(ptr: string): unknown {
|
||||||
|
let cur: unknown = this.root;
|
||||||
|
for (const raw of ptr.split('/').filter(Boolean)) {
|
||||||
|
const key = raw.replace(/~1/g, '/').replace(/~0/g, '~');
|
||||||
|
if (cur && typeof cur === 'object') cur = (cur as Record<string, unknown>)[decodeURIComponent(key)];
|
||||||
|
else return undefined;
|
||||||
|
}
|
||||||
|
return cur;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Properties offered for an object, including those of oneOf/anyOf branches. */
|
||||||
|
properties(s: Schema | undefined): Record<string, Schema> {
|
||||||
|
const r = this.resolve(s);
|
||||||
|
if (!r) return {};
|
||||||
|
const out: Record<string, Schema> = { ...(r.properties ?? {}) };
|
||||||
|
for (const branch of [...(r.oneOf ?? []), ...(r.anyOf ?? [])]) {
|
||||||
|
Object.assign(out, this.resolve(branch)?.properties ?? {});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
child(s: Schema | undefined, key: string | number): Schema | undefined {
|
||||||
|
const r = this.resolve(s);
|
||||||
|
if (!r) return undefined;
|
||||||
|
if (typeof key === 'number') {
|
||||||
|
if (Array.isArray(r.items)) return this.resolve(r.items[key]);
|
||||||
|
return this.resolve(r.items);
|
||||||
|
}
|
||||||
|
const p = this.properties(r)[key];
|
||||||
|
if (p) return this.resolve(p);
|
||||||
|
if (typeof r.additionalProperties === 'object') return this.resolve(r.additionalProperties);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
types(s: Schema | undefined): string[] {
|
||||||
|
const r = this.resolve(s);
|
||||||
|
if (!r) return [];
|
||||||
|
const t = Array.isArray(r.type) ? r.type : r.type ? [r.type] : [];
|
||||||
|
if (!t.length) {
|
||||||
|
if (r.properties) return ['object'];
|
||||||
|
if (r.items) return ['array'];
|
||||||
|
if (r.enum?.length) return [...new Set(r.enum.map(jsonType))];
|
||||||
|
}
|
||||||
|
return r.nullable ? [...t, 'null'] : t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Example value for a new field: default, example, first enum, or an empty value of the type. */
|
||||||
|
sample(s: Schema | undefined, depth = 0): unknown {
|
||||||
|
const r = this.resolve(s);
|
||||||
|
if (!r || depth > 6) return '';
|
||||||
|
if (r.default !== undefined) return r.default;
|
||||||
|
if (r.example !== undefined) return r.example;
|
||||||
|
if (r.examples?.length) return r.examples[0];
|
||||||
|
if (r.const !== undefined) return r.const;
|
||||||
|
if (r.enum?.length) return r.enum[0];
|
||||||
|
const t = this.types(r)[0];
|
||||||
|
switch (t) {
|
||||||
|
case 'object': {
|
||||||
|
const out: Record<string, unknown> = {};
|
||||||
|
for (const k of r.required ?? []) out[k] = this.sample(this.properties(r)[k], depth + 1);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
case 'array':
|
||||||
|
return [];
|
||||||
|
case 'integer':
|
||||||
|
case 'number':
|
||||||
|
return r.minimum ?? 0;
|
||||||
|
case 'boolean':
|
||||||
|
return false;
|
||||||
|
case 'null':
|
||||||
|
return null;
|
||||||
|
default:
|
||||||
|
if (r.format === 'email') return '[email protected]';
|
||||||
|
if (r.format === 'date-time') return new Date().toISOString();
|
||||||
|
if (r.format === 'date') return new Date().toISOString().slice(0, 10);
|
||||||
|
if (r.format === 'uuid') return '{{$uuid}}';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function jsonType(v: unknown): string {
|
||||||
|
if (v === null) return 'null';
|
||||||
|
if (Array.isArray(v)) return 'array';
|
||||||
|
if (typeof v === 'number') return Number.isInteger(v) ? 'integer' : 'number';
|
||||||
|
return typeof v;
|
||||||
|
}
|
||||||
|
|
||||||
|
function nodeType(n: JNode): string {
|
||||||
|
switch (n.kind) {
|
||||||
|
case 'number':
|
||||||
|
return /^-?\d+$/.test(n.raw) ? 'integer' : 'number';
|
||||||
|
default:
|
||||||
|
return n.kind;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scalar(n: JNode): unknown {
|
||||||
|
switch (n.kind) {
|
||||||
|
case 'string':
|
||||||
|
return n.value;
|
||||||
|
case 'number':
|
||||||
|
return Number(n.raw);
|
||||||
|
case 'boolean':
|
||||||
|
return n.value;
|
||||||
|
case 'null':
|
||||||
|
return null;
|
||||||
|
default:
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Issues {
|
||||||
|
/** Problems per node id. */
|
||||||
|
nodes: Map<number, string[]>;
|
||||||
|
/** Missing required keys per object node id. */
|
||||||
|
missing: Map<number, string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validate(ctx: SchemaCtx, root: JNode | null): Issues {
|
||||||
|
const issues: Issues = { nodes: new Map(), missing: new Map() };
|
||||||
|
const add = (id: number, msg: string) => {
|
||||||
|
const l = issues.nodes.get(id) ?? [];
|
||||||
|
l.push(msg);
|
||||||
|
issues.nodes.set(id, l);
|
||||||
|
};
|
||||||
|
const walk = (n: JNode, s: Schema | undefined) => {
|
||||||
|
const r = ctx.resolve(s);
|
||||||
|
if (!r) return;
|
||||||
|
if (n.kind === 'variable') return; // resolved at send time
|
||||||
|
const allowed = ctx.types(r);
|
||||||
|
const t = nodeType(n);
|
||||||
|
if (allowed.length && !allowed.includes(t) && !(t === 'integer' && allowed.includes('number'))) {
|
||||||
|
add(n.id, `expected ${allowed.join(' or ')}, got ${t}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const v = scalar(n);
|
||||||
|
if (r.enum && v !== undefined && !r.enum.some((e) => e === v)) add(n.id, `must be one of ${r.enum.map((e) => JSON.stringify(e)).join(', ')}`);
|
||||||
|
if (r.const !== undefined && v !== undefined && r.const !== v) add(n.id, `must be ${JSON.stringify(r.const)}`);
|
||||||
|
if (n.kind === 'string' && !/\{\{/.test(n.value)) {
|
||||||
|
if (r.minLength !== undefined && n.value.length < r.minLength) add(n.id, `at least ${r.minLength} characters`);
|
||||||
|
if (r.maxLength !== undefined && n.value.length > r.maxLength) add(n.id, `at most ${r.maxLength} characters`);
|
||||||
|
if (r.pattern) {
|
||||||
|
try {
|
||||||
|
if (!new RegExp(r.pattern, 'u').test(n.value)) add(n.id, `must match ${r.pattern}`);
|
||||||
|
} catch {
|
||||||
|
/* pattern uses syntax JS does not know; skip */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (r.format === 'email' && n.value && !/^[^@\s]+@[^@\s]+$/.test(n.value)) add(n.id, 'not an e-mail address');
|
||||||
|
}
|
||||||
|
if (n.kind === 'number') {
|
||||||
|
const x = Number(n.raw);
|
||||||
|
if (r.minimum !== undefined && x < r.minimum) add(n.id, `minimum ${r.minimum}`);
|
||||||
|
if (r.maximum !== undefined && x > r.maximum) add(n.id, `maximum ${r.maximum}`);
|
||||||
|
}
|
||||||
|
if (n.kind === 'object') {
|
||||||
|
const keys = new Set(n.entries.map((e) => e.key));
|
||||||
|
const missing = (r.required ?? []).filter((k) => !keys.has(k));
|
||||||
|
if (missing.length) issues.missing.set(n.id, missing);
|
||||||
|
const props = ctx.properties(r);
|
||||||
|
for (const e of n.entries) {
|
||||||
|
if (r.additionalProperties === false && !(e.key in props)) add(e.value.id, `"${e.key}" is not allowed here`);
|
||||||
|
walk(e.value, ctx.child(r, e.key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (n.kind === 'array') {
|
||||||
|
if (r.minItems !== undefined && n.items.length < r.minItems) add(n.id, `at least ${r.minItems} items`);
|
||||||
|
if (r.maxItems !== undefined && n.items.length > r.maxItems) add(n.id, `at most ${r.maxItems} items`);
|
||||||
|
n.items.forEach((it, i) => walk(it, ctx.child(r, i)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (root) walk(root, ctx.root);
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
/** Plain copy of reactive state, for sending over IPC. */
|
||||||
|
export function plain<T>(value: T): T {
|
||||||
|
return $state.snapshot(value as unknown) as unknown as T;
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import type { KeyValue, Request, RequestSettings } from './types';
|
||||||
|
|
||||||
|
export const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
|
||||||
|
|
||||||
|
export const DEFAULT_SETTINGS: RequestSettings = {
|
||||||
|
timeout_ms: 30000,
|
||||||
|
follow_redirects: true,
|
||||||
|
max_redirects: 10,
|
||||||
|
verify_tls: true,
|
||||||
|
http_version: 'auto',
|
||||||
|
cookies: true,
|
||||||
|
retry_on_401: true
|
||||||
|
};
|
||||||
|
|
||||||
|
export function newRequest(kind: Request['type'] = 'http'): Request {
|
||||||
|
const base: Request = {
|
||||||
|
name: kind === 'ws' ? 'New WebSocket' : kind === 'graphql' ? 'New GraphQL query' : 'New request',
|
||||||
|
type: kind,
|
||||||
|
method: kind === 'graphql' ? 'POST' : 'GET',
|
||||||
|
url: '',
|
||||||
|
auth: 'inherit'
|
||||||
|
};
|
||||||
|
if (kind === 'graphql') base.graphql = { query: 'query {\n \n}\n', variables: '' };
|
||||||
|
if (kind === 'ws') base.ws = { subprotocols: [], messages: [] };
|
||||||
|
return normalizeRequest(base);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fills optional parts so editors can bind to them directly. */
|
||||||
|
export function normalizeRequest(r: Request): Request {
|
||||||
|
r.params ??= { query: [], path: {} };
|
||||||
|
r.params.query ??= [];
|
||||||
|
r.params.path ??= {};
|
||||||
|
r.headers ??= [];
|
||||||
|
r.body ??= { type: 'none' };
|
||||||
|
r.body.form ??= [];
|
||||||
|
r.body.multipart ??= [];
|
||||||
|
r.body.content ??= '';
|
||||||
|
r.vars ??= {};
|
||||||
|
r.extract ??= [];
|
||||||
|
r.assert ??= [];
|
||||||
|
r.settings = { ...DEFAULT_SETTINGS, ...(r.settings ?? {}) };
|
||||||
|
r.auth ??= 'inherit';
|
||||||
|
if (r.type === 'graphql') r.graphql ??= { query: '', variables: '' };
|
||||||
|
if (r.type === 'ws') r.ws ??= { subprotocols: [], messages: [] };
|
||||||
|
if (!r.method) r.method = 'GET';
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Splits `?a=1&b` off a URL into rows, keeping `{{vars}}` intact. */
|
||||||
|
export function parseQuery(url: string): KeyValue[] {
|
||||||
|
const q = url.indexOf('?');
|
||||||
|
if (q < 0) return [];
|
||||||
|
let qs = url.slice(q + 1);
|
||||||
|
const hash = qs.indexOf('#');
|
||||||
|
if (hash >= 0) qs = qs.slice(0, hash);
|
||||||
|
if (!qs) return [];
|
||||||
|
return qs.split('&').map((pair) => {
|
||||||
|
const eq = pair.indexOf('=');
|
||||||
|
const name = eq < 0 ? pair : pair.slice(0, eq);
|
||||||
|
const value = eq < 0 ? '' : pair.slice(eq + 1);
|
||||||
|
return { name: safeDecode(name), value: safeDecode(value) };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeDecode(s: string): string {
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(s.replace(/\+/g, ' '));
|
||||||
|
} catch {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodePart(s: string): string {
|
||||||
|
// Keep variables readable in the URL bar.
|
||||||
|
return s
|
||||||
|
.split(/(\{\{.*?\}\})/g)
|
||||||
|
.map((p) => (p.startsWith('{{') ? p : encodeURIComponent(p).replace(/%2F/gi, '/').replace(/%3A/gi, ':').replace(/%2C/gi, ',')))
|
||||||
|
.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rewrites the query of `url` from the enabled rows. Disabled rows stay in the table only. */
|
||||||
|
export function withQuery(url: string, rows: KeyValue[]): string {
|
||||||
|
const hashAt = url.indexOf('#');
|
||||||
|
const hash = hashAt >= 0 ? url.slice(hashAt) : '';
|
||||||
|
const noHash = hashAt >= 0 ? url.slice(0, hashAt) : url;
|
||||||
|
const q = noHash.indexOf('?');
|
||||||
|
const base = q >= 0 ? noHash.slice(0, q) : noHash;
|
||||||
|
const enabled = rows.filter((r) => r.enabled !== false && (r.name || r.value));
|
||||||
|
if (!enabled.length) return base + hash;
|
||||||
|
const qs = enabled
|
||||||
|
.map((r) => (r.value === '' && !r.name.includes('=') ? encodePart(r.name) : `${encodePart(r.name)}=${encodePart(r.value)}`))
|
||||||
|
.join('&');
|
||||||
|
return `${base}?${qs}${hash}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Merges rows parsed from the URL with the table, keeping disabled rows and descriptions. */
|
||||||
|
export function mergeQuery(fromUrl: KeyValue[], table: KeyValue[]): KeyValue[] {
|
||||||
|
const out: KeyValue[] = [];
|
||||||
|
const used = new Set<number>();
|
||||||
|
let urlIdx = 0;
|
||||||
|
for (const row of table) {
|
||||||
|
if (row.enabled === false) {
|
||||||
|
out.push(row);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const next = fromUrl[urlIdx++];
|
||||||
|
if (!next) continue;
|
||||||
|
out.push({ ...row, name: next.name, value: next.value });
|
||||||
|
used.add(urlIdx - 1);
|
||||||
|
}
|
||||||
|
for (let i = urlIdx; i < fromUrl.length; i++) out.push({ ...fromUrl[i] });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pathParamNames(url: string): string[] {
|
||||||
|
const m = url.match(/^[a-z]+:\/\/[^/]*/i);
|
||||||
|
let path = m ? url.slice(m[0].length) : url.replace(/^\{\{[^}]+\}\}/, '');
|
||||||
|
path = path.split(/[?#]/)[0];
|
||||||
|
return path
|
||||||
|
.split('/')
|
||||||
|
.filter((s) => s.startsWith(':') && /^:[\w-]+$/.test(s))
|
||||||
|
.map((s) => s.slice(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function methodColor(m: string | undefined): string {
|
||||||
|
switch ((m ?? 'GET').toUpperCase()) {
|
||||||
|
case 'GET':
|
||||||
|
return 'text-get';
|
||||||
|
case 'POST':
|
||||||
|
return 'text-post';
|
||||||
|
case 'PUT':
|
||||||
|
return 'text-put';
|
||||||
|
case 'PATCH':
|
||||||
|
return 'text-patch';
|
||||||
|
case 'DELETE':
|
||||||
|
return 'text-delete';
|
||||||
|
default:
|
||||||
|
return 'text-soft';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function statusColor(s: number | undefined | null): string {
|
||||||
|
if (!s) return 'text-delete';
|
||||||
|
if (s < 300) return 'text-ok';
|
||||||
|
if (s < 400) return 'text-post';
|
||||||
|
return 'text-delete';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatBytes(n: number | null | undefined): string {
|
||||||
|
if (n == null) return '';
|
||||||
|
if (n < 1024) return `${n} B`;
|
||||||
|
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||||
|
return `${(n / 1024 / 1024).toFixed(2)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatMs(n: number | null | undefined): string {
|
||||||
|
if (n == null) return '';
|
||||||
|
if (n < 1000) return `${Math.round(n)} ms`;
|
||||||
|
return `${(n / 1000).toFixed(2)} s`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { api } from './api';
|
||||||
|
import type { Tab } from './state/workspace.svelte';
|
||||||
|
|
||||||
|
const decoder = new TextDecoder('utf-8', { fatal: false });
|
||||||
|
|
||||||
|
/** Fetches and decodes the body of the tab's current response once. */
|
||||||
|
export async function loadBody(tab: Tab): Promise<void> {
|
||||||
|
const r = tab.result;
|
||||||
|
if (!r || r.bodyText !== undefined || !r.result.body_id) return;
|
||||||
|
try {
|
||||||
|
const buf = await api.responseBody(r.result.body_id);
|
||||||
|
const bytes = new Uint8Array(buf);
|
||||||
|
r.bodyBytes = bytes;
|
||||||
|
r.bodyText = decoder.decode(bytes);
|
||||||
|
} catch {
|
||||||
|
r.bodyText = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function responseText(tab: Tab): string | null {
|
||||||
|
return tab.result?.bodyText ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BodyKind = 'json' | 'xml' | 'html' | 'image' | 'pdf' | 'text' | 'binary';
|
||||||
|
|
||||||
|
export function bodyKind(contentType: string | null | undefined, bytes?: Uint8Array): BodyKind {
|
||||||
|
const ct = (contentType ?? '').toLowerCase();
|
||||||
|
if (/[/+]json\b/.test(ct)) return 'json';
|
||||||
|
if (/[/+]xml\b/.test(ct)) return 'xml';
|
||||||
|
if (ct.includes('text/html')) return 'html';
|
||||||
|
if (ct.startsWith('image/')) return 'image';
|
||||||
|
if (ct.includes('application/pdf')) return 'pdf';
|
||||||
|
if (ct.startsWith('text/') || ct.includes('javascript') || ct.includes('x-www-form-urlencoded')) return 'text';
|
||||||
|
if (bytes) {
|
||||||
|
const head = decoder.decode(bytes.slice(0, 512)).trimStart();
|
||||||
|
if (head.startsWith('{') || head.startsWith('[')) return 'json';
|
||||||
|
if (head.startsWith('<?xml')) return 'xml';
|
||||||
|
if (/^<!doctype html|^<html/i.test(head)) return 'html';
|
||||||
|
// Many NUL bytes means binary.
|
||||||
|
let nul = 0;
|
||||||
|
for (let i = 0; i < Math.min(bytes.length, 1024); i++) if (bytes[i] === 0) nul++;
|
||||||
|
if (nul > 0) return 'binary';
|
||||||
|
}
|
||||||
|
return 'text';
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { plain } from '$lib/plain.svelte';
|
||||||
|
import { api, errorText } from './api';
|
||||||
|
import { ws, type Tab } from './state/workspace.svelte';
|
||||||
|
import { dialogs } from './state/dialogs.svelte';
|
||||||
|
import type { Request } from './types';
|
||||||
|
import { toast } from '@joshicodes/cock';
|
||||||
|
|
||||||
|
const DESTRUCTIVE = new Set(['DELETE', 'PUT']);
|
||||||
|
|
||||||
|
export async function sendTab(tab: Tab | undefined = ws.active) {
|
||||||
|
if (!tab || tab.kind !== 'request' || !tab.draft) return;
|
||||||
|
if (tab.draft.type === 'ws') return; // the WS view connects on its own
|
||||||
|
if (tab.sending) return;
|
||||||
|
const env = ws.env(tab.col);
|
||||||
|
const envEntry = ws.collection(tab.col)?.environments.find((e) => e.id === env);
|
||||||
|
const method = (tab.draft.method ?? 'GET').toUpperCase();
|
||||||
|
if (envEntry?.protected && DESTRUCTIVE.has(method)) {
|
||||||
|
const ok = await dialogs.confirm(
|
||||||
|
`${method} against ${envEntry.name}?`,
|
||||||
|
`${envEntry.name} is a protected environment. Make sure this is what you want.`,
|
||||||
|
`Send ${method}`
|
||||||
|
);
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
|
tab.sending = true;
|
||||||
|
tab.error = undefined;
|
||||||
|
const request = plain(tab.draft);
|
||||||
|
try {
|
||||||
|
const result = await api.send({
|
||||||
|
col: tab.col,
|
||||||
|
request_id: tab.id,
|
||||||
|
request,
|
||||||
|
env,
|
||||||
|
tab: tab.key,
|
||||||
|
history_body_limit: Number(localStorage.getItem('knock.historyBodyLimit') ?? 1024 * 1024)
|
||||||
|
});
|
||||||
|
if (tab.result) tab.previous = tab.result;
|
||||||
|
tab.result = { result, at: Date.now() };
|
||||||
|
if (result.output.missing.length) {
|
||||||
|
toast.warning('Sent with undefined variables', {
|
||||||
|
description: result.output.missing.map((m) => `{{${m}}}`).join(', ')
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (const x of result.output.extracted) {
|
||||||
|
if (x.error) toast.warning(`Extract ${x.var}: ${x.error}`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
const msg = errorText(e);
|
||||||
|
if (msg !== 'cancelled') tab.error = msg;
|
||||||
|
} finally {
|
||||||
|
tab.sending = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cancelTab(tab: Tab | undefined = ws.active) {
|
||||||
|
if (tab?.sending) api.cancel(tab.key);
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/** Promise-based modal dialogs, rendered once by DialogHost. */
|
||||||
|
|
||||||
|
export type DialogState =
|
||||||
|
| { kind: 'confirm'; title: string; body: string; action: string; resolve: (ok: boolean) => void }
|
||||||
|
| { kind: 'prompt'; title: string; label: string; value: string; action: string; resolve: (v: string | null) => void }
|
||||||
|
| { kind: 'new-collection' }
|
||||||
|
| { kind: 'import' }
|
||||||
|
| { kind: 'runner'; col: string; folder: string }
|
||||||
|
| { kind: 'code'; col: string | null; tabKey: string };
|
||||||
|
|
||||||
|
class Dialogs {
|
||||||
|
current = $state<DialogState | null>(null);
|
||||||
|
|
||||||
|
confirm(title: string, body = '', action = 'OK'): Promise<boolean> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
this.current = { kind: 'confirm', title, body, action, resolve };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
prompt(title: string, label: string, value = '', action = 'OK'): Promise<string | null> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
this.current = { kind: 'prompt', title, label, value, action, resolve };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
newCollection() {
|
||||||
|
this.current = { kind: 'new-collection' };
|
||||||
|
}
|
||||||
|
|
||||||
|
importer() {
|
||||||
|
this.current = { kind: 'import' };
|
||||||
|
}
|
||||||
|
|
||||||
|
runner(col: string, folder: string) {
|
||||||
|
this.current = { kind: 'runner', col, folder };
|
||||||
|
}
|
||||||
|
|
||||||
|
code(col: string | null, tabKey: string) {
|
||||||
|
this.current = { kind: 'code', col, tabKey };
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
const c = this.current;
|
||||||
|
this.current = null;
|
||||||
|
if (c?.kind === 'confirm') c.resolve(false);
|
||||||
|
if (c?.kind === 'prompt') c.resolve(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const dialogs = new Dialogs();
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
/** Cross-component UI signals (shortcuts that open things elsewhere). */
|
||||||
|
class Ui {
|
||||||
|
envMenuRequest = $state(0);
|
||||||
|
focusUrlRequest = $state(0);
|
||||||
|
sidebarFilterRequest = $state(0);
|
||||||
|
toggleJsonModeRequest = $state(0);
|
||||||
|
sendRequest = $state(0);
|
||||||
|
/** Inline rename target in the sidebar: `${col}:${id}`. */
|
||||||
|
renaming = $state<string | null>(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ui = new Ui();
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { plain } from '$lib/plain.svelte';
|
||||||
|
import { api } from '$lib/api';
|
||||||
|
import { redrawVars } from '$lib/editor/cm';
|
||||||
|
import type { Request, VarInfo } from '$lib/types';
|
||||||
|
|
||||||
|
/** Variables visible to the active request, for highlighting, hover and autocomplete. */
|
||||||
|
class VarsStore {
|
||||||
|
map = $state(new Map<string, VarInfo>());
|
||||||
|
dynamic = $state<[string, string][]>([]);
|
||||||
|
ready = $state(false);
|
||||||
|
mask = $state(false);
|
||||||
|
#timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
#seq = 0;
|
||||||
|
|
||||||
|
refresh(col: string | null, requestId: string | null, request: Request | undefined, env: string | null) {
|
||||||
|
clearTimeout(this.#timer);
|
||||||
|
if (!request) return;
|
||||||
|
const seq = ++this.#seq;
|
||||||
|
this.#timer = setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.varsList({ col, request_id: requestId, request: plain(request), env });
|
||||||
|
if (seq !== this.#seq) return;
|
||||||
|
this.map = new Map(res.vars.map((v) => [v.name, v]));
|
||||||
|
this.dynamic = res.dynamic;
|
||||||
|
this.ready = true;
|
||||||
|
redrawVars();
|
||||||
|
} catch {
|
||||||
|
this.ready = false;
|
||||||
|
}
|
||||||
|
}, 120);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const varsStore = new VarsStore();
|
||||||
@@ -0,0 +1,360 @@
|
|||||||
|
import { api, errorText } from '$lib/api';
|
||||||
|
import type { CollectionView, Request, SendResult, TreeNode } from '$lib/types';
|
||||||
|
import { toast } from '@joshicodes/cock';
|
||||||
|
import { newRequest, normalizeRequest } from '$lib/request';
|
||||||
|
|
||||||
|
export type TabKind = 'request' | 'folder' | 'collection' | 'environment' | 'settings' | 'history';
|
||||||
|
|
||||||
|
export interface ResultState {
|
||||||
|
result: SendResult;
|
||||||
|
/** Decoded body text, filled lazily by the viewer. */
|
||||||
|
bodyText?: string;
|
||||||
|
bodyBytes?: Uint8Array;
|
||||||
|
at: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Tab {
|
||||||
|
key: string;
|
||||||
|
kind: TabKind;
|
||||||
|
col: string | null;
|
||||||
|
/** Request or folder id inside the collection; env id for environment tabs. */
|
||||||
|
id: string | null;
|
||||||
|
title: string;
|
||||||
|
preview: boolean;
|
||||||
|
draft?: Request;
|
||||||
|
saved?: string;
|
||||||
|
sending?: boolean;
|
||||||
|
result?: ResultState;
|
||||||
|
previous?: ResultState;
|
||||||
|
error?: string;
|
||||||
|
diskChanged?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function load<T>(key: string, fallback: T): T {
|
||||||
|
try {
|
||||||
|
const v = localStorage.getItem(key);
|
||||||
|
return v ? (JSON.parse(v) as T) : fallback;
|
||||||
|
} catch {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function store(key: string, value: unknown) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(key, JSON.stringify(value));
|
||||||
|
} catch {
|
||||||
|
/* storage blocked; settings just do not persist */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function snapshot(r: Request | undefined): string {
|
||||||
|
return JSON.stringify(r ?? null);
|
||||||
|
}
|
||||||
|
|
||||||
|
class Workspace {
|
||||||
|
collections = $state<CollectionView[]>([]);
|
||||||
|
envByCol = $state<Record<string, string | null>>(load('knock.env', {}));
|
||||||
|
tabs = $state<Tab[]>([]);
|
||||||
|
activeKey = $state<string | null>(null);
|
||||||
|
layout = $state<'columns' | 'rows'>(load('knock.layout', 'columns'));
|
||||||
|
maskSecrets = $state<boolean>(load('knock.mask', false));
|
||||||
|
sidebarWidth = $state<number>(load('knock.sidebar', 280));
|
||||||
|
paletteOpen = $state(false);
|
||||||
|
/** Collection that new requests and commands act on. */
|
||||||
|
focusCol = $state<string | null>(null);
|
||||||
|
|
||||||
|
get active(): Tab | undefined {
|
||||||
|
return this.tabs.find((t) => t.key === this.activeKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
collection(id: string | null): CollectionView | undefined {
|
||||||
|
return this.collections.find((c) => c.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
env(col: string | null): string | null {
|
||||||
|
if (!col) return null;
|
||||||
|
const c = this.collection(col);
|
||||||
|
const chosen = this.envByCol[col];
|
||||||
|
if (chosen && c?.environments.some((e) => e.id === chosen)) return chosen;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
setEnv(col: string, env: string | null) {
|
||||||
|
this.envByCol[col] = env;
|
||||||
|
store('knock.env', this.envByCol);
|
||||||
|
}
|
||||||
|
|
||||||
|
setLayout(l: 'columns' | 'rows') {
|
||||||
|
this.layout = l;
|
||||||
|
store('knock.layout', l);
|
||||||
|
}
|
||||||
|
|
||||||
|
setMask(m: boolean) {
|
||||||
|
this.maskSecrets = m;
|
||||||
|
store('knock.mask', m);
|
||||||
|
}
|
||||||
|
|
||||||
|
setSidebarWidth(w: number) {
|
||||||
|
this.sidebarWidth = w;
|
||||||
|
store('knock.sidebar', w);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ collections
|
||||||
|
|
||||||
|
async restore() {
|
||||||
|
const open: string[] = load('knock.open', []);
|
||||||
|
for (const root of open) {
|
||||||
|
try {
|
||||||
|
this.upsert(await api.collectionOpen(root));
|
||||||
|
} catch {
|
||||||
|
/* folder moved or deleted; it simply is not reopened */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const savedTabs: { kind: TabKind; col: string | null; id: string | null }[] = load('knock.tabs', []);
|
||||||
|
for (const t of savedTabs) {
|
||||||
|
if (t.kind === 'request' && t.col && t.id) await this.openRequest(t.col, t.id, false);
|
||||||
|
}
|
||||||
|
const active = load<string | null>('knock.activeTab', null);
|
||||||
|
if (active && this.tabs.some((t) => t.key === active)) this.activeKey = active;
|
||||||
|
}
|
||||||
|
|
||||||
|
persistOpen() {
|
||||||
|
store(
|
||||||
|
'knock.open',
|
||||||
|
this.collections.map((c) => c.root)
|
||||||
|
);
|
||||||
|
store(
|
||||||
|
'knock.tabs',
|
||||||
|
this.tabs.filter((t) => t.kind === 'request' && !t.preview).map((t) => ({ kind: t.kind, col: t.col, id: t.id }))
|
||||||
|
);
|
||||||
|
store('knock.activeTab', this.activeKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
upsert(c: CollectionView) {
|
||||||
|
const i = this.collections.findIndex((x) => x.id === c.id);
|
||||||
|
if (i >= 0) this.collections[i] = c;
|
||||||
|
else this.collections.push(c);
|
||||||
|
if (!this.focusCol) this.focusCol = c.id;
|
||||||
|
this.persistOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
async open(path: string) {
|
||||||
|
try {
|
||||||
|
const c = await api.collectionOpen(path);
|
||||||
|
this.upsert(c);
|
||||||
|
this.focusCol = c.id;
|
||||||
|
if (c.problems.length) {
|
||||||
|
toast.warning(`${c.problems.length} file(s) could not be read`, {
|
||||||
|
description: c.problems.map((p) => p.path).join(', ')
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return c;
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not open collection', { description: errorText(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(path: string, name: string) {
|
||||||
|
try {
|
||||||
|
const c = await api.collectionCreate(path, name);
|
||||||
|
this.upsert(c);
|
||||||
|
this.focusCol = c.id;
|
||||||
|
return c;
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not create collection', { description: errorText(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async close(id: string) {
|
||||||
|
const dirty = this.tabs.filter((t) => t.col === id && this.isDirty(t));
|
||||||
|
if (dirty.length && !confirm(`${dirty.length} unsaved request(s) in this collection. Close anyway?`)) return;
|
||||||
|
await api.collectionClose(id);
|
||||||
|
this.collections = this.collections.filter((c) => c.id !== id);
|
||||||
|
this.tabs = this.tabs.filter((t) => t.col !== id);
|
||||||
|
if (!this.tabs.some((t) => t.key === this.activeKey)) this.activeKey = this.tabs.at(-1)?.key ?? null;
|
||||||
|
if (this.focusCol === id) this.focusCol = this.collections[0]?.id ?? null;
|
||||||
|
this.persistOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Called when files changed on disk. Clean tabs reload, dirty ones get a banner. */
|
||||||
|
async onDiskChange(col: string, paths: string[]) {
|
||||||
|
try {
|
||||||
|
this.upsert(await api.collectionGet(col));
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const t of this.tabs) {
|
||||||
|
if (t.col !== col || t.kind !== 'request' || !t.id || !paths.includes(t.id)) continue;
|
||||||
|
let fresh: Request;
|
||||||
|
try {
|
||||||
|
fresh = normalizeRequest(await api.requestGet(col, t.id));
|
||||||
|
} catch {
|
||||||
|
continue; // deleted or mid-write; the tree already reflects it
|
||||||
|
}
|
||||||
|
if (snapshot(fresh) === t.saved) continue;
|
||||||
|
if (this.isDirty(t)) t.diskChanged = true;
|
||||||
|
else {
|
||||||
|
t.draft = fresh;
|
||||||
|
t.saved = snapshot(fresh);
|
||||||
|
t.title = fresh.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ tabs
|
||||||
|
|
||||||
|
isDirty(t: Tab): boolean {
|
||||||
|
return t.kind === 'request' && t.draft !== undefined && snapshot(t.draft) !== t.saved;
|
||||||
|
}
|
||||||
|
|
||||||
|
activate(key: string) {
|
||||||
|
this.activeKey = key;
|
||||||
|
const t = this.active;
|
||||||
|
if (t?.col) this.focusCol = t.col;
|
||||||
|
this.persistOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
async openRequest(col: string, id: string, preview = true) {
|
||||||
|
const key = `${col}:${id}`;
|
||||||
|
const existing = this.tabs.find((t) => t.key === key);
|
||||||
|
if (existing) {
|
||||||
|
if (!preview) existing.preview = false;
|
||||||
|
this.activate(key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let req: Request;
|
||||||
|
try {
|
||||||
|
req = normalizeRequest(await api.requestGet(col, id));
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not open request', { description: errorText(e) });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const tab: Tab = {
|
||||||
|
key,
|
||||||
|
kind: 'request',
|
||||||
|
col,
|
||||||
|
id,
|
||||||
|
title: req.name,
|
||||||
|
preview,
|
||||||
|
draft: req,
|
||||||
|
saved: snapshot(req)
|
||||||
|
};
|
||||||
|
this.insertTab(tab);
|
||||||
|
}
|
||||||
|
|
||||||
|
openSpecial(kind: TabKind, col: string | null, id: string | null, title: string) {
|
||||||
|
const key = `${kind}:${col ?? ''}:${id ?? ''}`;
|
||||||
|
if (this.tabs.some((t) => t.key === key)) return this.activate(key);
|
||||||
|
this.insertTab({ key, kind, col, id, title, preview: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
private insertTab(tab: Tab) {
|
||||||
|
const previewIdx = tab.preview ? this.tabs.findIndex((t) => t.preview && !this.isDirty(t)) : -1;
|
||||||
|
if (previewIdx >= 0) this.tabs[previewIdx] = tab;
|
||||||
|
else {
|
||||||
|
const at = this.tabs.findIndex((t) => t.key === this.activeKey);
|
||||||
|
this.tabs.splice(at >= 0 ? at + 1 : this.tabs.length, 0, tab);
|
||||||
|
}
|
||||||
|
this.activate(tab.key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A scratch request that lives only in a tab until saved. */
|
||||||
|
newScratch(kind: Request['type'] = 'http') {
|
||||||
|
const req = newRequest(kind);
|
||||||
|
const key = `scratch:${crypto.randomUUID()}`;
|
||||||
|
this.insertTab({
|
||||||
|
key,
|
||||||
|
kind: 'request',
|
||||||
|
col: this.focusCol,
|
||||||
|
id: null,
|
||||||
|
title: req.name,
|
||||||
|
preview: false,
|
||||||
|
draft: req,
|
||||||
|
saved: ''
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pin(key: string) {
|
||||||
|
const t = this.tabs.find((x) => x.key === key);
|
||||||
|
if (t) t.preview = false;
|
||||||
|
this.persistOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
closeTab(key: string, force = false) {
|
||||||
|
const i = this.tabs.findIndex((t) => t.key === key);
|
||||||
|
if (i < 0) return;
|
||||||
|
const t = this.tabs[i];
|
||||||
|
if (!force && this.isDirty(t) && !confirm(`"${t.title}" has unsaved changes. Close anyway?`)) return;
|
||||||
|
if (t.sending) api.cancel(t.key);
|
||||||
|
this.tabs.splice(i, 1);
|
||||||
|
if (this.activeKey === key) {
|
||||||
|
this.activeKey = this.tabs[Math.min(i, this.tabs.length - 1)]?.key ?? null;
|
||||||
|
}
|
||||||
|
this.persistOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
moveTab(from: number, to: number) {
|
||||||
|
const [t] = this.tabs.splice(from, 1);
|
||||||
|
this.tabs.splice(to, 0, t);
|
||||||
|
this.persistOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rename/move in the tree changes ids; keep open tabs pointing at the right file. */
|
||||||
|
retarget(col: string, oldId: string, newId: string) {
|
||||||
|
for (const t of this.tabs) {
|
||||||
|
if (t.col !== col || !t.id) continue;
|
||||||
|
if (t.id === oldId || t.id.startsWith(oldId + '/')) {
|
||||||
|
t.id = newId + t.id.slice(oldId.length);
|
||||||
|
t.key = `${col}:${t.id}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.activeKey?.startsWith(`${col}:${oldId}`)) {
|
||||||
|
this.activeKey = `${col}:${newId}${this.activeKey.slice(`${col}:${oldId}`.length)}`;
|
||||||
|
}
|
||||||
|
this.persistOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
async save(tab: Tab | undefined = this.active): Promise<boolean> {
|
||||||
|
if (!tab || tab.kind !== 'request' || !tab.draft) return false;
|
||||||
|
if (!tab.col) {
|
||||||
|
toast.info('Open or create a collection to save requests');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!tab.id) {
|
||||||
|
const r = await api.requestCreate(tab.col, '', tab.draft);
|
||||||
|
this.upsert(r.collection);
|
||||||
|
const oldKey = tab.key;
|
||||||
|
tab.id = r.id;
|
||||||
|
tab.key = `${tab.col}:${r.id}`;
|
||||||
|
if (this.activeKey === oldKey) this.activeKey = tab.key;
|
||||||
|
} else {
|
||||||
|
this.upsert(await api.requestSave(tab.col, tab.id, tab.draft));
|
||||||
|
}
|
||||||
|
tab.saved = snapshot(tab.draft);
|
||||||
|
tab.title = tab.draft.name;
|
||||||
|
tab.preview = false;
|
||||||
|
tab.diskChanged = false;
|
||||||
|
this.persistOpen();
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not save', { description: errorText(e) });
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
findNode(col: string, id: string): TreeNode | undefined {
|
||||||
|
const walk = (nodes: TreeNode[]): TreeNode | undefined => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
if (n.id === id) return n;
|
||||||
|
if (n.node === 'folder') {
|
||||||
|
const f = walk(n.children);
|
||||||
|
if (f) return f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const c = this.collection(col);
|
||||||
|
return c ? walk(c.tree.children) : undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ws = new Workspace();
|
||||||
@@ -0,0 +1,338 @@
|
|||||||
|
// Mirrors the Rust model in crates/knock-core/src/model.rs. Unknown keys are
|
||||||
|
// carried along untouched, so objects are spread, never rebuilt field by field.
|
||||||
|
|
||||||
|
export type Json = null | boolean | number | string | Json[] | { [k: string]: Json };
|
||||||
|
|
||||||
|
export interface KeyValue {
|
||||||
|
name: string;
|
||||||
|
value: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
description?: string;
|
||||||
|
[extra: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RequestKind = 'http' | 'graphql' | 'ws';
|
||||||
|
export type BodyType = 'none' | 'json' | 'raw' | 'form' | 'multipart' | 'binary';
|
||||||
|
|
||||||
|
export interface MultipartPart {
|
||||||
|
name: string;
|
||||||
|
value?: string;
|
||||||
|
file?: string;
|
||||||
|
content_type?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Body {
|
||||||
|
type: BodyType;
|
||||||
|
content?: string;
|
||||||
|
content_type?: string;
|
||||||
|
jsonc?: boolean;
|
||||||
|
form?: KeyValue[];
|
||||||
|
multipart?: MultipartPart[];
|
||||||
|
file?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthConfig {
|
||||||
|
type: string;
|
||||||
|
[field: string]: Json | undefined;
|
||||||
|
}
|
||||||
|
export type Auth = 'inherit' | 'none' | AuthConfig;
|
||||||
|
|
||||||
|
export interface ExtractRule {
|
||||||
|
var: string;
|
||||||
|
from: 'json' | 'header' | 'cookie' | 'regex' | 'status';
|
||||||
|
path: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
persist?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AssertTarget = 'status' | 'header' | 'time' | 'json' | 'size' | 'body';
|
||||||
|
export interface AssertRule {
|
||||||
|
on: AssertTarget;
|
||||||
|
path?: string;
|
||||||
|
equals?: Json;
|
||||||
|
not_equals?: Json;
|
||||||
|
contains?: Json;
|
||||||
|
exists?: boolean;
|
||||||
|
type?: string;
|
||||||
|
matches?: string;
|
||||||
|
gt?: number;
|
||||||
|
lt?: number;
|
||||||
|
enabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RequestSettings {
|
||||||
|
timeout_ms: number;
|
||||||
|
follow_redirects: boolean;
|
||||||
|
max_redirects: number;
|
||||||
|
verify_tls: boolean;
|
||||||
|
http_version: 'auto' | '1.1' | '2';
|
||||||
|
cookies: boolean;
|
||||||
|
retry_on_401: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GraphqlSpec {
|
||||||
|
query: string;
|
||||||
|
variables?: string;
|
||||||
|
operation_name?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WsSavedMessage {
|
||||||
|
name: string;
|
||||||
|
format: 'text' | 'json' | 'hex';
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WsSpec {
|
||||||
|
subprotocols?: string[];
|
||||||
|
messages?: WsSavedMessage[];
|
||||||
|
auto_reconnect?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Request {
|
||||||
|
name: string;
|
||||||
|
type: RequestKind;
|
||||||
|
method?: string;
|
||||||
|
url: string;
|
||||||
|
params?: { query: KeyValue[]; path: Record<string, string> };
|
||||||
|
headers?: KeyValue[];
|
||||||
|
auth: Auth;
|
||||||
|
body?: Body;
|
||||||
|
graphql?: GraphqlSpec;
|
||||||
|
ws?: WsSpec;
|
||||||
|
vars?: Record<string, string>;
|
||||||
|
extract?: ExtractRule[];
|
||||||
|
assert?: AssertRule[];
|
||||||
|
settings?: RequestSettings;
|
||||||
|
schema?: Json;
|
||||||
|
docs?: string;
|
||||||
|
[extra: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RequestHead {
|
||||||
|
node: 'request';
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: RequestKind;
|
||||||
|
method?: string;
|
||||||
|
}
|
||||||
|
export interface FolderNode {
|
||||||
|
node?: 'folder';
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
children: TreeNode[];
|
||||||
|
}
|
||||||
|
export type TreeNode = RequestHead | (FolderNode & { node: 'folder' });
|
||||||
|
|
||||||
|
export interface EnvEntry {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
color?: string | null;
|
||||||
|
protected: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CollectionView {
|
||||||
|
id: string;
|
||||||
|
root: string;
|
||||||
|
name: string;
|
||||||
|
tree: FolderNode;
|
||||||
|
environments: EnvEntry[];
|
||||||
|
problems: { path: string; message: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FolderMeta {
|
||||||
|
name?: string;
|
||||||
|
order?: string[];
|
||||||
|
auth?: Auth;
|
||||||
|
headers?: KeyValue[];
|
||||||
|
vars?: Record<string, string>;
|
||||||
|
[extra: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProxySettings {
|
||||||
|
mode: 'system' | 'none' | 'custom';
|
||||||
|
url?: string;
|
||||||
|
no_proxy?: string;
|
||||||
|
}
|
||||||
|
export interface ClientCert {
|
||||||
|
host: string;
|
||||||
|
cert?: string;
|
||||||
|
key?: string;
|
||||||
|
pkcs12?: string;
|
||||||
|
passphrase?: string;
|
||||||
|
}
|
||||||
|
export interface Manifest {
|
||||||
|
version: number;
|
||||||
|
name: string;
|
||||||
|
id: string;
|
||||||
|
auth?: Auth;
|
||||||
|
headers?: KeyValue[];
|
||||||
|
vars?: Record<string, string>;
|
||||||
|
order?: string[];
|
||||||
|
settings?: {
|
||||||
|
proxy?: ProxySettings;
|
||||||
|
ca_bundle?: string;
|
||||||
|
client_certs?: ClientCert[];
|
||||||
|
cookies?: boolean;
|
||||||
|
};
|
||||||
|
[extra: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EnvVarValue = string | { value?: string; secret?: boolean; description?: string };
|
||||||
|
export interface Environment {
|
||||||
|
name?: string;
|
||||||
|
color?: string;
|
||||||
|
protected?: boolean;
|
||||||
|
vars: Record<string, EnvVarValue>;
|
||||||
|
[extra: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Scope =
|
||||||
|
| 'runtime'
|
||||||
|
| 'request'
|
||||||
|
| 'folder'
|
||||||
|
| 'environment'
|
||||||
|
| 'collection'
|
||||||
|
| 'global'
|
||||||
|
| 'secret'
|
||||||
|
| 'dynamic'
|
||||||
|
| 'oauth';
|
||||||
|
|
||||||
|
export interface VarInfo {
|
||||||
|
name: string;
|
||||||
|
value: string | null;
|
||||||
|
scope: Scope | null;
|
||||||
|
source: string | null;
|
||||||
|
secret: boolean;
|
||||||
|
problem: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- results
|
||||||
|
|
||||||
|
export interface Timings {
|
||||||
|
ttfb_ms: number;
|
||||||
|
download_ms: number;
|
||||||
|
total_ms: number;
|
||||||
|
redirect_ms: number;
|
||||||
|
}
|
||||||
|
export interface Hop {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
status: number;
|
||||||
|
location: string;
|
||||||
|
headers: [string, string][];
|
||||||
|
ms: number;
|
||||||
|
}
|
||||||
|
export interface CookieInfo {
|
||||||
|
name: string;
|
||||||
|
value: string;
|
||||||
|
domain: string;
|
||||||
|
path: string;
|
||||||
|
expires: string | null;
|
||||||
|
secure: boolean;
|
||||||
|
http_only: boolean;
|
||||||
|
same_site: string | null;
|
||||||
|
}
|
||||||
|
export interface Response {
|
||||||
|
status: number;
|
||||||
|
status_text: string;
|
||||||
|
http_version: string;
|
||||||
|
url: string;
|
||||||
|
headers: [string, string][];
|
||||||
|
cookies: CookieInfo[];
|
||||||
|
size: number;
|
||||||
|
header_size: number;
|
||||||
|
content_type: string | null;
|
||||||
|
timings: Timings;
|
||||||
|
redirects: Hop[];
|
||||||
|
remote_addr: string | null;
|
||||||
|
body_file: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type StepStatus = 'ok' | 'error' | 'skipped' | 'pending' | 'warning';
|
||||||
|
export interface Exchange {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
request_headers: [string, string][];
|
||||||
|
request_body: string;
|
||||||
|
status: number | null;
|
||||||
|
response_headers: [string, string][];
|
||||||
|
response_body: string;
|
||||||
|
curl: string;
|
||||||
|
}
|
||||||
|
export interface Step {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
status: StepStatus;
|
||||||
|
at: string;
|
||||||
|
duration_ms: number;
|
||||||
|
summary: string;
|
||||||
|
hint: string | null;
|
||||||
|
exchange: Exchange | null;
|
||||||
|
data: Json;
|
||||||
|
}
|
||||||
|
export interface AuthDebug {
|
||||||
|
kind: string;
|
||||||
|
origin: string | null;
|
||||||
|
source: string | null;
|
||||||
|
steps: Step[];
|
||||||
|
sent: { location: string; name: string; value: string }[];
|
||||||
|
warnings: string[];
|
||||||
|
flow_id: string | null;
|
||||||
|
}
|
||||||
|
export interface SentRequest {
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
headers: [string, string][];
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
export interface AssertResult {
|
||||||
|
index: number;
|
||||||
|
label: string;
|
||||||
|
passed: boolean;
|
||||||
|
expected: string;
|
||||||
|
actual: string;
|
||||||
|
}
|
||||||
|
export interface Extracted {
|
||||||
|
var: string;
|
||||||
|
value: string | null;
|
||||||
|
persist: boolean;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
export interface RunOutput {
|
||||||
|
request: SentRequest | null;
|
||||||
|
response: Response | null;
|
||||||
|
auth: AuthDebug;
|
||||||
|
asserts: AssertResult[];
|
||||||
|
extracted: Extracted[];
|
||||||
|
error: string | null;
|
||||||
|
missing: string[];
|
||||||
|
retried: boolean;
|
||||||
|
}
|
||||||
|
export interface SendResult {
|
||||||
|
output: RunOutput;
|
||||||
|
body_id: string | null;
|
||||||
|
history_id: number | null;
|
||||||
|
body_file: string | null;
|
||||||
|
}
|
||||||
|
export interface Preview {
|
||||||
|
request: SentRequest | null;
|
||||||
|
auth: AuthDebug;
|
||||||
|
missing: string[];
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HistoryEntry {
|
||||||
|
id: number;
|
||||||
|
at: string;
|
||||||
|
collection: string;
|
||||||
|
request_id: string | null;
|
||||||
|
name: string;
|
||||||
|
method: string;
|
||||||
|
url: string;
|
||||||
|
status: number | null;
|
||||||
|
duration_ms: number | null;
|
||||||
|
size: number | null;
|
||||||
|
error: string | null;
|
||||||
|
has_body: boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
// Small stroke icons drawn on a 16px grid, so they sit on the same baseline
|
||||||
|
// as 13px UI text.
|
||||||
|
const paths: Record<string, string> = {
|
||||||
|
'chevron-right': 'M6 4l4 4-4 4',
|
||||||
|
'chevron-down': 'M4 6l4 4 4-4',
|
||||||
|
'chevron-up': 'M4 10l4-4 4 4',
|
||||||
|
plus: 'M8 3v10M3 8h10',
|
||||||
|
x: 'M4 4l8 8M12 4l-8 8',
|
||||||
|
minus: 'M3 8h10',
|
||||||
|
search: 'M7 12A5 5 0 1 0 7 2a5 5 0 0 0 0 10zM14 14l-3.5-3.5',
|
||||||
|
more: 'M3.5 8h.01M8 8h.01M12.5 8h.01',
|
||||||
|
folder: 'M2 4.5A1.5 1.5 0 0 1 3.5 3h3l1.5 1.5h4.5A1.5 1.5 0 0 1 14 6v5.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 11.5z',
|
||||||
|
file: 'M4 2h5l3 3v9H4zM9 2v3h3',
|
||||||
|
copy: 'M5.5 5.5h7v7h-7zM3.5 10.5v-7h7',
|
||||||
|
trash: 'M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.5 9h6l.5-9',
|
||||||
|
history: 'M2.5 8a5.5 5.5 0 1 0 1.6-3.9M2.5 2.5v2h2M8 5v3l2 1.5',
|
||||||
|
settings:
|
||||||
|
'M8 10a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM8 1.5v1.8M8 12.7v1.8M1.5 8h1.8M12.7 8h1.8M3.4 3.4l1.3 1.3M11.3 11.3l1.3 1.3M3.4 12.6l1.3-1.3M11.3 4.7l1.3-1.3',
|
||||||
|
eye: 'M1.5 8S4 3.5 8 3.5 14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8zM8 10a2 2 0 1 0 0-4 2 2 0 0 0 0 4z',
|
||||||
|
'eye-off': 'M2 2l12 12M6.6 6.6a2 2 0 0 0 2.8 2.8M4.2 4.4C2.5 5.6 1.5 8 1.5 8S4 12.5 8 12.5c1.3 0 2.4-.4 3.4-1M7 3.6c.3 0 .7-.1 1-.1 4 0 6.5 4.5 6.5 4.5s-.5 1-1.5 2.1',
|
||||||
|
check: 'M3 8.5l3 3 7-7',
|
||||||
|
alert: 'M8 2.5l6 11H2zM8 7v3M8 12h.01',
|
||||||
|
grip: 'M6 4h.01M10 4h.01M6 8h.01M10 8h.01M6 12h.01M10 12h.01',
|
||||||
|
window: 'M3 3h10v10H3z',
|
||||||
|
restore: 'M5 3h8v8M3 5h8v8H3z',
|
||||||
|
globe: 'M8 14.5a6.5 6.5 0 1 0 0-13 6.5 6.5 0 0 0 0 13zM1.5 8h13M8 1.5c-2 2-2 11 0 13M8 1.5c2 2 2 11 0 13',
|
||||||
|
layers: 'M8 2l6 3-6 3-6-3zM2 8l6 3 6-3M2 11l6 3 6-3',
|
||||||
|
columns: 'M2.5 3h11v10h-11zM8 3v10',
|
||||||
|
rows: 'M2.5 3h11v10h-11zM2.5 8h11',
|
||||||
|
key: 'M10 6a3 3 0 1 1-3 3M7 9l-5 5M3.5 12.5l1.5 1.5M5 11l1.5 1.5',
|
||||||
|
lock: 'M4 7h8v6.5H4zM5.5 7V5a2.5 2.5 0 0 1 5 0v2',
|
||||||
|
link: 'M6.5 9.5l3-3M7 4.5l1-1a2.8 2.8 0 0 1 4 4l-1 1M9 11.5l-1 1a2.8 2.8 0 0 1-4-4l1-1',
|
||||||
|
upload: 'M8 11V3M5 6l3-3 3 3M3 13h10',
|
||||||
|
download: 'M8 3v8M5 8l3 3 3-3M3 13h10',
|
||||||
|
refresh: 'M13.5 8A5.5 5.5 0 1 1 11.9 4.1M13.5 2.5v2.5H11',
|
||||||
|
play: 'M5 3l8 5-8 5z',
|
||||||
|
stop: 'M4 4h8v8H4z',
|
||||||
|
edit: 'M10.5 2.5l3 3L6 13H3v-3z',
|
||||||
|
external: 'M9 3h4v4M13 3L7 9M11 9.5V13H3V5h3.5',
|
||||||
|
filter: 'M2.5 3h11L9 8.5V13l-2-1V8.5z',
|
||||||
|
bolt: 'M9 1.5L3.5 9H8l-1 5.5L12.5 7H8z',
|
||||||
|
wrap: 'M2.5 4h11M2.5 8h9a2 2 0 0 1 0 4H9M10.5 10.5 9 12l1.5 1.5M2.5 12h4',
|
||||||
|
door: 'M4 14V2.5h8V14M2.5 14h11M9.5 8.5h.01'
|
||||||
|
};
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
name: string;
|
||||||
|
size?: number;
|
||||||
|
class?: string;
|
||||||
|
stroke?: number;
|
||||||
|
}
|
||||||
|
let { name, size = 14, class: klass = '', stroke = 1.5 }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svg
|
||||||
|
width={size}
|
||||||
|
height={size}
|
||||||
|
viewBox="0 0 16 16"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width={stroke}
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
class="shrink-0 {klass}"
|
||||||
|
aria-hidden="true"><path d={paths[name] ?? ''} /></svg
|
||||||
|
>
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { KeyValue } from '$lib/types';
|
||||||
|
import VarInput from './VarInput.svelte';
|
||||||
|
import Icon from './Icon.svelte';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
rows: KeyValue[];
|
||||||
|
namePlaceholder?: string;
|
||||||
|
valuePlaceholder?: string;
|
||||||
|
nameSuggestions?: string[];
|
||||||
|
valueSuggestions?: (name: string) => string[];
|
||||||
|
separator?: string;
|
||||||
|
bulk?: boolean;
|
||||||
|
readonlyNames?: boolean;
|
||||||
|
onchange?: () => void;
|
||||||
|
}
|
||||||
|
let {
|
||||||
|
rows = $bindable(),
|
||||||
|
namePlaceholder = 'Name',
|
||||||
|
valuePlaceholder = 'Value',
|
||||||
|
nameSuggestions = [],
|
||||||
|
valueSuggestions,
|
||||||
|
separator = ':',
|
||||||
|
bulk = $bindable(false),
|
||||||
|
readonlyNames = false,
|
||||||
|
onchange
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
/** Writing into the trailing empty row turns it into a real row in place, so focus stays put. */
|
||||||
|
function set(i: number, field: 'name' | 'value', v: string) {
|
||||||
|
if (i >= rows.length) rows.push({ name: '', value: '', [field]: v });
|
||||||
|
else rows[i][field] = v;
|
||||||
|
onchange?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toText(rs: KeyValue[]) {
|
||||||
|
return rs.map((r) => `${r.enabled === false ? '// ' : ''}${r.name}${separator} ${r.value}`).join('\n');
|
||||||
|
}
|
||||||
|
let bulkText = $state('');
|
||||||
|
$effect(() => {
|
||||||
|
if (bulk) bulkText = toText(rows);
|
||||||
|
});
|
||||||
|
|
||||||
|
function fromText(text: string) {
|
||||||
|
const out: KeyValue[] = [];
|
||||||
|
for (const raw of text.split('\n')) {
|
||||||
|
if (!raw.trim()) continue;
|
||||||
|
let line = raw;
|
||||||
|
let enabled = true;
|
||||||
|
if (line.trimStart().startsWith('//')) {
|
||||||
|
enabled = false;
|
||||||
|
line = line.trimStart().slice(2).trimStart();
|
||||||
|
}
|
||||||
|
const i = line.indexOf(separator);
|
||||||
|
const name = (i < 0 ? line : line.slice(0, i)).trim();
|
||||||
|
const value = i < 0 ? '' : line.slice(i + separator.length).trim();
|
||||||
|
const prev = rows.find((r) => r.name === name);
|
||||||
|
out.push({ ...(prev ?? {}), name, value, ...(enabled ? { enabled: undefined } : { enabled: false }) });
|
||||||
|
}
|
||||||
|
rows = out;
|
||||||
|
onchange?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
function remove(i: number) {
|
||||||
|
rows.splice(i, 1);
|
||||||
|
onchange?.();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if bulk}
|
||||||
|
<textarea
|
||||||
|
class="k-field mono h-full min-h-[160px] w-full resize-none !border-line !bg-input p-2 leading-relaxed"
|
||||||
|
bind:value={bulkText}
|
||||||
|
spellcheck="false"
|
||||||
|
oninput={() => fromText(bulkText)}
|
||||||
|
placeholder="Name{separator} value, one per line. Prefix with // to disable."
|
||||||
|
></textarea>
|
||||||
|
{:else}
|
||||||
|
<div class="flex flex-col text-[12.5px]">
|
||||||
|
{#each readonlyNames ? rows : [...rows, null] as row, i (i)}
|
||||||
|
{@const real = row !== null}
|
||||||
|
<div class="group flex items-center gap-1 border-b border-line/60 py-0.5 {row?.enabled === false ? 'opacity-55' : ''}">
|
||||||
|
{#if real}
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="mx-1.5 size-3.5 accent-[var(--knock-cyan)]"
|
||||||
|
checked={row.enabled !== false}
|
||||||
|
title={row.enabled === false ? 'Disabled' : 'Enabled'}
|
||||||
|
onchange={(e) => {
|
||||||
|
rows[i].enabled = (e.currentTarget as HTMLInputElement).checked ? undefined : false;
|
||||||
|
onchange?.();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<span class="mx-1.5 size-3.5 shrink-0"></span>
|
||||||
|
{/if}
|
||||||
|
<div class="flex w-[38%] min-w-0">
|
||||||
|
{#if readonlyNames}
|
||||||
|
<span class="mono truncate px-[7px] py-[5px] text-soft">{row?.name}</span>
|
||||||
|
{:else}
|
||||||
|
<VarInput value={row?.name ?? ''} placeholder={namePlaceholder} suggestions={nameSuggestions} oninput={(v) => set(i, 'name', v)} />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<div class="flex min-w-0 flex-1">
|
||||||
|
<VarInput value={row?.value ?? ''} placeholder={valuePlaceholder} suggestions={valueSuggestions?.(row?.name ?? '') ?? []} oninput={(v) => set(i, 'value', v)} />
|
||||||
|
</div>
|
||||||
|
{#if real}
|
||||||
|
<button class="grid size-6 place-items-center rounded text-fg-subtle opacity-0 hover:text-delete group-hover:opacity-100" title="Remove" onclick={() => remove(i)}>
|
||||||
|
<Icon name="x" size={12} />
|
||||||
|
</button>
|
||||||
|
{:else}
|
||||||
|
<span class="size-6 shrink-0"></span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
// The knock mark (DESIGN.md: ring r36 stroke 12, chevron stroke 10), in currentColor.
|
||||||
|
// Below 24px the favicon geometry is used so it does not fall apart.
|
||||||
|
let { size = 18, class: klass = '' }: { size?: number; class?: string } = $props();
|
||||||
|
let small = $derived(size < 24);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svg width={size} height={size} viewBox="0 0 100 100" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" class={klass} aria-hidden="true">
|
||||||
|
<circle cx="50" cy="50" r="36" stroke-width={small ? 16 : 12} />
|
||||||
|
<path d={small ? 'M46 40 L55 50 L46 60' : 'M45 40 L55 50 L45 60'} stroke-width={small ? 15 : 10} />
|
||||||
|
</svg>
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { varsStore } from '$lib/state/vars.svelte';
|
||||||
|
import { varTooltip } from '$lib/editor/cm';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
value: string;
|
||||||
|
placeholder?: string;
|
||||||
|
class?: string;
|
||||||
|
mono?: boolean;
|
||||||
|
secret?: boolean;
|
||||||
|
suggestions?: string[];
|
||||||
|
oninput?: (v: string) => void;
|
||||||
|
onkeydown?: (e: KeyboardEvent) => void;
|
||||||
|
onblur?: () => void;
|
||||||
|
}
|
||||||
|
let {
|
||||||
|
value = $bindable(''),
|
||||||
|
placeholder = '',
|
||||||
|
class: klass = '',
|
||||||
|
mono = true,
|
||||||
|
secret = false,
|
||||||
|
suggestions = [],
|
||||||
|
oninput,
|
||||||
|
onkeydown,
|
||||||
|
onblur
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
let input: HTMLInputElement;
|
||||||
|
let mirror: HTMLDivElement;
|
||||||
|
let focused = $state(false);
|
||||||
|
let reveal = $state(false);
|
||||||
|
let menu = $state<{ items: { label: string; detail: string; insert: string }[]; index: number; from: number } | null>(null);
|
||||||
|
let tip = $state<{ x: number; y: number; el: HTMLElement } | null>(null);
|
||||||
|
|
||||||
|
type Part = { text: string; var?: string; missing?: boolean };
|
||||||
|
let parts = $derived.by((): Part[] => {
|
||||||
|
const out: Part[] = [];
|
||||||
|
const re = /\{\{\s*([^{}]+?)\s*\}\}/g;
|
||||||
|
let last = 0;
|
||||||
|
let m: RegExpExecArray | null;
|
||||||
|
const v = value ?? '';
|
||||||
|
while ((m = re.exec(v))) {
|
||||||
|
if (m.index > last) out.push({ text: v.slice(last, m.index) });
|
||||||
|
const name = m[1];
|
||||||
|
const missing =
|
||||||
|
varsStore.ready && !name.startsWith('$') && !name.startsWith('secret.') && !name.startsWith('oauth.') && !varsStore.map.has(name);
|
||||||
|
out.push({ text: m[0], var: name, missing });
|
||||||
|
last = m.index + m[0].length;
|
||||||
|
}
|
||||||
|
if (last < v.length) out.push({ text: v.slice(last) });
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
|
||||||
|
let masked = $derived(secret && !reveal && !focused && !!value && !/\{\{/.test(value));
|
||||||
|
|
||||||
|
function syncScroll() {
|
||||||
|
if (mirror && input) mirror.scrollLeft = input.scrollLeft;
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeMenu() {
|
||||||
|
const pos = input.selectionStart ?? 0;
|
||||||
|
const before = value.slice(0, pos);
|
||||||
|
const open = before.lastIndexOf('{{');
|
||||||
|
if (open >= 0 && !before.slice(open).includes('}}')) {
|
||||||
|
const q = before.slice(open + 2).trim().toLowerCase();
|
||||||
|
const items = [
|
||||||
|
...[...varsStore.map.values()].map((v) => ({ label: v.name, detail: v.scope ?? '', insert: v.name })),
|
||||||
|
...varsStore.dynamic.map(([n, d]) => ({ label: n, detail: d, insert: n.replace('(...)', '()') }))
|
||||||
|
]
|
||||||
|
.filter((i) => i.label.toLowerCase().includes(q))
|
||||||
|
.slice(0, 12);
|
||||||
|
menu = items.length ? { items, index: 0, from: open + 2 } : null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (suggestions.length && document.activeElement === input) {
|
||||||
|
const q = value.toLowerCase();
|
||||||
|
const items = suggestions
|
||||||
|
.filter((s) => s.toLowerCase().startsWith(q) && s.toLowerCase() !== q)
|
||||||
|
.slice(0, 10)
|
||||||
|
.map((s) => ({ label: s, detail: '', insert: s }));
|
||||||
|
menu = items.length ? { items, index: 0, from: -1 } : null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
menu = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pick(i: number) {
|
||||||
|
if (!menu) return;
|
||||||
|
const item = menu.items[i];
|
||||||
|
if (menu.from < 0) {
|
||||||
|
value = item.insert;
|
||||||
|
} else {
|
||||||
|
const pos = input.selectionStart ?? value.length;
|
||||||
|
const after = value.slice(pos);
|
||||||
|
const close = after.startsWith('}}') ? '' : '}}';
|
||||||
|
value = value.slice(0, menu.from) + item.insert + close + after;
|
||||||
|
const caret = menu.from + item.insert.length + 2;
|
||||||
|
queueMicrotask(() => input.setSelectionRange(caret, caret));
|
||||||
|
}
|
||||||
|
menu = null;
|
||||||
|
oninput?.(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function keydown(e: KeyboardEvent) {
|
||||||
|
if (menu) {
|
||||||
|
if (e.key === 'ArrowDown') {
|
||||||
|
e.preventDefault();
|
||||||
|
menu.index = (menu.index + 1) % menu.items.length;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.key === 'ArrowUp') {
|
||||||
|
e.preventDefault();
|
||||||
|
menu.index = (menu.index - 1 + menu.items.length) % menu.items.length;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.key === 'Enter' || e.key === 'Tab') {
|
||||||
|
e.preventDefault();
|
||||||
|
pick(menu.index);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
e.stopPropagation();
|
||||||
|
menu = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onkeydown?.(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hover(e: MouseEvent) {
|
||||||
|
// The input sits on top, so find the var under the pointer via the mirror.
|
||||||
|
const spans = mirror?.querySelectorAll<HTMLElement>('[data-var]');
|
||||||
|
if (!spans) return;
|
||||||
|
for (const s of spans) {
|
||||||
|
const r = s.getBoundingClientRect();
|
||||||
|
if (e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) {
|
||||||
|
if (tip?.el.dataset.name !== s.dataset.var) {
|
||||||
|
const el = varTooltip(s.dataset.var!);
|
||||||
|
el.dataset.name = s.dataset.var!;
|
||||||
|
tip = { x: r.left, y: r.top, el };
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tip = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mountTip(node: HTMLElement, el: HTMLElement) {
|
||||||
|
node.append(el);
|
||||||
|
return {
|
||||||
|
update(next: HTMLElement) {
|
||||||
|
node.replaceChildren(next);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="relative min-w-0 flex-1 {klass}">
|
||||||
|
<div
|
||||||
|
bind:this={mirror}
|
||||||
|
aria-hidden="true"
|
||||||
|
class="pointer-events-none absolute inset-0 overflow-hidden whitespace-pre px-[7px] py-[5px] text-[12.5px] leading-[18px] {mono ? 'mono' : ''}"
|
||||||
|
>
|
||||||
|
{#if masked}
|
||||||
|
<span class="text-fg-muted">{'•'.repeat(Math.min(24, value.length))}</span>
|
||||||
|
{:else}
|
||||||
|
{#each parts as p}{#if p.var}<span data-var={p.var} class={p.missing ? 'cm-var-missing' : 'cm-var'}>{p.text}</span>{:else}<span class="text-fg">{p.text}</span>{/if}{/each}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
bind:this={input}
|
||||||
|
bind:value
|
||||||
|
{placeholder}
|
||||||
|
spellcheck="false"
|
||||||
|
autocomplete="off"
|
||||||
|
class="k-field relative !bg-transparent !text-transparent caret-[var(--k-text)] leading-[18px] {mono ? '' : '!font-sans'} {focused ? '!bg-input' : ''}"
|
||||||
|
style="-webkit-text-fill-color: transparent"
|
||||||
|
oninput={() => {
|
||||||
|
computeMenu();
|
||||||
|
syncScroll();
|
||||||
|
oninput?.(value);
|
||||||
|
}}
|
||||||
|
onscroll={syncScroll}
|
||||||
|
onkeydown={keydown}
|
||||||
|
onkeyup={syncScroll}
|
||||||
|
onclick={syncScroll}
|
||||||
|
onfocus={() => (focused = true)}
|
||||||
|
onblur={() => {
|
||||||
|
focused = false;
|
||||||
|
setTimeout(() => (menu = null), 120);
|
||||||
|
onblur?.();
|
||||||
|
}}
|
||||||
|
onmousemove={hover}
|
||||||
|
onmouseleave={() => (tip = null)}
|
||||||
|
/>
|
||||||
|
{#if secret && value && !/\{\{/.test(value)}
|
||||||
|
<button
|
||||||
|
class="absolute right-1 top-1/2 -translate-y-1/2 px-1 text-[11px] text-fg-subtle hover:text-fg"
|
||||||
|
onclick={() => (reveal = !reveal)}
|
||||||
|
tabindex="-1">{reveal ? 'hide' : 'show'}</button
|
||||||
|
>
|
||||||
|
{/if}
|
||||||
|
{#if menu}
|
||||||
|
<div class="absolute left-0 top-full z-50 mt-1 max-h-64 min-w-[240px] overflow-auto rounded border border-line bg-input py-1 shadow-lg">
|
||||||
|
{#each menu.items as item, i}
|
||||||
|
<button
|
||||||
|
class="flex w-full items-baseline gap-3 px-2.5 py-1 text-left {i === menu.index ? 'bg-accent-soft text-strong' : 'text-fg'}"
|
||||||
|
onmousedown={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
pick(i);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span class="mono text-[12px]">{item.label}</span>
|
||||||
|
<span class="truncate text-[11px] text-fg-subtle">{item.detail}</span>
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if tip}
|
||||||
|
<div class="fixed z-50 rounded border border-line bg-input shadow-lg" style:left="{tip.x}px" style:top="{tip.y - 6}px" style:transform="translateY(-100%)" use:mountTip={tip.el}></div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { DropdownMenu, MenuItem, MenuLabel, MenuSeparator } from '@joshicodes/cock';
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import { ws } from '$lib/state/workspace.svelte';
|
||||||
|
import { ui } from '$lib/state/ui.svelte';
|
||||||
|
|
||||||
|
let { col }: { col: string } = $props();
|
||||||
|
let collection = $derived(ws.collection(col));
|
||||||
|
let current = $derived(collection?.environments.find((e) => e.id === ws.env(col)));
|
||||||
|
let open = $state(false);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (ui.envMenuRequest > 0) open = true;
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if collection}
|
||||||
|
<DropdownMenu bind:open label="Environment" placement="bottom-start">
|
||||||
|
{#snippet trigger(attrs)}
|
||||||
|
<button
|
||||||
|
{...attrs}
|
||||||
|
class="flex h-7 max-w-[260px] items-center gap-2 rounded border border-line bg-panel pr-2 text-left hover:border-border-strong"
|
||||||
|
title="Environment (Ctrl+E)"
|
||||||
|
>
|
||||||
|
<span class="h-full w-1 shrink-0 rounded-l" style:background={current?.color ?? 'transparent'}></span>
|
||||||
|
<span class="truncate text-fg-muted">{collection.name}</span>
|
||||||
|
<span class="text-fg-subtle">/</span>
|
||||||
|
<span class="truncate {current ? 'text-strong' : 'text-fg-subtle'}">{current?.name ?? 'No environment'}</span>
|
||||||
|
{#if current?.protected}
|
||||||
|
<Icon name="lock" size={12} class="text-post" />
|
||||||
|
{/if}
|
||||||
|
<Icon name="chevron-down" size={12} class="text-fg-subtle" />
|
||||||
|
</button>
|
||||||
|
{/snippet}
|
||||||
|
<MenuLabel>{collection.name}</MenuLabel>
|
||||||
|
<MenuItem onselect={() => ws.setEnv(col, null)}>
|
||||||
|
{#snippet icon()}<Icon name={!current ? 'check' : 'minus'} class={!current ? '' : 'opacity-0'} />{/snippet}
|
||||||
|
No environment
|
||||||
|
</MenuItem>
|
||||||
|
{#each collection.environments as env (env.id)}
|
||||||
|
<MenuItem onselect={() => ws.setEnv(col, env.id)} hint={env.protected ? 'protected' : undefined}>
|
||||||
|
{#snippet icon()}<Icon name="check" class={current?.id === env.id ? '' : 'opacity-0'} />{/snippet}
|
||||||
|
<span class="flex items-center gap-2">
|
||||||
|
{#if env.color}<span class="inline-block size-2.5 rounded-sm" style:background={env.color}></span>{/if}
|
||||||
|
{env.name}
|
||||||
|
</span>
|
||||||
|
</MenuItem>
|
||||||
|
{/each}
|
||||||
|
<MenuSeparator />
|
||||||
|
<MenuItem onselect={() => ws.openSpecial('environment', col, current?.id ?? collection.environments[0]?.id ?? null, 'Environments')}>
|
||||||
|
{#snippet icon()}<Icon name="layers" />{/snippet}
|
||||||
|
Manage environments
|
||||||
|
</MenuItem>
|
||||||
|
{#if ws.collections.length > 1}
|
||||||
|
<MenuSeparator />
|
||||||
|
<MenuLabel>Switch collection</MenuLabel>
|
||||||
|
{#each ws.collections.filter((c) => c.id !== col) as c (c.id)}
|
||||||
|
<MenuItem onselect={() => (ws.focusCol = c.id)}>{c.name}</MenuItem>
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
</DropdownMenu>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import { api } from '$lib/api';
|
||||||
|
import type { HistoryEntry } from '$lib/types';
|
||||||
|
import { formatMs, methodColor, statusColor, normalizeRequest } from '$lib/request';
|
||||||
|
import { ws } from '$lib/state/workspace.svelte';
|
||||||
|
import { dialogs } from '$lib/state/dialogs.svelte';
|
||||||
|
import { RelativeTime } from '@joshicodes/cock';
|
||||||
|
|
||||||
|
let query = $state('');
|
||||||
|
let entries = $state<HistoryEntry[]>([]);
|
||||||
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
entries = await api.history(query.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
query;
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = setTimeout(load, 150);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Refresh when a request finishes anywhere.
|
||||||
|
$effect(() => {
|
||||||
|
ws.tabs.map((t) => t.result?.at).join();
|
||||||
|
load();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function openEntry(h: HistoryEntry) {
|
||||||
|
const d = await api.historyGet(h.id);
|
||||||
|
const req = normalizeRequest(d.request);
|
||||||
|
const key = `history:${h.id}`;
|
||||||
|
if (!ws.tabs.some((t) => t.key === key)) {
|
||||||
|
ws.tabs.push({
|
||||||
|
key,
|
||||||
|
kind: 'request',
|
||||||
|
col: h.collection || null,
|
||||||
|
id: null,
|
||||||
|
title: req.name || h.url,
|
||||||
|
preview: true,
|
||||||
|
draft: req,
|
||||||
|
saved: '',
|
||||||
|
result: d.response
|
||||||
|
? {
|
||||||
|
at: Date.now(),
|
||||||
|
result: {
|
||||||
|
output: {
|
||||||
|
request: null,
|
||||||
|
response: d.response,
|
||||||
|
auth: { kind: '', origin: null, source: null, steps: [], sent: [], warnings: [], flow_id: null },
|
||||||
|
asserts: [],
|
||||||
|
extracted: [],
|
||||||
|
error: null,
|
||||||
|
missing: [],
|
||||||
|
retried: false
|
||||||
|
},
|
||||||
|
body_id: d.body_id,
|
||||||
|
history_id: h.id,
|
||||||
|
body_file: null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
});
|
||||||
|
}
|
||||||
|
ws.activate(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function clearAll() {
|
||||||
|
if (await dialogs.confirm('Clear the whole history?', 'This cannot be undone.', 'Clear')) {
|
||||||
|
await api.historyDelete(null);
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="shrink-0 px-2 py-2">
|
||||||
|
<label class="flex h-7 items-center gap-2 rounded border border-line bg-panel px-2 focus-within:border-cyan-deep">
|
||||||
|
<Icon name="search" size={12} class="text-fg-subtle" />
|
||||||
|
<input bind:value={query} class="min-w-0 flex-1 bg-transparent outline-none placeholder:text-fg-subtle" placeholder="URL, name, method, status" spellcheck="false" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="k-scroll min-h-0 flex-1">
|
||||||
|
{#each entries as h (h.id)}
|
||||||
|
<button class="group flex w-full flex-col gap-0.5 border-b border-line/60 px-3 py-1.5 text-left hover:bg-hover/50" onclick={() => openEntry(h)}>
|
||||||
|
<div class="flex w-full items-center gap-2">
|
||||||
|
<span class="mono text-[10.5px] font-bold {methodColor(h.method)}">{h.method}</span>
|
||||||
|
<span class="mono text-[11px] {statusColor(h.status)}">{h.status ?? 'ERR'}</span>
|
||||||
|
<span class="text-[11px] text-fg-subtle">{formatMs(h.duration_ms)}</span>
|
||||||
|
<span class="flex-1"></span>
|
||||||
|
<span class="text-[11px] text-fg-subtle"><RelativeTime date={h.at} format="short" /></span>
|
||||||
|
</div>
|
||||||
|
<span class="mono w-full truncate text-[11.5px] text-soft" title={h.url}>{h.url}</span>
|
||||||
|
</button>
|
||||||
|
{:else}
|
||||||
|
<p class="px-4 py-6 text-fg-muted">{query ? 'Nothing matches.' : 'Requests you send show up here.'}</p>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{#if entries.length}
|
||||||
|
<div class="shrink-0 border-t border-line px-3 py-1.5">
|
||||||
|
<button class="text-[12px] text-fg-subtle hover:text-delete" onclick={clearAll}>Clear history</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,515 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { ContextMenu, DropdownMenu, MenuItem, MenuLabel, MenuSeparator, toast } from '@joshicodes/cock';
|
||||||
|
import { open as openDialog } from '@tauri-apps/plugin-dialog';
|
||||||
|
import { revealItemInDir } from '@tauri-apps/plugin-opener';
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import { api, errorText } from '$lib/api';
|
||||||
|
import { ws } from '$lib/state/workspace.svelte';
|
||||||
|
import { ui } from '$lib/state/ui.svelte';
|
||||||
|
import { fuzzy } from '$lib/fuzzy';
|
||||||
|
import { methodColor, newRequest } from '$lib/request';
|
||||||
|
import type { CollectionView, TreeNode } from '$lib/types';
|
||||||
|
import HistoryPanel from './HistoryPanel.svelte';
|
||||||
|
import { dialogs } from '$lib/state/dialogs.svelte';
|
||||||
|
|
||||||
|
const ROW = 26;
|
||||||
|
|
||||||
|
let panel = $state<'tree' | 'history'>('tree');
|
||||||
|
let filter = $state('');
|
||||||
|
let filterInput: HTMLInputElement | undefined = $state();
|
||||||
|
let expanded = $state<Set<string>>(new Set(JSON.parse(localStorage.getItem('knock.expanded') ?? '[]')));
|
||||||
|
let scrollTop = $state(0);
|
||||||
|
let viewportH = $state(600);
|
||||||
|
let selected = $state<string | null>(null);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (ui.sidebarFilterRequest > 0) {
|
||||||
|
panel = 'tree';
|
||||||
|
queueMicrotask(() => filterInput?.focus());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function persistExpanded() {
|
||||||
|
localStorage.setItem('knock.expanded', JSON.stringify([...expanded]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle(key: string, force?: boolean) {
|
||||||
|
const next = new Set(expanded);
|
||||||
|
const open = force ?? !next.has(key);
|
||||||
|
if (open) next.add(key);
|
||||||
|
else next.delete(key);
|
||||||
|
expanded = next;
|
||||||
|
persistExpanded();
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Row {
|
||||||
|
key: string;
|
||||||
|
col: CollectionView;
|
||||||
|
node: TreeNode | null; // null = collection root
|
||||||
|
depth: number;
|
||||||
|
hits?: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
let rows = $derived.by(() => {
|
||||||
|
const out: Row[] = [];
|
||||||
|
const q = filter.trim();
|
||||||
|
for (const col of ws.collections) {
|
||||||
|
const rootKey = `${col.id}:`;
|
||||||
|
if (q) {
|
||||||
|
const matches: { row: Row; score: number }[] = [];
|
||||||
|
const walk = (nodes: TreeNode[], depth: number, path: string) => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
if (n.node === 'folder') walk(n.children, depth + 1, `${path}${n.name}/`);
|
||||||
|
else {
|
||||||
|
const m = fuzzy(q, `${path}${n.name}`);
|
||||||
|
if (m) {
|
||||||
|
const offset = path.length;
|
||||||
|
matches.push({
|
||||||
|
row: { key: `${col.id}:${n.id}`, col, node: n, depth: 1, hits: m.hits.filter((h) => h >= offset).map((h) => h - offset) },
|
||||||
|
score: m.score
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(col.tree.children, 1, '');
|
||||||
|
if (matches.length) {
|
||||||
|
out.push({ key: rootKey, col, node: null, depth: 0 });
|
||||||
|
matches.sort((a, b) => b.score - a.score);
|
||||||
|
out.push(...matches.map((m) => m.row));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push({ key: rootKey, col, node: null, depth: 0 });
|
||||||
|
if (!expanded.has(rootKey) && expanded.has(`closed:${col.id}`)) continue;
|
||||||
|
const walk = (nodes: TreeNode[], depth: number) => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
const key = `${col.id}:${n.id}`;
|
||||||
|
out.push({ key, col, node: n, depth });
|
||||||
|
if (n.node === 'folder' && expanded.has(key)) walk(n.children, depth + 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(col.tree.children, 1);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
|
||||||
|
let first = $derived(Math.max(0, Math.floor(scrollTop / ROW) - 10));
|
||||||
|
let last = $derived(Math.min(rows.length, Math.ceil((scrollTop + viewportH) / ROW) + 10));
|
||||||
|
|
||||||
|
function collapsedRoot(col: CollectionView) {
|
||||||
|
return expanded.has(`closed:${col.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleRoot(col: CollectionView) {
|
||||||
|
toggle(`closed:${col.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function activeKeyFor(r: Row) {
|
||||||
|
const t = ws.active;
|
||||||
|
return t && t.col === r.col.id && t.id === r.node?.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function click(r: Row, e: MouseEvent) {
|
||||||
|
selected = r.key;
|
||||||
|
ws.focusCol = r.col.id;
|
||||||
|
if (!r.node) return toggleRoot(r.col);
|
||||||
|
if (r.node.node === 'folder') {
|
||||||
|
if (e.detail === 2) ws.openSpecial('folder', r.col.id, r.node.id, r.node.name);
|
||||||
|
else toggle(r.key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ws.openRequest(r.col.id, r.node.id, e.detail < 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function keydown(e: KeyboardEvent) {
|
||||||
|
const idx = rows.findIndex((r) => r.key === selected);
|
||||||
|
const r = rows[idx];
|
||||||
|
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||||
|
e.preventDefault();
|
||||||
|
const next = rows[Math.max(0, Math.min(rows.length - 1, idx + (e.key === 'ArrowDown' ? 1 : -1)))];
|
||||||
|
if (next) {
|
||||||
|
selected = next.key;
|
||||||
|
ensureVisible(rows.indexOf(next));
|
||||||
|
}
|
||||||
|
} else if (!r) {
|
||||||
|
return;
|
||||||
|
} else if (e.key === 'ArrowRight' && r.node?.node === 'folder') toggle(r.key, true);
|
||||||
|
else if (e.key === 'ArrowLeft' && r.node?.node === 'folder') toggle(r.key, false);
|
||||||
|
else if (e.key === 'Enter' && r.node) {
|
||||||
|
if (r.node.node === 'folder') toggle(r.key);
|
||||||
|
else ws.openRequest(r.col.id, r.node.id, false);
|
||||||
|
} else if (e.key === 'F2' && r.node) ui.renaming = r.key;
|
||||||
|
else if (e.key === 'Delete' && r.node) remove(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
let scroller: HTMLDivElement | undefined = $state();
|
||||||
|
function ensureVisible(i: number) {
|
||||||
|
if (!scroller) return;
|
||||||
|
const top = i * ROW;
|
||||||
|
if (top < scroller.scrollTop) scroller.scrollTop = top;
|
||||||
|
else if (top + ROW > scroller.scrollTop + viewportH) scroller.scrollTop = top + ROW - viewportH;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- actions
|
||||||
|
|
||||||
|
let menuRow = $state<Row | null>(null);
|
||||||
|
|
||||||
|
function folderOf(r: Row | null): string {
|
||||||
|
if (!r?.node) return '';
|
||||||
|
if (r.node.node === 'folder') return r.node.id;
|
||||||
|
const i = r.node.id.lastIndexOf('/');
|
||||||
|
return i < 0 ? '' : r.node.id.slice(0, i);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addRequest(r: Row | null, kind: 'http' | 'graphql' | 'ws' = 'http') {
|
||||||
|
const col = r?.col.id ?? ws.focusCol;
|
||||||
|
if (!col) return ws.newScratch(kind);
|
||||||
|
const folder = folderOf(r);
|
||||||
|
try {
|
||||||
|
const res = await api.requestCreate(col, folder, newRequest(kind));
|
||||||
|
ws.upsert(res.collection);
|
||||||
|
if (folder) toggle(`${col}:${folder}`, true);
|
||||||
|
await ws.openRequest(col, res.id, false);
|
||||||
|
ui.renaming = `${col}:${res.id}`;
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not create request', { description: errorText(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addFolder(r: Row | null) {
|
||||||
|
const col = r?.col.id ?? ws.focusCol;
|
||||||
|
if (!col) return;
|
||||||
|
const parent = folderOf(r);
|
||||||
|
try {
|
||||||
|
const res = await api.folderCreate(col, parent, 'New folder');
|
||||||
|
ws.upsert(res.collection);
|
||||||
|
if (parent) toggle(`${col}:${parent}`, true);
|
||||||
|
ui.renaming = `${col}:${res.id}`;
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not create folder', { description: errorText(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function duplicate(r: Row) {
|
||||||
|
if (!r.node) return;
|
||||||
|
try {
|
||||||
|
const res = await api.duplicate(r.col.id, r.node.id);
|
||||||
|
ws.upsert(res.collection);
|
||||||
|
await ws.openRequest(r.col.id, res.id, false);
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not duplicate', { description: errorText(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(r: Row) {
|
||||||
|
if (!r.node) return;
|
||||||
|
const what = r.node.node === 'folder' ? `folder "${r.node.name}" and everything in it` : `"${r.node.name}"`;
|
||||||
|
if (!(await dialogs.confirm(`Delete ${what}?`, 'The file is removed from disk. Use git to get it back.', 'Delete'))) return;
|
||||||
|
try {
|
||||||
|
ws.upsert(await api.remove(r.col.id, r.node.id));
|
||||||
|
for (const t of [...ws.tabs]) {
|
||||||
|
if (t.col === r.col.id && t.id && (t.id === r.node.id || t.id.startsWith(r.node.id + '/'))) ws.closeTab(t.key, true);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not delete', { description: errorText(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let renameValue = $state('');
|
||||||
|
$effect(() => {
|
||||||
|
const key = ui.renaming;
|
||||||
|
if (!key) return;
|
||||||
|
const r = rows.find((x) => x.key === key);
|
||||||
|
renameValue = r?.node?.name ?? '';
|
||||||
|
});
|
||||||
|
|
||||||
|
async function commitRename(r: Row) {
|
||||||
|
const name = renameValue.trim();
|
||||||
|
ui.renaming = null;
|
||||||
|
if (!r.node || !name || name === r.node.name) return;
|
||||||
|
try {
|
||||||
|
const res = await api.rename(r.col.id, r.node.id, name);
|
||||||
|
ws.upsert(res.collection);
|
||||||
|
ws.retarget(r.col.id, r.node.id, res.id);
|
||||||
|
for (const t of ws.tabs) if (t.col === r.col.id && t.id === res.id && t.draft) {
|
||||||
|
t.draft.name = name;
|
||||||
|
t.title = name;
|
||||||
|
if (t.saved) t.saved = JSON.stringify({ ...JSON.parse(t.saved), name });
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not rename', { description: errorText(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function focusInput(node: HTMLInputElement) {
|
||||||
|
node.focus();
|
||||||
|
node.select();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- drag and drop
|
||||||
|
|
||||||
|
let drag = $state<Row | null>(null);
|
||||||
|
let dropAt = $state<{ key: string; where: 'before' | 'after' | 'into' } | null>(null);
|
||||||
|
|
||||||
|
function dragOver(e: DragEvent, r: Row) {
|
||||||
|
if (!drag || !r.node || drag.col.id !== r.col.id || drag.key === r.key) return;
|
||||||
|
if (drag.node?.node === 'folder' && r.node.id.startsWith(drag.node.id + '/')) return;
|
||||||
|
e.preventDefault();
|
||||||
|
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
|
||||||
|
const y = (e.clientY - rect.top) / rect.height;
|
||||||
|
const where = r.node.node === 'folder' && y > 0.25 && y < 0.75 ? 'into' : y < 0.5 ? 'before' : 'after';
|
||||||
|
dropAt = { key: r.key, where };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function drop(r: Row) {
|
||||||
|
const d = drag;
|
||||||
|
const at = dropAt;
|
||||||
|
drag = null;
|
||||||
|
dropAt = null;
|
||||||
|
if (!d?.node || !r.node || !at) return;
|
||||||
|
let folder: string;
|
||||||
|
let index: number | null;
|
||||||
|
if (at.where === 'into') {
|
||||||
|
folder = r.node.id;
|
||||||
|
index = null;
|
||||||
|
toggle(r.key, true);
|
||||||
|
} else {
|
||||||
|
folder = folderOf({ ...r, node: { ...r.node, node: 'request' } as TreeNode });
|
||||||
|
const siblings = siblingsOf(r.col, folder);
|
||||||
|
let i = siblings.findIndex((s) => s.id === r.node!.id);
|
||||||
|
const from = siblings.findIndex((s) => s.id === d.node!.id);
|
||||||
|
if (from >= 0 && from < i) i -= 1;
|
||||||
|
index = at.where === 'before' ? i : i + 1;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await api.move(r.col.id, d.node.id, folder, index);
|
||||||
|
ws.upsert(res.collection);
|
||||||
|
ws.retarget(r.col.id, d.node.id, res.id);
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('Could not move', { description: errorText(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function siblingsOf(col: CollectionView, folder: string): TreeNode[] {
|
||||||
|
if (!folder) return col.tree.children;
|
||||||
|
const n = ws.findNode(col.id, folder);
|
||||||
|
return n?.node === 'folder' ? n.children : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openCollection() {
|
||||||
|
const dir = await openDialog({ directory: true, title: 'Open collection folder' });
|
||||||
|
if (typeof dir === 'string') await ws.open(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
function highlight(name: string, hits?: number[]) {
|
||||||
|
if (!hits?.length) return [{ t: name, h: false }];
|
||||||
|
const set = new Set(hits);
|
||||||
|
const parts: { t: string; h: boolean }[] = [];
|
||||||
|
for (let i = 0; i < name.length; i++) {
|
||||||
|
const h = set.has(i);
|
||||||
|
const lastPart = parts.at(-1);
|
||||||
|
if (lastPart && lastPart.h === h) lastPart.t += name[i];
|
||||||
|
else parts.push({ t: name[i], h });
|
||||||
|
}
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
const methodLabel = (n: TreeNode) =>
|
||||||
|
n.node === 'request' ? (n.type === 'ws' ? 'WS' : n.type === 'graphql' ? 'GQL' : (n.method ?? 'GET').slice(0, 6)) : '';
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<aside class="flex h-full flex-col bg-sidebar" style:width="{ws.sidebarWidth}px">
|
||||||
|
<div class="flex h-9 shrink-0 items-center gap-1 border-b border-line px-2">
|
||||||
|
<button class="px-1.5 py-1 k-label {panel === 'tree' ? '!text-fg' : 'hover:!text-fg-muted'}" onclick={() => (panel = 'tree')}>Collections</button>
|
||||||
|
<button class="px-1.5 py-1 k-label {panel === 'history' ? '!text-fg' : 'hover:!text-fg-muted'}" onclick={() => (panel = 'history')}>History</button>
|
||||||
|
<div class="flex-1"></div>
|
||||||
|
{#if panel === 'tree'}
|
||||||
|
<DropdownMenu label="New" placement="bottom-end">
|
||||||
|
{#snippet trigger(attrs)}
|
||||||
|
<button {...attrs} class="grid size-7 place-items-center rounded text-fg-muted hover:bg-hover hover:text-fg" title="New">
|
||||||
|
<Icon name="plus" />
|
||||||
|
</button>
|
||||||
|
{/snippet}
|
||||||
|
<MenuItem onselect={() => addRequest(null)} hint="Ctrl+N">HTTP request</MenuItem>
|
||||||
|
<MenuItem onselect={() => addRequest(null, 'graphql')}>GraphQL request</MenuItem>
|
||||||
|
<MenuItem onselect={() => addRequest(null, 'ws')}>WebSocket</MenuItem>
|
||||||
|
<MenuItem onselect={() => addFolder(null)} disabled={!ws.focusCol}>Folder</MenuItem>
|
||||||
|
<MenuSeparator />
|
||||||
|
<MenuItem onselect={openCollection} hint="Ctrl+O">Open collection…</MenuItem>
|
||||||
|
<MenuItem onselect={() => dialogs.newCollection()}>New collection…</MenuItem>
|
||||||
|
<MenuItem onselect={() => dialogs.importer()}>Import…</MenuItem>
|
||||||
|
</DropdownMenu>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if panel === 'history'}
|
||||||
|
<HistoryPanel />
|
||||||
|
{:else}
|
||||||
|
<div class="shrink-0 px-2 py-2">
|
||||||
|
<label class="flex h-7 items-center gap-2 rounded border border-line bg-panel px-2 focus-within:border-cyan-deep">
|
||||||
|
<Icon name="filter" size={12} class="text-fg-subtle" />
|
||||||
|
<input
|
||||||
|
bind:this={filterInput}
|
||||||
|
bind:value={filter}
|
||||||
|
class="min-w-0 flex-1 bg-transparent outline-none placeholder:text-fg-subtle"
|
||||||
|
placeholder="Filter requests"
|
||||||
|
spellcheck="false"
|
||||||
|
onkeydown={(e) => {
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
filter = '';
|
||||||
|
filterInput?.blur();
|
||||||
|
} else if (e.key === 'ArrowDown') {
|
||||||
|
selected = rows.find((r) => r.node?.node === 'request')?.key ?? null;
|
||||||
|
scroller?.focus();
|
||||||
|
} else if (e.key === 'Enter') {
|
||||||
|
const r = rows.find((x) => x.node?.node === 'request');
|
||||||
|
if (r?.node) ws.openRequest(r.col.id, r.node.id, false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if ws.collections.length === 0}
|
||||||
|
<div class="px-4 py-6 text-fg-muted">
|
||||||
|
<p class="mb-3">No collection open.</p>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<button class="text-left text-accent hover:underline" onclick={openCollection}>Open a folder</button>
|
||||||
|
<button class="text-left text-accent hover:underline" onclick={() => dialogs.newCollection()}>Create a collection</button>
|
||||||
|
<button class="text-left text-accent hover:underline" onclick={() => dialogs.importer()}>Import from Postman, Bruno or cURL</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<ContextMenu label="Collection actions" class="min-h-0 flex-1">
|
||||||
|
{#snippet children()}
|
||||||
|
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
||||||
|
<div
|
||||||
|
bind:this={scroller}
|
||||||
|
bind:clientHeight={viewportH}
|
||||||
|
class="k-scroll h-full outline-none"
|
||||||
|
tabindex="0"
|
||||||
|
role="tree"
|
||||||
|
aria-label="Collections"
|
||||||
|
onscroll={(e) => (scrollTop = (e.currentTarget as HTMLElement).scrollTop)}
|
||||||
|
onkeydown={keydown}
|
||||||
|
>
|
||||||
|
<div style:height="{rows.length * ROW}px" class="relative">
|
||||||
|
{#each rows.slice(first, last) as r, i (r.key)}
|
||||||
|
{@const top = (first + i) * ROW}
|
||||||
|
{@const isActive = activeKeyFor(r)}
|
||||||
|
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||||
|
<div
|
||||||
|
role="treeitem"
|
||||||
|
aria-selected={selected === r.key}
|
||||||
|
tabindex="-1"
|
||||||
|
class="group absolute inset-x-0 flex items-center gap-1.5 pr-2 {isActive ? 'bg-hover text-strong' : selected === r.key ? 'bg-hover/60' : 'hover:bg-hover/50'} {dropAt?.key === r.key && dropAt.where === 'into' ? 'outline outline-1 -outline-offset-1 outline-cyan' : ''}"
|
||||||
|
style:top="{top}px"
|
||||||
|
style:height="{ROW}px"
|
||||||
|
style:padding-left="{8 + r.depth * 14}px"
|
||||||
|
draggable={!!r.node && ui.renaming !== r.key}
|
||||||
|
ondragstart={(e) => {
|
||||||
|
drag = r;
|
||||||
|
e.dataTransfer?.setData('text/plain', r.key);
|
||||||
|
}}
|
||||||
|
ondragend={() => {
|
||||||
|
drag = null;
|
||||||
|
dropAt = null;
|
||||||
|
}}
|
||||||
|
ondragover={(e) => dragOver(e, r)}
|
||||||
|
ondragleave={() => {
|
||||||
|
if (dropAt?.key === r.key) dropAt = null;
|
||||||
|
}}
|
||||||
|
ondrop={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
drop(r);
|
||||||
|
}}
|
||||||
|
onclick={(e) => click(r, e)}
|
||||||
|
oncontextmenu={() => {
|
||||||
|
menuRow = r;
|
||||||
|
selected = r.key;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#if dropAt?.key === r.key && dropAt.where !== 'into'}
|
||||||
|
<span class="pointer-events-none absolute inset-x-2 h-0.5 bg-cyan {dropAt.where === 'before' ? 'top-0' : 'bottom-0'}"></span>
|
||||||
|
{/if}
|
||||||
|
{#if !r.node}
|
||||||
|
<Icon name={collapsedRoot(r.col) ? 'chevron-right' : 'chevron-down'} size={12} class="text-fg-subtle" />
|
||||||
|
<span class="truncate font-bold text-strong">{r.col.name}</span>
|
||||||
|
{#if r.col.problems.length}
|
||||||
|
<span title="{r.col.problems.length} file(s) could not be read"><Icon name="alert" size={12} class="text-post" /></span>
|
||||||
|
{/if}
|
||||||
|
{:else if r.node.node === 'folder'}
|
||||||
|
<Icon name={expanded.has(r.key) ? 'chevron-down' : 'chevron-right'} size={12} class="text-fg-subtle" />
|
||||||
|
<Icon name="folder" size={13} class="text-fg-subtle" />
|
||||||
|
{:else}
|
||||||
|
<span class="mono w-9 shrink-0 text-right text-[10.5px] font-bold {r.node.type === 'http' ? methodColor(r.node.method) : 'text-soft'}">{methodLabel(r.node)}</span>
|
||||||
|
{/if}
|
||||||
|
{#if r.node}
|
||||||
|
{#if ui.renaming === r.key}
|
||||||
|
<input
|
||||||
|
use:focusInput
|
||||||
|
bind:value={renameValue}
|
||||||
|
class="k-field !py-0.5 !font-sans"
|
||||||
|
onclick={(e) => e.stopPropagation()}
|
||||||
|
onkeydown={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (e.key === 'Enter') commitRename(r);
|
||||||
|
if (e.key === 'Escape') ui.renaming = null;
|
||||||
|
}}
|
||||||
|
onblur={() => commitRename(r)}
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<span class="min-w-0 flex-1 truncate {r.node.node === 'folder' ? 'text-soft' : ''}">
|
||||||
|
{#each highlight(r.node.name, r.hits) as p}<span class={p.h ? 'text-accent' : ''}>{p.t}</span>{/each}
|
||||||
|
</span>
|
||||||
|
{#if filter && r.node.id.includes('/')}
|
||||||
|
<span class="truncate text-[11px] text-fg-subtle">{r.node.id.slice(0, r.node.id.lastIndexOf('/'))}</span>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<span class="flex-1"></span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
{#snippet menu()}
|
||||||
|
{#if menuRow}
|
||||||
|
{@const r = menuRow}
|
||||||
|
{#if !r.node || r.node.node === 'folder'}
|
||||||
|
<MenuItem onselect={() => addRequest(r)}>New request</MenuItem>
|
||||||
|
<MenuItem onselect={() => addRequest(r, 'graphql')}>New GraphQL request</MenuItem>
|
||||||
|
<MenuItem onselect={() => addRequest(r, 'ws')}>New WebSocket</MenuItem>
|
||||||
|
<MenuItem onselect={() => addFolder(r)}>New folder</MenuItem>
|
||||||
|
<MenuSeparator />
|
||||||
|
{/if}
|
||||||
|
{#if r.node}
|
||||||
|
{#if r.node.node === 'request'}
|
||||||
|
<MenuItem onselect={() => ws.openRequest(r.col.id, r.node!.id, false)}>Open in new tab</MenuItem>
|
||||||
|
<MenuItem onselect={() => duplicate(r)}>Duplicate</MenuItem>
|
||||||
|
{:else}
|
||||||
|
<MenuItem onselect={() => ws.openSpecial('folder', r.col.id, r.node!.id, r.node!.name)}>Folder settings</MenuItem>
|
||||||
|
<MenuItem onselect={() => dialogs.runner(r.col.id, r.node!.id)}>Run folder</MenuItem>
|
||||||
|
{/if}
|
||||||
|
<MenuItem onselect={() => (ui.renaming = r.key)} hint="F2">Rename</MenuItem>
|
||||||
|
<MenuItem onselect={() => revealItemInDir(`${r.col.root}/${r.node!.id}`)}>Show in file manager</MenuItem>
|
||||||
|
<MenuSeparator />
|
||||||
|
<MenuItem variant="danger" onselect={() => remove(r)} hint="Del">Delete</MenuItem>
|
||||||
|
{:else}
|
||||||
|
<MenuItem onselect={() => ws.openSpecial('collection', r.col.id, null, r.col.name)}>Collection settings</MenuItem>
|
||||||
|
<MenuItem onselect={() => ws.openSpecial('environment', r.col.id, ws.env(r.col.id) ?? r.col.environments[0]?.id ?? null, 'Environments')}>Environments</MenuItem>
|
||||||
|
<MenuItem onselect={() => dialogs.runner(r.col.id, '')}>Run collection</MenuItem>
|
||||||
|
<MenuItem onselect={() => revealItemInDir(`${r.col.root}/knock.yaml`)}>Show in file manager</MenuItem>
|
||||||
|
<MenuSeparator />
|
||||||
|
<MenuItem onselect={() => ws.close(r.col.id)}>Close collection</MenuItem>
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<MenuLabel>Nothing selected</MenuLabel>
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
</ContextMenu>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</aside>
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import { ws, type Tab } from '$lib/state/workspace.svelte';
|
||||||
|
import { methodColor } from '$lib/request';
|
||||||
|
|
||||||
|
let dragFrom = $state<number | null>(null);
|
||||||
|
let dragOver = $state<number | null>(null);
|
||||||
|
|
||||||
|
function label(t: Tab) {
|
||||||
|
if (t.kind !== 'request' || !t.draft) return '';
|
||||||
|
if (t.draft.type === 'ws') return 'WS';
|
||||||
|
if (t.draft.type === 'graphql') return 'GQL';
|
||||||
|
return (t.draft.method ?? 'GET').slice(0, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
const specialIcon: Record<string, string> = {
|
||||||
|
folder: 'folder',
|
||||||
|
collection: 'layers',
|
||||||
|
environment: 'globe',
|
||||||
|
settings: 'settings',
|
||||||
|
history: 'history'
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="flex h-9 shrink-0 items-stretch border-b border-line bg-sidebar">
|
||||||
|
<div class="k-scroll flex min-w-0 flex-1 items-stretch overflow-y-hidden [scrollbar-width:none]" role="tablist">
|
||||||
|
{#each ws.tabs as t, i (t.key)}
|
||||||
|
{@const active = t.key === ws.activeKey}
|
||||||
|
{@const dirty = ws.isDirty(t)}
|
||||||
|
<div
|
||||||
|
role="tab"
|
||||||
|
tabindex="0"
|
||||||
|
aria-selected={active}
|
||||||
|
draggable="true"
|
||||||
|
class="group relative flex max-w-[220px] shrink-0 items-center gap-1.5 border-r border-line pl-3 pr-1.5 {active ? 'bg-panel text-strong' : 'text-fg-muted hover:bg-hover/40'} {dragOver === i ? 'shadow-[inset_2px_0_0_var(--knock-cyan)]' : ''}"
|
||||||
|
onclick={() => ws.activate(t.key)}
|
||||||
|
ondblclick={() => ws.pin(t.key)}
|
||||||
|
onauxclick={(e) => {
|
||||||
|
if (e.button === 1) ws.closeTab(t.key);
|
||||||
|
}}
|
||||||
|
onkeydown={(e) => {
|
||||||
|
if (e.key === 'Enter') ws.activate(t.key);
|
||||||
|
}}
|
||||||
|
ondragstart={() => (dragFrom = i)}
|
||||||
|
ondragover={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
dragOver = i;
|
||||||
|
}}
|
||||||
|
ondragleave={() => (dragOver = null)}
|
||||||
|
ondrop={() => {
|
||||||
|
if (dragFrom !== null && dragFrom !== i) ws.moveTab(dragFrom, i);
|
||||||
|
dragFrom = null;
|
||||||
|
dragOver = null;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#if active}<span class="absolute inset-x-0 top-0 h-0.5 bg-cyan"></span>{/if}
|
||||||
|
{#if t.kind === 'request'}
|
||||||
|
<span class="mono text-[10px] font-bold {t.draft?.type === 'http' ? methodColor(t.draft?.method) : 'text-soft'}">{label(t)}</span>
|
||||||
|
{:else}
|
||||||
|
<Icon name={specialIcon[t.kind] ?? 'file'} size={12} class="text-fg-subtle" />
|
||||||
|
{/if}
|
||||||
|
<span class="truncate {t.preview ? 'italic' : ''}">{t.draft?.name ?? t.title}</span>
|
||||||
|
{#if t.sending}
|
||||||
|
<span class="mono text-[10px] text-fg-subtle">…</span>
|
||||||
|
{/if}
|
||||||
|
<button
|
||||||
|
class="grid size-5 shrink-0 place-items-center rounded hover:bg-hover"
|
||||||
|
title="Close (Ctrl+W)"
|
||||||
|
onclick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
ws.closeTab(t.key);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#if dirty}
|
||||||
|
<span class="size-2 rounded-full bg-fg-muted group-hover:hidden"></span>
|
||||||
|
<Icon name="x" size={11} class="hidden group-hover:block" />
|
||||||
|
{:else}
|
||||||
|
<Icon name="x" size={11} class="{active ? '' : 'opacity-0'} group-hover:opacity-100" />
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<button class="grid w-9 shrink-0 place-items-center text-fg-muted hover:bg-hover/40 hover:text-fg" title="New request (Ctrl+T)" onclick={() => ws.newScratch()}>
|
||||||
|
<Icon name="plus" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import Mark from '$lib/ui/Mark.svelte';
|
||||||
|
import EnvSwitcher from './EnvSwitcher.svelte';
|
||||||
|
import { ws } from '$lib/state/workspace.svelte';
|
||||||
|
import { Kbd } from '@joshicodes/cock';
|
||||||
|
|
||||||
|
const win = getCurrentWindow();
|
||||||
|
let maximized = $state(false);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
win.isMaximized().then((m) => (maximized = m));
|
||||||
|
const un = win.onResized(async () => (maximized = await win.isMaximized()));
|
||||||
|
return () => {
|
||||||
|
un.then((f) => f());
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
function onDown(e: MouseEvent) {
|
||||||
|
if (e.button !== 0) return;
|
||||||
|
if ((e.target as HTMLElement).closest('button, input, select, a, [data-no-drag]')) return;
|
||||||
|
if (e.detail === 2) win.toggleMaximize();
|
||||||
|
else win.startDragging();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
|
<header class="flex h-10 shrink-0 items-center gap-3 border-b border-line bg-titlebar pl-3" onmousedown={onDown}>
|
||||||
|
<div class="flex items-center gap-2 text-cyan [:root:not(.dark)_&]:text-cyan-deep">
|
||||||
|
<Mark size={18} />
|
||||||
|
<span class="text-[15px] font-bold tracking-tight text-strong">knock</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="ml-3 flex items-center gap-1">
|
||||||
|
{#if ws.focusCol}
|
||||||
|
<EnvSwitcher col={ws.focusCol} />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-1 justify-center">
|
||||||
|
<button
|
||||||
|
class="flex h-7 w-full max-w-[420px] items-center gap-2 rounded border border-line bg-panel px-2.5 text-left text-fg-subtle hover:border-border-strong"
|
||||||
|
onclick={() => (ws.paletteOpen = true)}
|
||||||
|
>
|
||||||
|
<Icon name="search" size={13} />
|
||||||
|
<span class="flex-1 truncate">Find requests, environments, actions</span>
|
||||||
|
<Kbd>Ctrl K</Kbd>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center">
|
||||||
|
<button
|
||||||
|
class="grid size-8 place-items-center text-fg-muted hover:text-fg"
|
||||||
|
title={ws.layout === 'columns' ? 'Response below request' : 'Response beside request'}
|
||||||
|
onclick={() => ws.setLayout(ws.layout === 'columns' ? 'rows' : 'columns')}
|
||||||
|
>
|
||||||
|
<Icon name={ws.layout === 'columns' ? 'columns' : 'rows'} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="grid size-8 place-items-center text-fg-muted hover:text-fg"
|
||||||
|
title={ws.maskSecrets ? 'Secrets are masked. Click to show them' : 'Secrets are shown. Click to mask them'}
|
||||||
|
onclick={() => ws.setMask(!ws.maskSecrets)}
|
||||||
|
>
|
||||||
|
<Icon name={ws.maskSecrets ? 'eye-off' : 'eye'} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="grid size-8 place-items-center text-fg-muted hover:text-fg"
|
||||||
|
title="Settings"
|
||||||
|
onclick={() => ws.openSpecial('settings', null, null, 'Settings')}
|
||||||
|
>
|
||||||
|
<Icon name="settings" />
|
||||||
|
</button>
|
||||||
|
<div class="ml-2 flex h-10">
|
||||||
|
<button class="grid w-11 place-items-center text-fg-muted hover:bg-hover hover:text-fg" title="Minimize" onclick={() => win.minimize()}>
|
||||||
|
<Icon name="minus" size={13} />
|
||||||
|
</button>
|
||||||
|
<button class="grid w-11 place-items-center text-fg-muted hover:bg-hover hover:text-fg" title={maximized ? 'Restore' : 'Maximize'} onclick={() => win.toggleMaximize()}>
|
||||||
|
<Icon name={maximized ? 'restore' : 'window'} size={12} />
|
||||||
|
</button>
|
||||||
|
<button class="grid w-11 place-items-center text-fg-muted hover:bg-delete hover:text-white" title="Close" onclick={() => win.close()}>
|
||||||
|
<Icon name="x" size={13} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { open as openDialog } from '@tauri-apps/plugin-dialog';
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import { api } from '$lib/api';
|
||||||
|
import { ws } from '$lib/state/workspace.svelte';
|
||||||
|
import { dialogs } from '$lib/state/dialogs.svelte';
|
||||||
|
import { Kbd } from '@joshicodes/cock';
|
||||||
|
|
||||||
|
let recent = $state<string[]>([]);
|
||||||
|
onMount(async () => {
|
||||||
|
recent = (await api.recent()).filter((r) => !ws.collections.some((c) => c.root === r));
|
||||||
|
});
|
||||||
|
|
||||||
|
async function openCollection() {
|
||||||
|
const dir = await openDialog({ directory: true, title: 'Open collection folder' });
|
||||||
|
if (typeof dir === 'string') await ws.open(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
const home = (p: string) => p.replace(/^\/home\/[^/]+/, '~');
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="k-scroll h-full">
|
||||||
|
<div class="mx-auto flex max-w-[620px] flex-col gap-10 px-8 py-16">
|
||||||
|
<div>
|
||||||
|
<img src="/wordmark.svg" alt="knock" class="h-9 [:root:not(.dark)_&]:hidden" />
|
||||||
|
<img src="/wordmark-light.svg" alt="knock" class="hidden h-9 [:root:not(.dark)_&]:block" />
|
||||||
|
<p class="mt-4 text-fg-muted">Knock on an API and see what comes back. Collections are folders of YAML files you keep in git.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-2 gap-px overflow-hidden rounded border border-line bg-line">
|
||||||
|
{#each [
|
||||||
|
{ label: 'New request', hint: 'Ctrl T', icon: 'plus', run: () => ws.newScratch() },
|
||||||
|
{ label: 'Open collection', hint: 'Ctrl O', icon: 'folder', run: openCollection },
|
||||||
|
{ label: 'New collection', hint: '', icon: 'layers', run: () => dialogs.newCollection() },
|
||||||
|
{ label: 'Import', hint: 'Postman, Bruno, cURL', icon: 'download', run: () => dialogs.importer() }
|
||||||
|
] as a}
|
||||||
|
<button class="flex items-center gap-3 bg-panel px-4 py-4 text-left hover:bg-hover/50" onclick={a.run}>
|
||||||
|
<Icon name={a.icon} class="text-accent" />
|
||||||
|
<span class="flex-1 text-strong">{a.label}</span>
|
||||||
|
{#if a.hint.startsWith('Ctrl')}<Kbd>{a.hint}</Kbd>{:else}<span class="text-[12px] text-fg-subtle">{a.hint}</span>{/if}
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if recent.length}
|
||||||
|
<div>
|
||||||
|
<div class="k-label mb-2">Recent</div>
|
||||||
|
{#each recent as r}
|
||||||
|
<div class="group flex items-center">
|
||||||
|
<button class="mono min-w-0 flex-1 truncate py-1.5 text-left text-[12.5px] text-soft hover:text-accent" onclick={() => ws.open(r)}>{home(r)}</button>
|
||||||
|
<button
|
||||||
|
class="px-2 text-fg-subtle opacity-0 hover:text-fg group-hover:opacity-100"
|
||||||
|
title="Remove from list"
|
||||||
|
onclick={async () => {
|
||||||
|
await api.recentForget(r);
|
||||||
|
recent = recent.filter((x) => x !== r);
|
||||||
|
}}><Icon name="x" size={12} /></button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="grid grid-cols-[auto_1fr] gap-x-6 gap-y-1.5 text-[12.5px]">
|
||||||
|
{#each [['Ctrl Enter', 'Send'], ['Ctrl S', 'Save'], ['Ctrl K', 'Find anything'], ['Ctrl P', 'Filter requests'], ['Ctrl E', 'Switch environment'], ['Ctrl L', 'Focus URL'], ['Ctrl Shift J', 'JSON form / code']] as [k, v]}
|
||||||
|
<Kbd class="justify-self-start">{k}</Kbd><span class="text-fg-muted">{v}</span>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { toast } from '@joshicodes/cock';
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import { ws, type Tab } from '$lib/state/workspace.svelte';
|
||||||
|
import type { AuthDebug, Exchange, Json } from '$lib/types';
|
||||||
|
import TokenInspector from './TokenInspector.svelte';
|
||||||
|
import { formatMs } from '$lib/request';
|
||||||
|
|
||||||
|
let { debug, tab }: { debug: AuthDebug; tab?: Tab } = $props();
|
||||||
|
|
||||||
|
let open = $state<Record<string, boolean>>({});
|
||||||
|
let firstError = $derived(debug.steps.findIndex((s) => s.status === 'error'));
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (firstError >= 0) open[`${firstError}`] = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const mark: Record<string, { icon: string; cls: string; label: string }> = {
|
||||||
|
ok: { icon: 'check', cls: 'text-ok', label: 'ok' },
|
||||||
|
error: { icon: 'x', cls: 'text-delete', label: 'failed' },
|
||||||
|
skipped: { icon: 'minus', cls: 'text-fg-subtle', label: 'skipped' },
|
||||||
|
pending: { icon: 'more', cls: 'text-fg-muted', label: 'waiting' },
|
||||||
|
warning: { icon: 'alert', cls: 'text-post', label: 'warning' }
|
||||||
|
};
|
||||||
|
|
||||||
|
function m(s: string) {
|
||||||
|
return ws.maskSecrets ? maskText(s) : s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Masks token-looking values and known secret parameters. */
|
||||||
|
function maskText(s: string): string {
|
||||||
|
return s
|
||||||
|
.replace(/\b(eyJ[\w-]+\.[\w-]+\.[\w-]*)/g, '••••••')
|
||||||
|
.replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|code_verifier)["']?\s*[:=]\s*["']?)([^"'&\s,}]+)/gi, '$1••••••')
|
||||||
|
.replace(/(Authorization:\s*\w+\s+)\S+/gi, '$1••••••');
|
||||||
|
}
|
||||||
|
|
||||||
|
function copy(text: string, what = 'Copied') {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
toast.success(what);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTokenData(d: Json): d is { tokens: Record<string, string> } {
|
||||||
|
return !!d && typeof d === 'object' && !Array.isArray(d) && 'tokens' in d;
|
||||||
|
}
|
||||||
|
function isParams(d: Json): d is { params: [string, string][]; url?: string } {
|
||||||
|
return !!d && typeof d === 'object' && !Array.isArray(d) && 'params' in d && Array.isArray((d as { params: unknown }).params);
|
||||||
|
}
|
||||||
|
|
||||||
|
function exchangeText(x: Exchange, side: 'req' | 'res'): string {
|
||||||
|
if (side === 'req') {
|
||||||
|
return `${x.method} ${x.url}\n${x.request_headers.map(([k, v]) => `${k}: ${v}`).join('\n')}${x.request_body ? `\n\n${x.request_body}` : ''}`;
|
||||||
|
}
|
||||||
|
return `${x.status ?? '(no response)'}\n${x.response_headers.map(([k, v]) => `${k}: ${v}`).join('\n')}${x.response_body ? `\n\n${prettyJson(x.response_body)}` : ''}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function prettyJson(s: string): string {
|
||||||
|
try {
|
||||||
|
return JSON.stringify(JSON.parse(s), null, 2);
|
||||||
|
} catch {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function exportFlow(format: 'json' | 'md') {
|
||||||
|
const steps = debug.steps.map((s) => ({ ...s, summary: maskText(s.summary), exchange: s.exchange ? JSON.parse(maskText(JSON.stringify(s.exchange))) : null, data: JSON.parse(maskText(JSON.stringify(s.data ?? null))) }));
|
||||||
|
const text =
|
||||||
|
format === 'json'
|
||||||
|
? JSON.stringify({ kind: debug.kind, origin: debug.origin, steps, warnings: debug.warnings }, null, 2)
|
||||||
|
: [`# ${debug.kind} auth flow`, '', ...steps.map((s, i) => `${i + 1}. **${s.title}**: ${s.status} (${Math.round(s.duration_ms)} ms) ${s.summary}${s.hint ? `\n > ${s.hint}` : ''}${s.exchange ? `\n\n \`\`\`\n ${s.exchange.curl.replace(/\n/g, '\n ')}\n \`\`\`` : ''}`)].join('\n');
|
||||||
|
copy(text, `Flow copied as ${format === 'json' ? 'JSON' : 'Markdown'} (secrets masked)`);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="k-scroll selectable h-full p-3 text-[12.5px]">
|
||||||
|
{#if !debug.kind || debug.kind === 'none'}
|
||||||
|
<p class="text-fg-subtle">No auth was used for this request.</p>
|
||||||
|
{:else}
|
||||||
|
<div class="mb-3 flex items-center gap-3">
|
||||||
|
<span class="text-fg"><span class="font-bold">{debug.kind}</span> <span class="text-fg-muted">from the {debug.origin}{debug.origin !== 'request' ? ` (${debug.source})` : ''}</span></span>
|
||||||
|
<span class="flex-1"></span>
|
||||||
|
{#if debug.steps.length > 1}
|
||||||
|
<button class="text-[12px] text-fg-muted hover:text-fg" onclick={() => exportFlow('md')}>Copy as Markdown</button>
|
||||||
|
<button class="text-[12px] text-fg-muted hover:text-fg" onclick={() => exportFlow('json')}>Copy as JSON</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#each debug.warnings as w}
|
||||||
|
<p class="mb-1 flex items-center gap-1.5 text-post"><Icon name="alert" size={12} />{w}</p>
|
||||||
|
{/each}
|
||||||
|
|
||||||
|
<ol class="relative mt-2">
|
||||||
|
{#each debug.steps as s, i (i)}
|
||||||
|
{@const mk = mark[s.status] ?? mark.ok}
|
||||||
|
{@const isFirstError = i === firstError}
|
||||||
|
<li class="relative pb-1 pl-7">
|
||||||
|
{#if i < debug.steps.length - 1}<span class="absolute bottom-0 left-[9px] top-6 w-px bg-line"></span>{/if}
|
||||||
|
<span class="absolute left-0 top-1 grid size-[19px] place-items-center rounded-full border {isFirstError ? 'border-delete bg-delete/15' : 'border-line bg-panel'}">
|
||||||
|
<Icon name={mk.icon} size={11} class={mk.cls} stroke={2} />
|
||||||
|
</span>
|
||||||
|
<button class="flex w-full items-baseline gap-2 py-1 text-left" onclick={() => (open[`${i}`] = !open[`${i}`])}>
|
||||||
|
<span class="{s.status === 'error' ? 'font-bold text-delete' : s.status === 'skipped' ? 'text-fg-muted' : 'text-fg'}">{s.title}</span>
|
||||||
|
<span class="min-w-0 flex-1 truncate text-fg-muted">{m(s.summary)}</span>
|
||||||
|
<span class="mono shrink-0 text-[11px] text-fg-subtle">{s.duration_ms ? formatMs(s.duration_ms) : ''}</span>
|
||||||
|
{#if s.exchange || (s.data !== null && s.data !== undefined)}
|
||||||
|
<Icon name={open[`${i}`] ? 'chevron-down' : 'chevron-right'} size={11} class="shrink-0 text-fg-subtle" />
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
{#if isFirstError}
|
||||||
|
<div class="mb-2 rounded border border-delete/40 bg-delete/8 px-3 py-2">
|
||||||
|
<div class="font-bold text-delete">This is where it failed</div>
|
||||||
|
<div class="mt-0.5 text-fg">{m(s.summary)}</div>
|
||||||
|
{#if s.hint}<div class="mt-1.5 whitespace-pre-wrap text-fg-muted">{s.hint}</div>{/if}
|
||||||
|
</div>
|
||||||
|
{:else if s.hint}
|
||||||
|
<div class="mb-1 whitespace-pre-wrap text-[12px] text-fg-muted">{s.hint}</div>
|
||||||
|
{/if}
|
||||||
|
{#if open[`${i}`]}
|
||||||
|
<div class="mb-3 flex flex-col gap-2">
|
||||||
|
{#if isParams(s.data)}
|
||||||
|
<div class="rounded border border-line">
|
||||||
|
{#if s.data.url}
|
||||||
|
<div class="flex items-start gap-2 border-b border-line px-2 py-1.5">
|
||||||
|
<span class="mono min-w-0 flex-1 break-all text-[12px]">{m(s.data.url)}</span>
|
||||||
|
<button class="shrink-0 text-[11px] text-accent" onclick={() => copy(String((s.data as { url: string }).url))}>copy</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#each s.data.params as [k, v]}
|
||||||
|
<div class="group mono flex items-start gap-3 border-b border-line/50 px-2 py-1 text-[12px] last:border-0">
|
||||||
|
<span class="w-40 shrink-0 text-get">{k}</span>
|
||||||
|
<span class="min-w-0 flex-1 break-all">{m(v)}</span>
|
||||||
|
<button class="shrink-0 font-sans text-[11px] text-accent opacity-0 group-hover:opacity-100" onclick={() => copy(v)}>copy</button>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if isTokenData(s.data)}
|
||||||
|
{#each Object.entries(s.data.tokens) as [name, token]}
|
||||||
|
<TokenInspector {name} {token} />
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
{#if s.exchange}
|
||||||
|
{@const x = s.exchange}
|
||||||
|
<div class="grid grid-cols-1 gap-2 xl:grid-cols-2">
|
||||||
|
<div class="rounded border border-line">
|
||||||
|
<div class="flex items-center border-b border-line px-2 py-1"><span class="k-label flex-1">Request</span><button class="text-[11px] text-accent" onclick={() => copy(x.curl, 'cURL copied')}>Copy as cURL</button></div>
|
||||||
|
<pre class="mono max-h-72 overflow-auto whitespace-pre-wrap break-all p-2 text-[11.5px]">{m(exchangeText(x, 'req'))}</pre>
|
||||||
|
</div>
|
||||||
|
<div class="rounded border border-line">
|
||||||
|
<div class="flex items-center border-b border-line px-2 py-1"><span class="k-label flex-1">Response</span><button class="text-[11px] text-accent" onclick={() => copy(exchangeText(x, 'res'))}>copy</button></div>
|
||||||
|
<pre class="mono max-h-72 overflow-auto whitespace-pre-wrap break-all p-2 text-[11.5px]">{m(exchangeText(x, 'res'))}</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if s.data !== null && s.data !== undefined && !isParams(s.data) && !isTokenData(s.data)}
|
||||||
|
<pre class="mono max-h-72 overflow-auto whitespace-pre-wrap break-all rounded border border-line p-2 text-[11.5px]">{m(JSON.stringify(s.data, null, 2))}</pre>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
{#if debug.sent.length}
|
||||||
|
<div class="k-label mb-1.5 mt-4">Attached to the request</div>
|
||||||
|
{#each debug.sent as x}
|
||||||
|
<div class="mono flex gap-3 border-b border-line/50 py-1">
|
||||||
|
<span class="w-16 shrink-0 text-fg-subtle">{x.location}</span>
|
||||||
|
<span class="w-40 shrink-0 text-get">{x.name}</span>
|
||||||
|
<span class="min-w-0 break-all">{ws.maskSecrets ? '••••••' : x.value}</span>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import VarInput from '$lib/ui/VarInput.svelte';
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import { api } from '$lib/api';
|
||||||
|
import { ws, type Tab } from '$lib/state/workspace.svelte';
|
||||||
|
import type { Auth, AuthConfig, Json, Preview, Request } from '$lib/types';
|
||||||
|
import OAuthConfig from './OAuthConfig.svelte';
|
||||||
|
import { AUTH_TYPES, authFields, type Field } from './types';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
auth: Auth;
|
||||||
|
tab?: Tab;
|
||||||
|
level: 'request' | 'folder' | 'collection';
|
||||||
|
}
|
||||||
|
let { auth = $bindable(), tab, level }: Props = $props();
|
||||||
|
|
||||||
|
let kind = $derived(typeof auth === 'string' ? auth : auth.type);
|
||||||
|
let cfg = $derived(typeof auth === 'object' ? auth : null);
|
||||||
|
let fields = $derived(cfg ? authFields(cfg.type) : []);
|
||||||
|
|
||||||
|
function setKind(k: string) {
|
||||||
|
if (k === 'inherit' || k === 'none') {
|
||||||
|
auth = k;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const prev = typeof auth === 'object' ? auth : null;
|
||||||
|
const next: AuthConfig = { type: k };
|
||||||
|
// Keep values of fields that exist in both types (username, token, …).
|
||||||
|
for (const f of authFields(k)) {
|
||||||
|
if (prev && prev[f.key] !== undefined) next[f.key] = prev[f.key];
|
||||||
|
else if (f.default !== undefined) next[f.key] = f.default;
|
||||||
|
}
|
||||||
|
auth = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function str(key: string): string {
|
||||||
|
const v = cfg?.[key];
|
||||||
|
return v === undefined || v === null ? '' : typeof v === 'string' ? v : JSON.stringify(v);
|
||||||
|
}
|
||||||
|
function set(key: string, v: Json | undefined) {
|
||||||
|
if (!cfg) return;
|
||||||
|
if (v === '' || v === undefined) delete cfg[key];
|
||||||
|
else cfg[key] = v;
|
||||||
|
}
|
||||||
|
|
||||||
|
let preview = $state<Preview | null>(null);
|
||||||
|
let previewTimer: ReturnType<typeof setTimeout>;
|
||||||
|
$effect(() => {
|
||||||
|
if (!tab?.draft || level !== 'request') return;
|
||||||
|
const snapshot = JSON.stringify(tab.draft);
|
||||||
|
const env = ws.env(tab.col);
|
||||||
|
clearTimeout(previewTimer);
|
||||||
|
previewTimer = setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
preview = await api.preview({ col: tab.col, request_id: tab.id, request: JSON.parse(snapshot) as Request, env });
|
||||||
|
} catch (e) {
|
||||||
|
preview = { request: null, auth: { kind: '', origin: null, source: null, steps: [], sent: [], warnings: [], flow_id: null }, missing: [], error: String(e) };
|
||||||
|
}
|
||||||
|
}, 250);
|
||||||
|
});
|
||||||
|
|
||||||
|
const fieldVisible = (f: Field) => !f.when || f.when(cfg ?? { type: '' });
|
||||||
|
const mask = (v: string) => (ws.maskSecrets ? '••••••' : v);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-4 p-3">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<span class="w-28 shrink-0 text-fg-muted">Type</span>
|
||||||
|
<select class="k-field !w-64 !border-line !bg-input !font-sans" value={kind} onchange={(e) => setKind((e.currentTarget as HTMLSelectElement).value)}>
|
||||||
|
{#if level !== 'collection'}<option value="inherit">Inherit from {level === 'request' ? 'folder / collection' : 'collection'}</option>{/if}
|
||||||
|
<option value="none">No auth</option>
|
||||||
|
{#each AUTH_TYPES as t}<option value={t.id}>{t.label}</option>{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if cfg?.type === 'oauth2' || cfg?.type === 'oidc'}
|
||||||
|
<OAuthConfig cfg={cfg} {tab} />
|
||||||
|
{:else if cfg}
|
||||||
|
{#each fields.filter(fieldVisible) as f (f.key)}
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
<label class="w-28 shrink-0 pt-1.5 text-fg-muted" for="auth-{f.key}">{f.label}</label>
|
||||||
|
<div class="flex min-w-0 max-w-xl flex-1 flex-col gap-1">
|
||||||
|
{#if f.kind === 'select'}
|
||||||
|
<select id="auth-{f.key}" class="k-field !w-64 !border-line !bg-input !font-sans" value={str(f.key) || String(f.default ?? '')} onchange={(e) => set(f.key, (e.currentTarget as HTMLSelectElement).value)}>
|
||||||
|
{#each f.options ?? [] as o}<option value={o.value}>{o.label}</option>{/each}
|
||||||
|
</select>
|
||||||
|
{:else if f.kind === 'bool'}
|
||||||
|
<label class="flex items-center gap-2 pt-1">
|
||||||
|
<input type="checkbox" class="size-3.5 accent-[var(--knock-cyan)]" checked={cfg[f.key] === undefined ? !!f.default : !!cfg[f.key]} onchange={(e) => set(f.key, (e.currentTarget as HTMLInputElement).checked)} />
|
||||||
|
<span class="text-[12px] text-fg-muted">{f.help ?? ''}</span>
|
||||||
|
</label>
|
||||||
|
{:else if f.kind === 'textarea'}
|
||||||
|
<textarea id="auth-{f.key}" class="k-field mono h-28 !border-line !bg-input" value={str(f.key)} oninput={(e) => set(f.key, (e.currentTarget as HTMLTextAreaElement).value)} placeholder={f.placeholder}></textarea>
|
||||||
|
{:else}
|
||||||
|
<div class="flex rounded border border-line bg-input">
|
||||||
|
<VarInput value={str(f.key)} secret={f.secret} placeholder={f.placeholder} oninput={(v) => set(f.key, v)} />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if f.help && f.kind !== 'bool'}<span class="text-[11.5px] text-fg-subtle">{f.help}</span>{/if}
|
||||||
|
{#if f.secret && str(f.key) && !str(f.key).includes('{{')}
|
||||||
|
<span class="flex items-center gap-1 text-[11.5px] text-post"><Icon name="alert" size={11} />This value would be saved in the request file. Use <code class="mono">{`{{secret.${f.key}}}`}</code> and store it in the keyring.</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{:else if kind === 'inherit'}
|
||||||
|
<p class="text-fg-muted">Uses the auth of the closest folder, or of the collection.</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if level === 'request' && preview}
|
||||||
|
<div class="mt-2 border-t border-line pt-3">
|
||||||
|
<div class="k-label mb-2">What will be sent</div>
|
||||||
|
{#if preview.error}
|
||||||
|
<p class="text-delete">{preview.error}</p>
|
||||||
|
{:else}
|
||||||
|
{#if preview.auth.origin && preview.auth.kind !== 'none'}
|
||||||
|
<p class="mb-2 text-[12px] text-fg-muted">
|
||||||
|
{preview.auth.kind} auth from the {preview.auth.origin}{preview.auth.origin !== 'request' ? ` (${preview.auth.source})` : ''}
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
{#each preview.auth.sent as s}
|
||||||
|
<div class="mono flex gap-2 py-0.5 text-[12px]">
|
||||||
|
<span class="text-fg-subtle">{s.location}</span>
|
||||||
|
<span class="text-get">{s.name}</span>
|
||||||
|
<span class="min-w-0 break-all text-fg">{mask(s.value)}</span>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#each preview.auth.warnings as w}
|
||||||
|
<p class="flex items-center gap-1.5 py-0.5 text-[12px] text-post"><Icon name="alert" size={12} />{w}</p>
|
||||||
|
{/each}
|
||||||
|
{#each preview.auth.steps.filter((s) => s.status === 'error') as s}
|
||||||
|
<p class="py-0.5 text-[12px] text-delete">{s.title}: {s.summary}</p>
|
||||||
|
{/each}
|
||||||
|
{#if preview.auth.kind === 'none' || !preview.auth.kind}
|
||||||
|
<p class="text-[12px] text-fg-subtle">No auth is attached.</p>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { AuthConfig } from '$lib/types';
|
||||||
|
import type { Tab } from '$lib/state/workspace.svelte';
|
||||||
|
|
||||||
|
let { cfg, tab }: { cfg: AuthConfig; tab?: Tab } = $props();
|
||||||
|
void cfg;
|
||||||
|
void tab;
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { toast } from '@joshicodes/cock';
|
||||||
|
import { ws } from '$lib/state/workspace.svelte';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
name: string;
|
||||||
|
token: string;
|
||||||
|
/** Expected audience and scopes, for warnings. */
|
||||||
|
audience?: string;
|
||||||
|
scopes?: string[];
|
||||||
|
/** Server clock skew in seconds (server minus local), from the Date header. */
|
||||||
|
skew?: number | null;
|
||||||
|
signature?: string | null;
|
||||||
|
}
|
||||||
|
let { name, token, audience, scopes, skew = null, signature = null }: Props = $props();
|
||||||
|
|
||||||
|
const CLAIMS: Record<string, string> = {
|
||||||
|
iss: 'Issuer: who created the token',
|
||||||
|
sub: 'Subject: who the token is about',
|
||||||
|
aud: 'Audience: which API may accept it',
|
||||||
|
exp: 'Expires at',
|
||||||
|
iat: 'Issued at',
|
||||||
|
nbf: 'Not valid before',
|
||||||
|
jti: 'Unique token id',
|
||||||
|
scope: 'Granted scopes',
|
||||||
|
scp: 'Granted scopes',
|
||||||
|
azp: 'Authorized party: the client the token was issued to',
|
||||||
|
nonce: 'Value from the login request, ties the ID token to it',
|
||||||
|
auth_time: 'When the user authenticated',
|
||||||
|
acr: 'Authentication context class',
|
||||||
|
amr: 'Authentication methods used',
|
||||||
|
sid: 'Session id',
|
||||||
|
client_id: 'Client the token was issued to',
|
||||||
|
typ: 'Token type',
|
||||||
|
alg: 'Signature algorithm',
|
||||||
|
kid: 'Key id, used to find the signing key in the JWKS'
|
||||||
|
};
|
||||||
|
|
||||||
|
function b64url(s: string): string {
|
||||||
|
const pad = s.replace(/-/g, '+').replace(/_/g, '/');
|
||||||
|
const bin = atob(pad + '==='.slice((pad.length + 3) % 4));
|
||||||
|
return new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let decoded = $derived.by(() => {
|
||||||
|
const parts = token.split('.');
|
||||||
|
if (parts.length !== 3) return null;
|
||||||
|
try {
|
||||||
|
return { header: JSON.parse(b64url(parts[0])), payload: JSON.parse(b64url(parts[1])) } as {
|
||||||
|
header: Record<string, unknown>;
|
||||||
|
payload: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let now = $state(Date.now() / 1000);
|
||||||
|
$effect(() => {
|
||||||
|
const t = setInterval(() => (now = Date.now() / 1000), 1000);
|
||||||
|
return () => clearInterval(t);
|
||||||
|
});
|
||||||
|
|
||||||
|
let warnings = $derived.by(() => {
|
||||||
|
const w: string[] = [];
|
||||||
|
const p = decoded?.payload;
|
||||||
|
if (!p) return w;
|
||||||
|
if (typeof p.exp === 'number' && p.exp < now) w.push('Expired');
|
||||||
|
if (typeof p.nbf === 'number' && p.nbf > now + 30) w.push('Not valid yet (nbf is in the future)');
|
||||||
|
if (audience) {
|
||||||
|
const aud = Array.isArray(p.aud) ? p.aud : [p.aud];
|
||||||
|
if (!aud.includes(audience)) w.push(`aud does not contain "${audience}"`);
|
||||||
|
}
|
||||||
|
if (scopes?.length) {
|
||||||
|
const granted = String(p.scope ?? p.scp ?? '').split(/[\s,]+/);
|
||||||
|
const missing = scopes.filter((s) => !granted.includes(s));
|
||||||
|
if (missing.length && (p.scope || p.scp)) w.push(`Scope missing: ${missing.join(', ')}`);
|
||||||
|
}
|
||||||
|
return w;
|
||||||
|
});
|
||||||
|
|
||||||
|
function timeValue(k: string, v: unknown): boolean {
|
||||||
|
return ['exp', 'iat', 'nbf', 'auth_time', 'updated_at'].includes(k) && typeof v === 'number';
|
||||||
|
}
|
||||||
|
|
||||||
|
function countdown(sec: number): string {
|
||||||
|
const d = Math.round(sec - now);
|
||||||
|
const abs = Math.abs(d);
|
||||||
|
const s = abs < 120 ? `${abs} s` : abs < 7200 ? `${Math.round(abs / 60)} min` : abs < 172800 ? `${Math.round(abs / 3600)} h` : `${Math.round(abs / 86400)} days`;
|
||||||
|
return d >= 0 ? `in ${s}` : `${s} ago`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const shown = (v: string) => (ws.maskSecrets ? '••••••' : v);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="rounded border border-line">
|
||||||
|
<div class="flex items-center gap-2 border-b border-line px-2 py-1">
|
||||||
|
<span class="k-label">{name.replace(/_/g, ' ')}</span>
|
||||||
|
<span class="text-[11px] text-fg-subtle">{decoded ? `JWT · ${decoded.header.alg ?? '?'}` : 'opaque token'}</span>
|
||||||
|
{#if signature}<span class="text-[11px] {signature === 'valid' ? 'text-ok' : 'text-delete'}">signature {signature}</span>{/if}
|
||||||
|
<span class="flex-1"></span>
|
||||||
|
<button
|
||||||
|
class="text-[11px] text-accent"
|
||||||
|
onclick={() => {
|
||||||
|
navigator.clipboard.writeText(token);
|
||||||
|
toast.success('Token copied');
|
||||||
|
}}>copy</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{#each warnings as w}
|
||||||
|
<div class="border-b border-line bg-delete/8 px-2 py-1 text-[12px] text-delete">{w}</div>
|
||||||
|
{/each}
|
||||||
|
{#if !decoded}
|
||||||
|
<div class="mono break-all px-2 py-1.5 text-[11.5px] text-fg-muted">{shown(token)}</div>
|
||||||
|
<p class="px-2 pb-2 text-[11.5px] text-fg-subtle">Not a JWT, so knock cannot read it. Token introspection (RFC 7662) asks the server what it means.</p>
|
||||||
|
{:else}
|
||||||
|
{#each [['header', decoded.header], ['payload', decoded.payload]] as [label, obj]}
|
||||||
|
<div class="k-label px-2 pt-2">{label}</div>
|
||||||
|
{#each Object.entries(obj as Record<string, unknown>) as [k, v]}
|
||||||
|
<div class="mono flex items-start gap-3 px-2 py-0.5 text-[12px]">
|
||||||
|
<span class="w-28 shrink-0 text-get" title={CLAIMS[k] ?? ''}>{k}</span>
|
||||||
|
<span class="min-w-0 flex-1 break-all">
|
||||||
|
{#if timeValue(k, v)}
|
||||||
|
{new Date((v as number) * 1000).toLocaleString()}
|
||||||
|
<span class="font-sans text-fg-muted">({countdown(v as number)})</span>
|
||||||
|
{:else}
|
||||||
|
{typeof v === 'string' ? v : JSON.stringify(v)}
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
{#if CLAIMS[k]}<span class="hidden shrink-0 font-sans text-[11px] text-fg-subtle xl:inline">{CLAIMS[k]}</span>{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{/each}
|
||||||
|
{#if skew !== null && Math.abs(skew) > 5}
|
||||||
|
<p class="px-2 pb-2 pt-1 text-[11.5px] text-post">Your clock is {Math.abs(Math.round(skew))} s {skew > 0 ? 'behind' : 'ahead of'} the server (Date header). Expiry checks can be off by that much.</p>
|
||||||
|
{/if}
|
||||||
|
<div class="h-1.5"></div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import type { AuthConfig, Json } from '$lib/types';
|
||||||
|
|
||||||
|
export interface Field {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
kind?: 'text' | 'select' | 'bool' | 'textarea';
|
||||||
|
secret?: boolean;
|
||||||
|
placeholder?: string;
|
||||||
|
help?: string;
|
||||||
|
default?: Json;
|
||||||
|
options?: { value: string; label: string }[];
|
||||||
|
when?: (c: AuthConfig) => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AUTH_TYPES = [
|
||||||
|
{ id: 'basic', label: 'Basic' },
|
||||||
|
{ id: 'bearer', label: 'Bearer token' },
|
||||||
|
{ id: 'apikey', label: 'API key' },
|
||||||
|
{ id: 'oauth2', label: 'OAuth 2.0' },
|
||||||
|
{ id: 'oidc', label: 'OpenID Connect' },
|
||||||
|
{ id: 'digest', label: 'Digest' },
|
||||||
|
{ id: 'jwt', label: 'JWT (self-signed)' },
|
||||||
|
{ id: 'awsv4', label: 'AWS Signature v4' },
|
||||||
|
{ id: 'oauth1', label: 'OAuth 1.0a' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const opt = (...v: string[]) => v.map((x) => ({ value: x, label: x }));
|
||||||
|
|
||||||
|
export function authFields(type: string): Field[] {
|
||||||
|
switch (type) {
|
||||||
|
case 'basic':
|
||||||
|
return [
|
||||||
|
{ key: 'username', label: 'Username' },
|
||||||
|
{ key: 'password', label: 'Password', secret: true, placeholder: '{{secret.password}}' }
|
||||||
|
];
|
||||||
|
case 'bearer':
|
||||||
|
return [
|
||||||
|
{ key: 'token', label: 'Token', secret: true, placeholder: '{{secret.token}}' },
|
||||||
|
{ key: 'prefix', label: 'Prefix', placeholder: 'Bearer', help: 'Sent as "<prefix> <token>". Empty sends the token alone.' }
|
||||||
|
];
|
||||||
|
case 'apikey':
|
||||||
|
return [
|
||||||
|
{ key: 'key', label: 'Name', placeholder: 'X-API-Key' },
|
||||||
|
{ key: 'value', label: 'Value', secret: true, placeholder: '{{secret.apiKey}}' },
|
||||||
|
{ key: 'in', label: 'Send in', kind: 'select', default: 'header', options: [
|
||||||
|
{ value: 'header', label: 'Header' },
|
||||||
|
{ value: 'query', label: 'Query parameter' },
|
||||||
|
{ value: 'cookie', label: 'Cookie' }
|
||||||
|
] }
|
||||||
|
];
|
||||||
|
case 'digest':
|
||||||
|
return [
|
||||||
|
{ key: 'username', label: 'Username' },
|
||||||
|
{ key: 'password', label: 'Password', secret: true, placeholder: '{{secret.password}}' },
|
||||||
|
{ key: 'algorithm', label: 'Algorithm', kind: 'select', default: 'auto', options: [
|
||||||
|
{ value: 'auto', label: 'From server challenge' },
|
||||||
|
...opt('MD5', 'MD5-sess', 'SHA-256', 'SHA-256-sess')
|
||||||
|
] }
|
||||||
|
];
|
||||||
|
case 'jwt':
|
||||||
|
return [
|
||||||
|
{ key: 'algorithm', label: 'Algorithm', kind: 'select', default: 'HS256', options: opt('HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'EdDSA') },
|
||||||
|
{ key: 'secret', label: 'Secret', secret: true, placeholder: '{{secret.jwtSecret}}', when: (c) => String(c.algorithm ?? 'HS256').startsWith('HS') },
|
||||||
|
{ key: 'private_key', label: 'Private key', placeholder: 'path/to/key.pem or {{secret.jwtKey}}', help: 'PEM file relative to the collection, or a variable holding the PEM', when: (c) => !String(c.algorithm ?? 'HS256').startsWith('HS') },
|
||||||
|
{ key: 'claims', label: 'Claims', kind: 'textarea', placeholder: '{\n "sub": "{{userId}}",\n "aud": "api"\n}', help: 'JSON. iat and exp are added unless set here.' },
|
||||||
|
{ key: 'header', label: 'Extra header', kind: 'textarea', placeholder: '{ "kid": "key-1" }' },
|
||||||
|
{ key: 'expires_in', label: 'Lifetime', placeholder: '300', help: 'Seconds until exp' },
|
||||||
|
{ key: 'prefix', label: 'Prefix', placeholder: 'Bearer' }
|
||||||
|
];
|
||||||
|
case 'awsv4':
|
||||||
|
return [
|
||||||
|
{ key: 'access_key', label: 'Access key', placeholder: '{{awsAccessKey}}' },
|
||||||
|
{ key: 'secret_key', label: 'Secret key', secret: true, placeholder: '{{secret.awsSecretKey}}' },
|
||||||
|
{ key: 'session_token', label: 'Session token', secret: true },
|
||||||
|
{ key: 'region', label: 'Region', placeholder: 'eu-central-1' },
|
||||||
|
{ key: 'service', label: 'Service', placeholder: 'execute-api' },
|
||||||
|
{ key: 'sign_in', label: 'Signature in', kind: 'select', default: 'header', options: [
|
||||||
|
{ value: 'header', label: 'Authorization header' },
|
||||||
|
{ value: 'query', label: 'Query string (presigned)' }
|
||||||
|
] }
|
||||||
|
];
|
||||||
|
case 'oauth1':
|
||||||
|
return [
|
||||||
|
{ key: 'consumer_key', label: 'Consumer key' },
|
||||||
|
{ key: 'consumer_secret', label: 'Consumer secret', secret: true },
|
||||||
|
{ key: 'token', label: 'Token' },
|
||||||
|
{ key: 'token_secret', label: 'Token secret', secret: true },
|
||||||
|
{ key: 'signature_method', label: 'Signature', kind: 'select', default: 'HMAC-SHA1', options: opt('HMAC-SHA1', 'HMAC-SHA256', 'RSA-SHA1', 'RSA-SHA256', 'PLAINTEXT') },
|
||||||
|
{ key: 'private_key', label: 'Private key', placeholder: 'path/to/key.pem', when: (c) => String(c.signature_method ?? '').startsWith('RSA') },
|
||||||
|
{ key: 'realm', label: 'Realm' },
|
||||||
|
{ key: 'callback', label: 'Callback' },
|
||||||
|
{ key: 'verifier', label: 'Verifier' },
|
||||||
|
{ key: 'add_to', label: 'Parameters in', kind: 'select', default: 'header', options: [
|
||||||
|
{ value: 'header', label: 'Authorization header' },
|
||||||
|
{ value: 'query', label: 'Query string' },
|
||||||
|
{ value: 'body', label: 'Form body' }
|
||||||
|
] },
|
||||||
|
{ key: 'include_body_hash', label: 'Body hash', kind: 'bool', help: 'Add oauth_body_hash for non-form bodies' }
|
||||||
|
];
|
||||||
|
default:
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
let props: Record<string, unknown> = $props();
|
||||||
|
void props;
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Modal, Button, Field, Input } from '@joshicodes/cock';
|
||||||
|
import { open as openDialog } from '@tauri-apps/plugin-dialog';
|
||||||
|
import { dialogs } from '$lib/state/dialogs.svelte';
|
||||||
|
import { ws } from '$lib/state/workspace.svelte';
|
||||||
|
import ImportDialog from './ImportDialog.svelte';
|
||||||
|
import RunnerDialog from './RunnerDialog.svelte';
|
||||||
|
import CodeDialog from './CodeDialog.svelte';
|
||||||
|
|
||||||
|
let d = $derived(dialogs.current);
|
||||||
|
let open = $derived(!!d);
|
||||||
|
let promptValue = $state('');
|
||||||
|
let colName = $state('');
|
||||||
|
let colPath = $state('');
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (d?.kind === 'prompt') promptValue = d.value;
|
||||||
|
if (d?.kind === 'new-collection') {
|
||||||
|
colName = '';
|
||||||
|
colPath = '';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function finishConfirm(ok: boolean) {
|
||||||
|
const c = dialogs.current;
|
||||||
|
dialogs.current = null;
|
||||||
|
if (c?.kind === 'confirm') c.resolve(ok);
|
||||||
|
}
|
||||||
|
function finishPrompt(v: string | null) {
|
||||||
|
const c = dialogs.current;
|
||||||
|
dialogs.current = null;
|
||||||
|
if (c?.kind === 'prompt') c.resolve(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pickFolder() {
|
||||||
|
const dir = await openDialog({ directory: true, title: 'Folder for the new collection' });
|
||||||
|
if (typeof dir === 'string') {
|
||||||
|
colPath = dir;
|
||||||
|
if (!colName) colName = dir.split('/').pop() ?? '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createCollection() {
|
||||||
|
if (!colPath || !colName.trim()) return;
|
||||||
|
const c = await ws.create(colPath, colName.trim());
|
||||||
|
if (c) dialogs.current = null;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if d?.kind === 'confirm'}
|
||||||
|
<Modal {open} title={d.title} description={d.body} size="sm" onclose={() => finishConfirm(false)}>
|
||||||
|
{#snippet footer()}
|
||||||
|
<div class="flex w-full justify-end gap-2">
|
||||||
|
<Button variant="ghost" onclick={() => finishConfirm(false)}>Cancel</Button>
|
||||||
|
<Button variant={/delete|clear|discard/i.test(d.action) ? 'danger' : 'solid'} onclick={() => finishConfirm(true)}>{d.action}</Button>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</Modal>
|
||||||
|
{:else if d?.kind === 'prompt'}
|
||||||
|
<Modal {open} title={d.title} size="sm" onclose={() => finishPrompt(null)}>
|
||||||
|
<Field label={d.label}>
|
||||||
|
{#snippet children(attrs)}
|
||||||
|
<Input {...attrs} bind:value={promptValue} onkeydown={(e: KeyboardEvent) => e.key === 'Enter' && finishPrompt(promptValue)} />
|
||||||
|
{/snippet}
|
||||||
|
</Field>
|
||||||
|
{#snippet footer()}
|
||||||
|
<div class="flex w-full justify-end gap-2">
|
||||||
|
<Button variant="ghost" onclick={() => finishPrompt(null)}>Cancel</Button>
|
||||||
|
<Button onclick={() => finishPrompt(promptValue)}>{d.action}</Button>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</Modal>
|
||||||
|
{:else if d?.kind === 'new-collection'}
|
||||||
|
<Modal {open} title="New collection" description="A collection is a folder. knock writes knock.yaml, an environments folder and a .gitignore for secrets into it." size="md" onclose={() => dialogs.close()}>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<Field label="Name">
|
||||||
|
{#snippet children(attrs)}<Input {...attrs} bind:value={colName} placeholder="My API" />{/snippet}
|
||||||
|
</Field>
|
||||||
|
<Field label="Folder" description="Pick an empty folder, or one inside a git repository.">
|
||||||
|
{#snippet children(attrs)}
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Input {...attrs} bind:value={colPath} class="mono flex-1" placeholder="/home/you/projects/my-api/knock" />
|
||||||
|
<Button variant="outline" onclick={pickFolder}>Choose…</Button>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
{#snippet footer()}
|
||||||
|
<div class="flex w-full justify-end gap-2">
|
||||||
|
<Button variant="ghost" onclick={() => dialogs.close()}>Cancel</Button>
|
||||||
|
<Button onclick={createCollection} disabled={!colPath || !colName.trim()}>Create</Button>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</Modal>
|
||||||
|
{:else if d?.kind === 'import'}
|
||||||
|
<ImportDialog />
|
||||||
|
{:else if d?.kind === 'runner'}
|
||||||
|
<RunnerDialog col={d.col} folder={d.folder} />
|
||||||
|
{:else if d?.kind === 'code'}
|
||||||
|
<CodeDialog tabKey={d.tabKey} />
|
||||||
|
{/if}
|
||||||