diff --git a/README.md b/README.md index 3290c27..d0f14ac 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,11 @@ A lightweight terminal REST client for development and testing: - **Postman-compatible storage.** Collections and environments are Postman files, edited in place: v2.1 JSON, or the v3 YAML folders that Postman v12 keeps in Git. TermRest writes them back as Postman would (untouched JSON byte-for-byte; in YAML only the lines you changed) and keeps everything it doesn't understand (examples, unknown fields). - **Scripts in Python, JavaScript, C# or PowerShell.** Pre-request and test scripts for collections, folders and requests, with variables, request changes and tests. JavaScript scripts use Postman's `pm` object, so Postman collections' scripts run too. Each language runs in the runtime you choose: your project's Python, Node.js or Bun, the .NET SDK, and PowerShell 7, with the packages and modules you installed (NuGet packages for C#). A script can have a version in each language (Postman's JavaScript next to a PowerShell one, say): each request runs one language only, the first of your order that has all its scripts, or the one it chooses. TermRest carries no script engine: a runtime starts for its first script and stops when idle. See [Scripts](#scripts). **Scripts are not sandboxed:** they run with your permissions, so turn them on only for collections you trust (see [Script safety](#script-safety)). - **Request history and cURL import.** Every request you send is kept per workspace, with credentials masked, ready to reopen, send again or save. Paste a curl command (for example from a browser's *Copy as cURL*) into the URL bar to import it. +- **Find, filter and color responses.** Ctrl+F finds text in the response. A JSONPath query ([RFC 9535](https://www.rfc-editor.org/rfc/rfc9535)) filters a JSON body, in the UI and with `send --filter`. JSON, XML and HTML bodies are colored, request bodies too. - **Recording.** Press Record (F12) and every request and response you send is recorded. On stop, TermRest asks where to save it as a HAR file (JSON, opens in browser dev tools). Credentials, cookies, tokens and secret variables are redacted, files sent with a request are recorded by path only, and a recording streams to a private temporary file instead of growing in memory. - **Large bodies from files.** Send a file as the body without loading it: it is streamed when the request is sent, and a JSON or XML file is checked first. - **Client certificates (mutual TLS)** are first-class: PEM (including encrypted keys and chains), PFX/PKCS#12, and OS certificate stores. That includes the Windows certificate store with non-exportable keys and the macOS keychain. Certificates bind to URL patterns via a Newman-compatible registry, and a TLS tab shows exactly what was negotiated and presented. -- **One native executable** per platform: Windows, macOS and Linux on x64 and ARM64. Built with .NET 10 Native AOT: under 20 MB, starts in about 50 ms, no runtime to install. +- **One native executable** per platform: Windows, macOS and Linux on x64 and ARM64. Built with .NET 10 Native AOT: about 20 MB, starts in about 50 ms, no runtime to install. - **A headless CLI** (`send`, `run`, `validate`, `convert`, `history`, `import-curl`, `certs`) for scripts and CI, using the same engine. > Status: **first prototype** (v0.1). See [Roadmap](#roadmap) and the original [design proposal](docs/design-proposal.md). @@ -37,7 +38,7 @@ A lightweight terminal REST client for development and testing: │ ││╭────╮───────╮────────╮───╮ │ │ │││Body│Headers│Timeline│TLS│ │ │ │││ ╰───────┴────────┴───┴─────────────────────────────────────────────────────────╮│ -│ │││Pretty: on Wrap: off Copy Save as… ││ +│ │││Pretty: on Wrap: off Copy Save as… Filter ││ │ │││{ ▲││ │ │││ "args": { █││ │ │││ "foo": "bar", ░││ @@ -126,6 +127,7 @@ A request that is not in a collection (a new one, an imported curl command, or o | F6 / Shift+F6 | Next / previous pane | Tab / Shift+Tab | Next / previous field | | F10 | Menu | Shift+F10 | Context menu | | Ctrl+L | Focus the URL bar | Ctrl+Q | Quit (asks to save) | +| Ctrl+F | Find in the response (see [Response tabs](#using-the-ui)) | F3 / Shift+F3 | Next / previous match | | F12 | Start / stop recording (see [Recording requests](#recording-requests)) | ← / → on a tab row | Previous / next tab (Home / End: first / last; ↓ or Enter: into the page) | **Request editor tabs** @@ -133,7 +135,7 @@ A request that is not in a collection (a new one, an imported curl command, or o - **Params:** query parameters (kept in sync with the URL) and path variables (`:id` segments). Values are sent as typed, except that a `#` in a query parameter, a path variable or a `{{variable}}` in the path, and a `?` in a path variable, are sent percent-encoded (`%23`, `%3F`): they stay part of the value instead of ending the query or path, where the rest would not be sent. - **Headers:** values are sent as typed, in UTF-8 as curl sends them (`X-User: José` works), and cookies a server set go back in the bytes it sent them in; a value with a line break or NUL is refused (a trailing line break is dropped), so a value can never add a header of its own. Headers that describe a body (`Content-Type`, `Content-Encoding` …) are left out of a request without one, with a warning. - **Auth:** inherit, none, Basic, Bearer, API key, Digest, NTLM, or an OAuth 2.0 access token. Other Postman auth types are kept but not yet applied. Passwords, tokens and API key values are masked. An empty Bearer token (as a login request's script fills in later) adds no header, as in Postman, and a warning says so: an `Authorization` header the request has stays. Digest and NTLM credentials answer only their own scheme's challenges (NTLM also Negotiate) from the request's origin, never a Basic one. Credentials in the URL (`https://user:password@host`) are sent as Basic auth, as curl and Postman send them, unless the request has an `Authorization` header or an auth helper; as in Postman, a `{{variable}}` there may hold any character: `@ / ? # \` in its value are encoded, so a password with them neither ends the user info nor makes the URL invalid. The history masks the password, or the user name of a URL without one (`https://***@host`), which is then the credential. An API key or OAuth 2.0 token sent in the query is URL-encoded and replaces a parameter of the same name. -- **Body:** none, raw (JSON, XML, text, HTML, JavaScript, with Beautify), form-data with files, x-www-form-urlencoded, a file (see [Sending a file as the body](#sending-a-file-as-the-body)), or GraphQL. Form-data is sent as browsers, curl and Postman send it: field and file names in UTF-8, a field's content type as typed (one with a line break or NUL is refused), and a file without one with the type of its extension (`.gif`, `.jpg`, `.jpeg`, `.png`, `.svg`, `.txt`, `.htm`, `.html`, `.pdf`, `.xml`, `.json`; any other gets `application/octet-stream`). An empty body is no body, sent without a `Content-Type`, as in Postman: raw text that is empty once its `{{variables}}` are replaced, a form with no enabled field, or a file body without a file (a warning says so). +- **Body:** none, raw (JSON, XML, text, HTML, JavaScript, colored in the language chosen, with Beautify), form-data with files, x-www-form-urlencoded, a file (see [Sending a file as the body](#sending-a-file-as-the-body)), or GraphQL (its variables colored as JSON). Form-data is sent as browsers, curl and Postman send it: field and file names in UTF-8, a field's content type as typed (one with a line break or NUL is refused), and a file without one with the type of its extension (`.gif`, `.jpg`, `.jpeg`, `.png`, `.svg`, `.txt`, `.htm`, `.html`, `.pdf`, `.xml`, `.json`; any other gets `application/octet-stream`). An empty body is no body, sent without a `Content-Type`, as in Postman: raw text that is empty once its `{{variables}}` are replaced, a form with no enabled field, or a file body without a file (a warning says so). - **Scripts:** pre-request and post-response (test) scripts, in Python, JavaScript, C# or PowerShell (see [Scripts](#scripts)). - **Settings:** per-request SSL verification and redirects, which client certificate applies, and the description. Redirects are followed like `curl -L`: at most *max redirects* (0 follows none; a negative `maxRedirects` on a request, as earlier imports of `--max-redirs -1` saved it, uses the workspace's), never from https to http; 301 and 302 turn a POST into a GET, 303 any method but HEAD, and 307 and 308 send the method and body again. The `Authorization`, `Proxy-Authorization`, `Cookie` and `Host` headers and the auth helper's (such as an API key) go only to the request's origin (scheme, host and port); other headers follow the redirect. The URL a redirect leads to never takes the user and password of the request's URL (they are sent as its `Authorization` header), so it is shown, kept in the history and recorded without them. @@ -141,12 +143,15 @@ Text editors show tabs 4 columns wide (the Tab key moves to the next field). Eve **Response tabs** -- **Body:** pretty or raw view, wrap, copy (the whole body as shown, with its own line breaks), save (as received). *Save as…* asks before replacing a file (*Cancel* is the default), and its message says when that is not the body as received: only the start of one the maximum response size cut, or the copy a history entry keeps (secrets masked as `***`, and cut at the history's size limit). A body over 1 MB shows its first 1 MB with a note; Copy and Save as… still give all of it. A large body shows *Formatting…* while it is prepared. XML with a document type (``) is shown as received: its entities are never expanded. +- **Body:** pretty or raw view, wrap, copy (the whole body as shown, with its own line breaks), save (as received). *Save as…* asks before replacing a file (*Cancel* is the default), and its message says when that is not the body as received: only the start of one the maximum response size cut, or the copy a history entry keeps (secrets masked as `***`, and cut at the history's size limit). A body over 1 MB shows its first 1 MB with a note; Copy and Save as… still give all of it. A large body shows *Formatting…* while it is prepared. XML with a document type (``) is shown as received: its entities are never expanded. JSON, XML, HTML and JavaScript bodies are colored as their Content-Type says, also with words wrapped; so are JSON and markup in a body of another type (`text/plain`) or none. +- **Filter:** shows a JSONPath row in the Body tab. Type a query ([RFC 9535](https://www.rfc-editor.org/rfc/rfc9535): `$.items[?@.price < 10].name`, `$..id`, `$.users[-1]`, with the functions `length`, `count`, `match`, `search` and `value`), and the body shows the values it selects as a JSON array (pretty, or on one line with *Pretty: off*), for this response and the ones after it, until you close the row (✕, Esc, or Filter again). The row says how many values the query selects, or why it can't: a query being typed that isn't valid JSONPath yet (the body keeps the last result meanwhile, and the message says where the query goes wrong), or a body that isn't JSON (shown as it is). NDJSON and JSON Lines bodies are filtered as an array of their lines. Copy copies the values (up to 16 MB of them); *Save as…* still saves the body as received. A large body shows *Filtering…* while the query runs. - **Headers:** as the server sent them, `Content-Encoding` and `Content-Length` included. A value too long for the pane ends with `…`: Enter or a double-click on its row shows the whole header, wrapped, to read or select, and *Copy* (the default button) copies its value. gzip, deflate and br bodies are decoded; a body that can't be decoded, or uses another coding, is kept as received, with a warning. The maximum response size applies to the body as received and once decoded. - **Timeline:** the exact request sent (with the generated `Accept-Encoding: gzip, deflate, br`, unless you typed one, such as `identity`, which is sent instead), DNS/connect/TLS/TTFB/download timing, and warnings. - **TLS:** protocol and cipher, the client certificate sent and whether the server asked for one, and the server chain with validation details. - **Scripts:** what the scripts did: tests, printed output, errors with their traceback, and the variables they set. Like a body, what is over 1 MB shows its first 1 MB with a note. +**Find** (**Ctrl+F**, from anywhere in the window, or *Request › Find in response*) opens a bar under the response. It looks in the text of the tab shown (Body, Timeline, TLS or Scripts) as you type, ignoring case unless you check *Match case*. Every match is highlighted, and the one selected is scrolled into view: **Enter** or **F3** selects the next one, **Shift+Enter** or **Shift+F3** the previous one, going round (▲ and ▼ do the same). The bar says which match is selected, of how many (at most 100,000 are counted). It looks in the text as shown: the values a filter selects, the start of a body over 1 MB. **Esc** closes it. In text fields and editors, Ctrl+F no longer moves the cursor right (an Emacs key of Terminal.Gui's). + ### Sending a file as the body For a large payload, choose **file** in the Body tab instead of pasting it into the editor. TermRest keeps only the file's path and reads the file each time the request is sent, streaming it: it is never loaded into memory, and you can keep editing it in another program, even one that keeps it open for writing (Excel, a log writer). Whatever such a program adds while the file is being sent is left out: it is sent as long as it was when sending started (form-data files too). @@ -653,7 +658,7 @@ termrest certs match https://client.badssl.com/ samples ```text termrest [] [--theme ] open the UI (default: current directory) -termrest send [opts] send one request; body to stdout (pipes and files get binary bodies, and any body with --raw, exactly as received), status/diagnostics to stderr +termrest send [opts] send one request; body to stdout (pipes and files get binary bodies, and any body with --raw, exactly as received; with --filter, the values a JSONPath query selects), status/diagnostics to stderr termrest run [--folder F] [opts] run all requests in order, with their scripts; exit code 1 if any fail, files of the collection can't be read, or the report or recording can't be written termrest validate check that files (JSON, YAML, v3 folders) round-trip unchanged through TermRest termrest convert [--to v3|v2.1] [-o O] convert a collection or environment between v2.1 JSON and v3 YAML; exit code 1, writing nothing, if files of the collection can't be read or the result can't be written. A folder must be a v3 collection (with `.resources/definition.yaml` or `*.request.yaml` files; in `postman/collections`, in its folders too), for `validate` too @@ -667,7 +672,7 @@ termrest snapshot [] [--send] render the UI headlessly (smoke t common options: -e/--env --var key=value --timeout -k/--insecure --record --python --javascript --csharp --powershell --script-order --no-scripts --allow-outside-files -send options: -i/--include -v/--verbose -o/--output --raw -f/--fail --curl --no-history +send options: -i/--include -v/--verbose -o/--output --raw --filter -f/--fail --curl --no-history run options: --bail --allow-http-errors --report-json history options: -n/--limit --show --json --clear import-curl options: --folder --name --dry-run @@ -681,6 +686,8 @@ snapshot options: --send --request --width --height --them termrest run "samples/TermRest Demo.postman_collection.json" -e "Postman Echo" --report-json report.json termrest send api.postman_collection.json "Users/Get user" --var userId=42 -i termrest send api.postman_collection.json "Users/Get user" --curl # print an equivalent curl command (scripts do not run; none, and exit code 2, if it can't be sent or curl can't send it the same way) +termrest send api.postman_collection.json "Users/List users" --filter '$.users[?@.active].email' + # only the values a JSONPath query selects, as a JSON array termrest run api.postman_collection.json --python .venv/bin/python # run the collection's Python scripts and tests termrest run postman-export.json --javascript node # run a Postman collection's pm.* scripts and tests termrest run api.postman_collection.json --csharp dotnet # build and run the collection's C# scripts and tests @@ -693,7 +700,9 @@ Paths on the command line are relative to the current folder, those of `--python The `--report-json` report redacts secrets the way [recordings](#recording-requests) do, test names and errors included. Missing folders are created; on Unix only you can read it. -`send` exits with 0 when done; 1 when there was no response, a test or script failed, the body couldn't be saved with `-o`, the recording wasn't saved, or files of the collection or the workspace settings can't be read; 2 for a usage problem (an unknown or ambiguous request or `-e` environment, or one `--curl` can't export); 22 for HTTP status 400 or more with `--fail`; 63 when the response body was cut at the maximum response size (*Tools › Settings*, `maxResponseSizeMb`, 50 MB), so what `-o` or standard output received is only its start; 130 when cancelled. Warnings raised while sending (a redirect not followed, a header left out, a cut body) are printed after the response. A name that matches several requests, in the workspace's collections or in one collection, is reported as ambiguous: give its path (`Folder/Name`) or its collection. So is an `-e` name that several environments of the workspace have: nothing is sent, and the error lists their files; pass one of them with `-e` instead (a JSON or YAML environment file). Without `-e`, the workspace's active environment is used. +`send --filter ` prints only the values a JSONPath query ([RFC 9535](https://www.rfc-editor.org/rfc/rfc9535), as in the UI's Filter) selects in a JSON body, as a JSON array: two-space indented, or on one line with `--raw`; with `-o`, it writes them to the file instead of the body. A query that isn't valid JSONPath is a usage error, reported with where it goes wrong before anything is sent; a body that isn't JSON (or binary, or empty) makes `send` exit with code 1. + +`send` exits with 0 when done; 1 when there was no response, a test or script failed, the body couldn't be saved with `-o` or filtered with `--filter`, the recording wasn't saved, or files of the collection or the workspace settings can't be read; 2 for a usage problem (an unknown or ambiguous request or `-e` environment, one `--curl` can't export, or a `--filter` query that isn't JSONPath); 22 for HTTP status 400 or more with `--fail`; 63 when the response body was cut at the maximum response size (*Tools › Settings*, `maxResponseSizeMb`, 50 MB), so what `-o` or standard output received is only its start; 130 when cancelled. Warnings raised while sending (a redirect not followed, a header left out, a cut body) are printed after the response. A name that matches several requests, in the workspace's collections or in one collection, is reported as ambiguous: give its path (`Folder/Name`) or its collection. So is an `-e` name that several environments of the workspace have: nothing is sent, and the error lists their files; pass one of them with `-e` instead (a JSON or YAML environment file). Without `-e`, the workspace's active environment is used. A body counts as binary when its Content-Type isn't text (`text/*`; JSON, XML or JavaScript named as a word of the subtype, as in `application/problem+json`, `application/x-ndjson` or `image/svg+xml`; form data), or, with no Content-Type, when it contains a NUL byte. Office documents (`application/vnd.openxmlformats-officedocument.…`) are ZIP files: binary. A console window shows binary content as a hex dump unless `--raw` asks for the bytes. Text bodies are decoded from the charset their Content-Type names (also one with a stray `;` at its end, which .NET's own parser rejects), legacy code pages included (windows-1252, Shift_JIS, GBK, Big5 …), and UTF-16 without a byte order mark in the byte order its text shows, in `send`, `history --show`, the UI, scripts and recordings. @@ -736,7 +745,7 @@ The [CI workflow](.github/workflows/ci.yml) tests on Windows, Linux and macOS. I src/TermRest.Core UI-free engine: Postman model + mapper (v2.1 JSON, v3 YAML), YAML reader/writer, variables, HTTP executor, certificates, history, recording (HAR, redaction), scripts (Python, JavaScript and PowerShell workers, C# programs built by the user's .NET SDK), - cURL import, workspace + cURL import, JSONPath (RFC 9535, with I-Regexp), workspace src/TermRest.Tui Terminal.Gui v2 views and dialogs src/TermRest.Cli `termrest` executable (System.CommandLine): TUI by default + headless commands tests/…Core.Tests xUnit v3: fidelity, mapper, URLs, variables, certificates, YAML, Postman v3, history, cURL, @@ -750,6 +759,7 @@ dotnet build dotnet test # Microsoft.Testing.Platform runner (see global.json) TERMREST_STORE_TESTS=1 dotnet test # Windows: also run the non-exportable cert-store mTLS test TERMREST_V3_CORPUS= dotnet test # also edit and revert every Postman v3 collection found under +TERMREST_JSONPATH_CTS= dotnet test # also run the JSONPath Compliance Test Suite (cts.json of github.com/jsonpath-standard/jsonpath-compliance-test-suite) TERMREST_TEST_PYTHON= dotnet test # the Python for script tests (default: python3 or python on PATH; skipped without) TERMREST_TEST_JAVASCRIPT= dotnet test # the Node.js or Bun for script tests (default: node or bun on PATH; skipped without) TERMREST_TEST_DOTNET= dotnet test # the .NET SDK (10+) for C# script tests (default: dotnet on PATH; skipped without) @@ -758,16 +768,15 @@ TERMREST_TEST_POWERSHELL= dotnet test # the PowerShell (7+) for PowerSh Notes: -- Terminal.Gui 2.5's `TextView` is marked obsolete in favour of the separate `Terminal.Gui.Editor` package. That package has not shipped a build for 2.5 yet, so TermRest uses `TextView` behind a small `TextArea` wrapper, which makes the later switch (folding, for one) a one-file change. `TextArea` also colors scripts: small hand-written lexers (`src/TermRest.Tui/Syntax`) color one line at a time from what the line above leaves open (a string or a comment), so an edit recolors only the lines down to the last one in view. +- Terminal.Gui 2.5's `TextView` is marked obsolete in favour of the separate `Terminal.Gui.Editor` package. That package has not shipped a build for 2.5 yet, so TermRest uses `TextView` behind a small `TextArea` wrapper, which makes the later switch (folding, for one) a one-file change. `TextArea` also colors scripts and bodies, and highlights what Find finds: small hand-written lexers (`src/TermRest.Tui/Syntax`) color one line at a time from what the line above leaves open (a string, a comment, a tag), so an edit recolors only the lines down to the last one in view; when words wrap, a line is colored whole and its colors split over its rows. - Mouse responsiveness: while the UI is in use (2 seconds after the last key or mouse event, and while a request is on its way), it runs Terminal.Gui's main loop at 60 passes per second and, on Windows, asks for 1 ms timer resolution (`UiPace`, `TimerResolution`), because Windows rounds the loop's and the input poll's sleeps up to 15.6 ms ticks. When idle, it goes back to Terminal.Gui's 25 passes and the system timer, so it costs next to nothing. The request and response tabs use `TabPanel` instead of Terminal.Gui's `Tabs`, which lays out and draws every page on each redraw; it looks the same and makes clicks, drags and resizes about twice as fast to repaint. - Unexpected errors in the UI are shown and logged to `errors.log` in TermRest's state folder (where the [history](#request-history) is kept), which only you can read; so are files that fail to save for a reason other than a disk or permission problem. The other files are saved anyway. - Each request uses a fresh connection, so timing and TLS details are exact; the TLS details are read as soon as the handshake completes, so they are there also for a server that closes the connection after its response (`Connection: close`, HTTP/1.0), and again once the response is in, for a server that asks for the client certificate only then (a TLS 1.2 renegotiation, as IIS does without *Negotiate Client Certificate*). Cookies persist for the session (**Tools › Clear cookies**). ## Roadmap -- **Next:** OAuth 2.0 token acquisition, including Entra ID client credentials with a certificate; response search and JSON path filtering; saving responses as Postman examples, and showing them in v3 collections. +- **Next:** OAuth 2.0 token acquisition, including Entra ID client credentials with a certificate; saving responses as Postman examples, and showing them in v3 collections. - **Phase 2:** - - Syntax highlighting of request and response bodies (scripts have it). - Proxy authentication. - Code snippets. - **Packaging:** winget, Homebrew, `.deb`/`.rpm`, and signed binaries. diff --git a/src/TermRest.Cli/SendCommand.cs b/src/TermRest.Cli/SendCommand.cs index 2e3e7da..28aa390 100644 --- a/src/TermRest.Cli/SendCommand.cs +++ b/src/TermRest.Cli/SendCommand.cs @@ -1,5 +1,7 @@ using System.CommandLine; +using System.Text; using TermRest.Core.Http; +using TermRest.Core.Json; using TermRest.Core.Postman; namespace TermRest.Cli; @@ -14,8 +16,9 @@ public static Command Create(Option insecure) var request = new Argument("request") { Description = "Request path such as \"Users/Get user\", or a unique request name" }; var include = new Option("--include", "-i") { Description = "Also print the response status line and headers to stdout" }; var verbose = new Option("--verbose", "-v") { Description = "Print the request, timing and TLS details to stderr" }; - var output = new Option("--output", "-o") { Description = "Write the raw response body to a file" }; - var raw = new Option("--raw") { Description = "Print the body as received (no JSON/XML pretty printing)" }; + var output = new Option("--output", "-o") { Description = "Write the raw response body (with --filter, the values selected) to a file" }; + var raw = new Option("--raw") { Description = "Print the body as received (no JSON/XML pretty printing); with --filter, the values on one line" }; + var filter = new Option("--filter") { Description = "Print only the values a JSONPath query (RFC 9535) selects in a JSON body, as an array: --filter '$.items[?@.price < 10].id'" }; var fail = new Option("--fail", "-f") { Description = "Exit with code 22 when the HTTP status is 400 or higher" }; var curl = new Option("--curl") { Description = "Print the request as a cURL command instead of sending it (scripts do not run)" }; var noHistory = new Option("--no-history") { Description = "Do not record this request in the workspace history" }; @@ -27,12 +30,28 @@ public static Command Create(Option insecure) command.Options.Add(verbose); command.Options.Add(output); command.Options.Add(raw); + command.Options.Add(filter); command.Options.Add(fail); command.Options.Add(curl); command.Options.Add(noHistory); command.SetAction(async (parseResult, cancellationToken) => { + // A query that is not valid JSONPath is reported before anything is sent. + JsonPath? query = null; + if (parseResult.GetValue(filter) is { } text) + { + try + { + query = JsonPath.Parse(text.TrimEnd()); + } + catch (JsonPathException ex) + { + Output.Error($"--filter: {ex.Message}"); + return 2; + } + } + if (options.Open(parseResult, parseResult.GetValue(collection)!, insecure) is not { } opened) { return 2; @@ -110,7 +129,7 @@ public static Command Create(Option insecure) printed = prepared.Warnings.Count; }, cancellationToken); var recorded = options.SaveRecording(parseResult, runner, recorder, cancellationToken.IsCancellationRequested); - var code = await ReportAsync(parseResult, exchange, verbose, include, output, raw, fail, cancellationToken); + var code = await ReportAsync(parseResult, exchange, query, verbose, include, output, raw, fail, cancellationToken); // Those raised while it was sent: a redirect not followed, a header left out, a body cut short … PrintWarnings(exchange.Request, printed); @@ -165,8 +184,8 @@ private static void PrintWarnings(PreparedRequest prepared, int from = 0) } private static async Task ReportAsync( - ParseResult parseResult, HttpExchange exchange, Option verbose, Option include, Option output, Option raw, Option fail, - CancellationToken cancellationToken) + ParseResult parseResult, HttpExchange exchange, JsonPath? query, Option verbose, Option include, Option output, Option raw, + Option fail, CancellationToken cancellationToken) { if (parseResult.GetValue(verbose)) { @@ -191,7 +210,14 @@ private static async Task ReportAsync( Console.Out.WriteLine(); } - if (parseResult.GetValue(output) is { } file) + if (query is not null) + { + if (await WriteFilteredAsync(query, response, parseResult.GetValue(raw), parseResult.GetValue(output), cancellationToken) is { } failed) + { + return failed; + } + } + else if (parseResult.GetValue(output) is { } file) { try { @@ -230,6 +256,44 @@ private static async Task ReportAsync( return response.BodyTruncated ? 63 : 0; } + /// The values selects in the body, printed or saved; the exit code when they cannot be. + private static async Task WriteFilteredAsync(JsonPath query, ResponseSnapshot response, bool compact, string? file, CancellationToken cancellationToken) + { + FilteredBody filtered; + try + { + filtered = BodyFilter.Apply(query, response.Body, response.ContentType, indented: !compact, cancellationToken: cancellationToken); + } + catch (JsonPathException ex) + { + Output.Error($"--filter: {ex.Message}"); + return 1; + } + catch (OperationCanceledException) + { + return 130; + } + + if (file is null) + { + Console.Out.WriteLine(filtered.Text); + return null; + } + + try + { + await File.WriteAllTextAsync(file, filtered.Text + "\n", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), cancellationToken); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + Output.Error($"The values could not be saved to {file}: {ex.Message}"); + return 1; + } + + Output.Info($"Saved {filtered.Count} value{(filtered.Count == 1 ? "" : "s")} to {file}"); + return null; + } + private static void PrintVerbose(HttpExchange exchange) { var request = exchange.Request; diff --git a/src/TermRest.Core/Http/BodyFilter.cs b/src/TermRest.Core/Http/BodyFilter.cs new file mode 100644 index 0000000..c5bd6a4 --- /dev/null +++ b/src/TermRest.Core/Http/BodyFilter.cs @@ -0,0 +1,140 @@ +using System.Buffers; +using System.Text; +using System.Text.Json; +using TermRest.Core.Json; + +namespace TermRest.Core.Http; + +/// The values a JSONPath query selects in a body, written as a JSON array. +/// The array: all the values, or the first when they would not fit the length asked. +/// How many values the query selects. +/// How many of them the array holds. +public sealed record FilteredBody(string Text, int Count, int Shown); + +/// Applies a JSONPath query to a response body. +public static class BodyFilter +{ + private static readonly JsonDocumentOptions DocumentOptions = new() { MaxDepth = 256 }; + + private static readonly JsonWriterOptions Indented = new() + { + Indented = true, + IndentCharacter = ' ', + IndentSize = 2, + NewLine = "\n", + Encoder = MinimalJsonEncoder.Instance, + MaxDepth = 1000, + }; + + private static readonly JsonWriterOptions Compact = new() { Encoder = MinimalJsonEncoder.Instance, MaxDepth = 1000 }; + + /// + /// The values selects in (decoded as it is shown: see + /// ; NDJSON and JSON Lines as an array of their lines), as a JSON array, two-space + /// indented or on one line. Values that would take it beyond of UTF-8 are left out. A + /// says why a body cannot be filtered: it is empty, binary or not JSON. + /// + public static FilteredBody Apply(JsonPath query, byte[] body, string? contentType, bool indented = true, long maxBytes = long.MaxValue, + CancellationToken cancellationToken = default) + { + if (body.Length == 0) + { + throw new JsonPathException("The body is empty."); + } + + if (!BodyFormatter.LooksLikeText(body, contentType)) + { + throw new JsonPathException("The body is binary, not JSON."); + } + + var text = BodyFormatter.Decode(body, contentType); + try + { + using var document = Parse(text, contentType); + var nodes = query.Select(document.RootElement, cancellationToken); + return Write(nodes, indented, maxBytes, cancellationToken); + } + catch (InvalidOperationException ex) when (ex is not ObjectDisposedException) + { + // System.Text.Json reads "\ud83d" (half of an emoji, cut by JavaScript), then fails on first access to it. + throw new JsonPathException("The body has a string holding half of a character (an unpaired surrogate such as \\ud83d)."); + } + } + + private static JsonDocument Parse(string text, string? contentType) + { + if (BodyFormatter.SubtypeHasWord(contentType, "ndjson", "jsonl", "jsonlines") && Lines(text) is { } lines) + { + return lines; + } + + try + { + return JsonDocument.Parse(text, DocumentOptions); + } + catch (JsonException ex) + { + throw new JsonPathException(ex.LineNumber is { } line + ? $"The body is not JSON: line {line + 1}, byte {ex.BytePositionInLine + 1}." + : "The body is not JSON."); + } + } + + /// JSON Lines: one array of the values on its lines; null when that is not what the body holds. + private static JsonDocument? Lines(string text) + { + var builder = new StringBuilder(text.Length + 16).Append('['); + var first = true; + foreach (var line in text.AsSpan().EnumerateLines()) + { + if (!line.IsWhiteSpace()) + { + if (!first) + { + builder.Append(','); + } + + builder.Append(line); + first = false; + } + + builder.Append('\n'); + } + + try + { + return JsonDocument.Parse(builder.Append(']').ToString(), DocumentOptions); + } + catch (JsonException) + { + return null; // one value written over several lines, say: read as a whole + } + } + + private static FilteredBody Write(IReadOnlyList nodes, bool indented, long maxBytes, CancellationToken cancellationToken) + { + var buffer = new ArrayBufferWriter(); + var shown = 0; + using (var writer = new Utf8JsonWriter(buffer, indented ? Indented : Compact)) + { + writer.WriteStartArray(); + foreach (var node in nodes) + { + if (shown > 0 && writer.BytesCommitted + writer.BytesPending > maxBytes) + { + break; + } + + node.WriteTo(writer); + if ((++shown & 255) == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + } + } + + writer.WriteEndArray(); + } + + return new FilteredBody(Encoding.UTF8.GetString(buffer.WrittenSpan), nodes.Count, shown); + } +} diff --git a/src/TermRest.Core/Http/BodyFormatter.cs b/src/TermRest.Core/Http/BodyFormatter.cs index 023c804..63fd18a 100644 --- a/src/TermRest.Core/Http/BodyFormatter.cs +++ b/src/TermRest.Core/Http/BodyFormatter.cs @@ -27,9 +27,13 @@ public static class BodyFormatter public static bool IsHtml(string? contentType) => SubtypeHasWord(contentType, "html", "xhtml"); - /// A short language label for the body (json, xml, html, text, binary). + /// A short language label for the body (json, xml, html, javascript, text, binary). public static string Language(byte[] body, string? contentType) => - IsJson(contentType) ? "json" : IsHtml(contentType) ? "html" : IsXml(contentType) ? "xml" : LooksLikeText(body, contentType) ? "text" : "binary"; + IsJson(contentType) ? "json" + : IsHtml(contentType) ? "html" + : IsXml(contentType) ? "xml" + : SubtypeHasWord(contentType, "javascript", "ecmascript") ? "javascript" + : LooksLikeText(body, contentType) ? "text" : "binary"; /// Whether a body is shown as text: its Content-Type declares text, or no NUL byte is near its start. public static bool LooksLikeText(byte[] body, string? contentType) => IsTextType(contentType) || !HasNulNearStart(body); diff --git a/src/TermRest.Core/Json/IRegexp.cs b/src/TermRest.Core/Json/IRegexp.cs new file mode 100644 index 0000000..523ac3c --- /dev/null +++ b/src/TermRest.Core/Json/IRegexp.cs @@ -0,0 +1,629 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; + +namespace TermRest.Core.Json; + +/// +/// Turns I-Regexp (RFC 9485), the regular expressions of JSONPath's match and search, into .NET ones that match code +/// points as I-Regexp does, not UTF-16 code units: "." and [^a] match an emoji whole, \p{L} matches 𝒜. +/// +internal static class IRegexp +{ + /// How long a regular expression may take on one string. + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(2); + + private static readonly ConcurrentDictionary<(string Category, bool Negated), List<(int Low, int High)>> SupplementaryCategories = new(); + + private const string Surrogates = @"\uD800-\uDFFF"; + + /// "." of I-Regexp: any code point but a line feed or a carriage return. + private const string Dot = @"(?:[^\n\r\uD800-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF])"; + + /// + /// A regular expression that matches what matches: the whole string (match) or a part of it + /// (search). Null when the pattern is not an I-Regexp, which then matches nothing. + /// + public static Regex? Create(string pattern, bool whole) + { + if (Translate(pattern) is not { } translated) + { + return null; + } + + var expression = whole ? $@"\A(?:{translated})\z" : translated; + try + { + // Matches in a time proportional to the string's length: a pattern taken from a response cannot hang a filter. + return new Regex(expression, RegexOptions.CultureInvariant | RegexOptions.NonBacktracking, Timeout); + } + catch (NotSupportedException) + { + try + { + return new Regex(expression, RegexOptions.CultureInvariant, Timeout); // too large for that engine: a{1000}{1000} + } + catch (ArgumentException) + { + return null; + } + } + catch (ArgumentException) + { + return null; // a count .NET cannot take: a{99999999999} + } + } + + public static bool IsMatch(Regex regex, string text) + { + try + { + return regex.IsMatch(text); + } + catch (RegexMatchTimeoutException) + { + throw new JsonPathException($"A regular expression takes more than {Timeout.TotalSeconds.ToString(CultureInfo.InvariantCulture)} seconds on a string of {text.Length.ToString(CultureInfo.InvariantCulture)} characters."); + } + } + + /// The .NET pattern for an I-Regexp; null when the text is not one. + internal static string? Translate(string pattern) => new Translator(pattern).Run(); + + private sealed class Translator(string pattern) + { + private const int MaxDepth = 64; + + private readonly StringBuilder _out = new(); + private int _pos; + private int _depth; + + public string? Run() + { + try + { + Regexp(); + return _pos == pattern.Length ? _out.ToString() : null; // a ) that closes nothing + } + catch (FormatException) + { + return null; + } + } + + // i-regexp = branch *( "|" branch ); branch = *piece; piece = atom [ quantifier ] + private void Regexp() + { + while (true) + { + while (_pos < pattern.Length && pattern[_pos] is not ('|' or ')')) + { + Atom(); + Quantifier(); + } + + if (!Take('|')) + { + return; + } + + _out.Append('|'); + } + } + + private void Atom() + { + switch (pattern[_pos]) + { + case '(': + _pos++; + if (++_depth > MaxDepth) + { + throw new FormatException(); + } + + _out.Append("(?:"); + Regexp(); + if (!Take(')')) + { + throw new FormatException(); + } + + _out.Append(')'); + _depth--; + break; + case '.': + _pos++; + _out.Append(Dot); + break; + case '[': + _pos++; + var negated = Take('^'); + var set = new CodePointSet(); + ClassItems(set); + Append(set, negated); + break; + case '\\' when Peek(1) is 'p' or 'P': + var category = new CodePointSet(); + Category(category); + Append(category, negated: false); + break; + case '\\': + AppendLiteral(SingleCharEscape()); + break; + + // Anchors, as ECMAScript (and the JSONPath compliance tests) take them. + case '^': + _pos++; + _out.Append(@"(?:\A)"); + break; + case '$': + _pos++; + _out.Append(@"(?:\z)"); + break; + case '*' or '+' or '?' or '{' or '}' or ']': + throw new FormatException(); + default: + AppendLiteral(CodePoint()); + break; + } + } + + // quantifier = "*" / "+" / "?" / "{" n [ "," [ m ] ] "}" + private void Quantifier() + { + if (_pos >= pattern.Length) + { + return; + } + + switch (pattern[_pos]) + { + case '*' or '+' or '?': + _out.Append(pattern[_pos++]); + break; + case '{': + var start = _pos++; + var min = Count() ?? throw new FormatException(); + var max = min; + if (Take(',')) + { + max = Count() ?? long.MaxValue; + } + + if (!Take('}') || max < min) + { + throw new FormatException(); + } + + _out.Append(pattern, start, _pos - start); + break; + } + } + + private long? Count() + { + var start = _pos; + long value = 0; + while (_pos < pattern.Length && char.IsAsciiDigit(pattern[_pos])) + { + value = Math.Min(value * 10 + (pattern[_pos++] - '0'), int.MaxValue); + } + + return _pos == start ? null : value; + } + + // charClassExpr = "[" [ "^" ] ( "-" / CCE1 ) *CCE1 [ "-" ] "]"; CCE1 = ( CCchar [ "-" CCchar ] ) / charClassEsc + private void ClassItems(CodePointSet set) + { + var first = true; + while (true) + { + if (_pos >= pattern.Length) + { + throw new FormatException(); + } + + var c = pattern[_pos]; + if (c == ']' && !first) + { + _pos++; + return; + } + + if (c == '-') + { + if (!first && Peek(1) != ']') + { + throw new FormatException(); // a - only comes first or last + } + + _pos++; + set.Ranges.Add(('-', '-')); + } + else if (c == '\\' && Peek(1) is 'p' or 'P') + { + Category(set); + } + else + { + var low = ClassChar(); + var high = low; + if (Peek(0) == '-' && Peek(1) is not (']' or -1)) + { + _pos++; + if (Peek(0) == '\\' && Peek(1) is 'p' or 'P') + { + throw new FormatException(); + } + + high = ClassChar(); + if (high < low) + { + throw new FormatException(); + } + } + + set.Ranges.Add((low, high)); + } + + first = false; + } + } + + // CCchar = ( %x00-2C / %x2E-5A / %x5E-D7FF / %xE000-10FFFF ) / SingleCharEsc + private int ClassChar() => pattern[_pos] switch + { + '\\' => SingleCharEscape(), + '-' or '[' or ']' => throw new FormatException(), + _ => CodePoint(), + }; + + // SingleCharEsc = "\" ( %x28-2B / "-" / "." / "?" / %x5B-5E / "n" / "r" / "t" / %x7B-7D ) + private int SingleCharEscape() + { + var c = Peek(1); + _pos += 2; + return c switch + { + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + '(' or ')' or '*' or '+' or '-' or '.' or '?' or '[' or '\\' or ']' or '^' or '{' or '|' or '}' => c, + _ => throw new FormatException(), + }; + } + + // catEsc = "\p{" charProp "}"; complEsc = "\P{" charProp "}" + private void Category(CodePointSet set) + { + var negated = pattern[_pos + 1] == 'P'; + _pos += 2; + if (!Take('{')) + { + throw new FormatException(); + } + + var end = pattern.IndexOf('}', _pos); + if (end < 0 || CategoryMembers(pattern[_pos..end]) is null) + { + throw new FormatException(); + } + + set.Categories.Add((pattern[_pos..end], negated)); + _pos = end + 1; + } + + private int CodePoint() + { + var c = pattern[_pos]; + if (char.IsHighSurrogate(c) && _pos + 1 < pattern.Length && char.IsLowSurrogate(pattern[_pos + 1])) + { + _pos += 2; + return char.ConvertToUtf32(c, pattern[_pos - 1]); + } + + if (char.IsSurrogate(c)) + { + throw new FormatException(); + } + + _pos++; + return c; + } + + private void AppendLiteral(int codePoint) + { + if (codePoint > 0xFFFF) + { + // A pair, grouped so that a quantifier repeats the character. + var text = char.ConvertFromUtf32(codePoint); + _out.Append("(?:"); + AppendUnit(_out, text[0]); + AppendUnit(_out, text[1]); + _out.Append(')'); + } + else + { + AppendUnit(_out, (char)codePoint); + } + } + + /// + /// A character class: its BMP part as a .NET class without surrogates, and its other code points as the surrogate + /// pairs that write them. + /// + private void Append(CodePointSet set, bool negated) + { + var bmp = new StringBuilder(); + var supplementary = new List<(int Low, int High)>(); + foreach (var (low, high) in set.Ranges) + { + if (low <= 0xFFFF) + { + AppendUnit(bmp, (char)low); + if (high > low) + { + bmp.Append('-'); + AppendUnit(bmp, (char)Math.Min(high, 0xFFFF)); + } + } + + if (high > 0xFFFF) + { + supplementary.Add((Math.Max(low, 0x10000), high)); + } + } + + foreach (var (name, categoryNegated) in set.Categories) + { + bmp.Append(categoryNegated ? @"\P{" : @"\p{").Append(name).Append('}'); + supplementary.AddRange(SupplementaryRanges(name, categoryNegated)); + } + + supplementary = Merge(supplementary); + var alternatives = new List(); + if (negated) + { + alternatives.Add($"[^{bmp}{Surrogates}]"); + alternatives.AddRange(Pairs(Complement(supplementary))); + } + else + { + if (bmp.Length > 0) + { + alternatives.Add($"[{bmp}-[{Surrogates}]]"); + } + + alternatives.AddRange(Pairs(supplementary)); + } + + _out.Append("(?:").AppendJoin('|', alternatives.Count > 0 ? alternatives : [@"[^\u0000-\uFFFF]"]).Append(')'); + } + + private int Peek(int offset) => _pos + offset < pattern.Length ? pattern[_pos + offset] : -1; + + private bool Take(char c) + { + if (Peek(0) != c) + { + return false; + } + + _pos++; + return true; + } + } + + private sealed class CodePointSet + { + public List<(int Low, int High)> Ranges { get; } = []; + + public List<(string Name, bool Negated)> Categories { get; } = []; + } + + private static void AppendUnit(StringBuilder builder, char c) + { + if (char.IsAsciiLetterOrDigit(c)) + { + builder.Append(c); + } + else + { + builder.Append(@"\u").Append(((int)c).ToString("X4", CultureInfo.InvariantCulture)); + } + } + + /// The general categories in an I-Regexp category name (Lu, or L for all letters); null for another name. + private static UnicodeCategory[]? CategoryMembers(string name) => name switch + { + "L" => [UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter], + "Lu" => [UnicodeCategory.UppercaseLetter], + "Ll" => [UnicodeCategory.LowercaseLetter], + "Lt" => [UnicodeCategory.TitlecaseLetter], + "Lm" => [UnicodeCategory.ModifierLetter], + "Lo" => [UnicodeCategory.OtherLetter], + "M" => [UnicodeCategory.NonSpacingMark, UnicodeCategory.SpacingCombiningMark, UnicodeCategory.EnclosingMark], + "Mn" => [UnicodeCategory.NonSpacingMark], + "Mc" => [UnicodeCategory.SpacingCombiningMark], + "Me" => [UnicodeCategory.EnclosingMark], + "N" => [UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber], + "Nd" => [UnicodeCategory.DecimalDigitNumber], + "Nl" => [UnicodeCategory.LetterNumber], + "No" => [UnicodeCategory.OtherNumber], + "P" => + [ + UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, + UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation, + ], + "Pc" => [UnicodeCategory.ConnectorPunctuation], + "Pd" => [UnicodeCategory.DashPunctuation], + "Ps" => [UnicodeCategory.OpenPunctuation], + "Pe" => [UnicodeCategory.ClosePunctuation], + "Pi" => [UnicodeCategory.InitialQuotePunctuation], + "Pf" => [UnicodeCategory.FinalQuotePunctuation], + "Po" => [UnicodeCategory.OtherPunctuation], + "Z" => [UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator], + "Zs" => [UnicodeCategory.SpaceSeparator], + "Zl" => [UnicodeCategory.LineSeparator], + "Zp" => [UnicodeCategory.ParagraphSeparator], + "S" => [UnicodeCategory.MathSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherSymbol], + "Sm" => [UnicodeCategory.MathSymbol], + "Sc" => [UnicodeCategory.CurrencySymbol], + "Sk" => [UnicodeCategory.ModifierSymbol], + "So" => [UnicodeCategory.OtherSymbol], + "C" => [UnicodeCategory.Control, UnicodeCategory.Format, UnicodeCategory.Surrogate, UnicodeCategory.PrivateUse, UnicodeCategory.OtherNotAssigned], + "Cc" => [UnicodeCategory.Control], + "Cf" => [UnicodeCategory.Format], + "Co" => [UnicodeCategory.PrivateUse], + "Cn" => [UnicodeCategory.OtherNotAssigned], + _ => null, + }; + + /// The code points from U+10000 on in a category (or out of it), worked out once per category. + private static List<(int Low, int High)> SupplementaryRanges(string category, bool negated) => + SupplementaryCategories.GetOrAdd((category, negated), static key => + { + var members = new bool[32]; + foreach (var member in CategoryMembers(key.Category)!) + { + members[(int)member] = true; + } + + var ranges = new List<(int Low, int High)>(); + var start = -1; + for (var codePoint = 0x10000; codePoint <= 0x110000; codePoint++) + { + var inSet = codePoint <= 0x10FFFF && members[(int)Rune.GetUnicodeCategory(new Rune(codePoint))] != key.Negated; + if (inSet && start < 0) + { + start = codePoint; + } + else if (!inSet && start >= 0) + { + ranges.Add((start, codePoint - 1)); + start = -1; + } + } + + return ranges; + }); + + private static List<(int Low, int High)> Merge(List<(int Low, int High)> ranges) + { + ranges.Sort(); + var merged = new List<(int Low, int High)>(); + foreach (var range in ranges) + { + if (merged.Count > 0 && range.Low <= merged[^1].High + 1) + { + merged[^1] = (merged[^1].Low, Math.Max(merged[^1].High, range.High)); + } + else + { + merged.Add(range); + } + } + + return merged; + } + + /// The code points from U+10000 to U+10FFFF outside the (merged) ranges. + private static List<(int Low, int High)> Complement(List<(int Low, int High)> ranges) + { + var complement = new List<(int Low, int High)>(); + var next = 0x10000; + foreach (var (low, high) in ranges) + { + if (low > next) + { + complement.Add((next, low - 1)); + } + + next = high + 1; + } + + if (next <= 0x10FFFF) + { + complement.Add((next, 0x10FFFF)); + } + + return complement; + } + + /// + /// The surrogate pairs that write code points of the (merged) ranges, grouped: for each run of high surrogates followed + /// by the same low surrogates, one alternative. + /// + private static List Pairs(List<(int Low, int High)> ranges) + { + var lows = new List<(int Low, int High)>?[0x400]; + foreach (var (low, high) in ranges) + { + for (var h = (low - 0x10000) >> 10; h <= (high - 0x10000) >> 10; h++) + { + var first = Math.Max(low, 0x10000 + (h << 10)); + var last = Math.Min(high, 0x10000 + (h << 10) + 0x3FF); + (lows[h] ??= []).Add((0xDC00 + ((first - 0x10000) & 0x3FF), 0xDC00 + ((last - 0x10000) & 0x3FF))); + } + } + + var alternatives = new List(); + for (var h = 0; h < lows.Length;) + { + if (lows[h] is not { } same) + { + h++; + continue; + } + + var end = h; + while (end + 1 < lows.Length && lows[end + 1] is { } next && next.SequenceEqual(same)) + { + end++; + } + + var builder = new StringBuilder(); + AppendRange(builder, 0xD800 + h, 0xD800 + end); + if (same.Count == 1) + { + AppendRange(builder, same[0].Low, same[0].High); + } + else + { + builder.Append('['); + foreach (var (low, high) in same) + { + AppendUnit(builder, (char)low); + if (high > low) + { + builder.Append('-'); + AppendUnit(builder, (char)high); + } + } + + builder.Append(']'); + } + + alternatives.Add(builder.ToString()); + h = end + 1; + } + + return alternatives; + } + + private static void AppendRange(StringBuilder builder, int low, int high) + { + if (low == high) + { + AppendUnit(builder, (char)low); + return; + } + + builder.Append('['); + AppendUnit(builder, (char)low); + builder.Append('-'); + AppendUnit(builder, (char)high); + builder.Append(']'); + } +} diff --git a/src/TermRest.Core/Json/JsonPath.cs b/src/TermRest.Core/Json/JsonPath.cs new file mode 100644 index 0000000..972b3d0 --- /dev/null +++ b/src/TermRest.Core/Json/JsonPath.cs @@ -0,0 +1,43 @@ +using System.Text.Json; + +namespace TermRest.Core.Json; + +/// +/// A JSONPath query (RFC 9535), such as $.store.book[?@.price < 10].title: selects values of a JSON document. +/// Its functions are the RFC's: length, count, value, and match and search, which take an I-Regexp (RFC 9485). +/// +public sealed class JsonPath +{ + /// The most values one step of a query may select: $..*..* on a large document fails rather than fill the memory. + internal const int MaxNodes = 1 << 22; + + private readonly PathQuery _query; + + private JsonPath(string text, PathQuery query) + { + Text = text; + _query = query; + } + + /// The query as written. + public string Text { get; } + + /// Parses a query; a says where it is not valid JSONPath. + public static JsonPath Parse(string text) => new(text, JsonPathParser.Parse(text)); + + /// + /// The values the query selects in , in document order. A when a + /// step selects too many values, or a regular expression takes too long. + /// + public IReadOnlyList Select(JsonElement root, CancellationToken cancellationToken = default) => + _query.Select(root, new PathEvaluation(root, cancellationToken)); + + public override string ToString() => Text; +} + +/// A query that is not valid JSONPath ( says where), or that could not be applied. +public sealed class JsonPathException(string message, int position = -1) : FormatException(message) +{ + /// Where in the query the problem is (from 0), or -1. + public int Position { get; } = position; +} diff --git a/src/TermRest.Core/Json/JsonPathEvaluation.cs b/src/TermRest.Core/Json/JsonPathEvaluation.cs new file mode 100644 index 0000000..421268b --- /dev/null +++ b/src/TermRest.Core/Json/JsonPathEvaluation.cs @@ -0,0 +1,838 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace TermRest.Core.Json; + +/// A query: from the root ($) or from the current value of a filter (@), then its segments. +internal sealed class PathQuery(bool absolute, Segment[] segments) +{ + /// Whether it selects at most one value: one name or index per segment, and no descendants. + public bool IsSingular { get; } = Array.TrueForAll(segments, s => s is ChildSegment { Selectors: [NameSelector or IndexSelector] }); + + public List Select(JsonElement current, PathEvaluation evaluation) + { + if (absolute && evaluation.Cached(this) is { } cached) + { + return cached; // the same for every value a filter tests + } + + List nodes = [absolute ? evaluation.Root : current]; + foreach (var segment in segments) + { + var next = new List(); + foreach (var node in nodes) + { + segment.Apply(node, next, evaluation); + } + + nodes = next; + if (nodes.Count == 0) + { + break; + } + } + + if (absolute) + { + evaluation.Cache(this, nodes); + } + + return nodes; + } + + /// The value a singular query selects, if any. + public bool TrySelectOne(JsonElement current, PathEvaluation evaluation, out JsonElement value) + { + if (absolute) + { + // Worked out once per filter, not once per value tested: $[-1] reads the whole array before its last element. + var nodes = Select(current, evaluation); + value = nodes.Count > 0 ? nodes[0] : default; + return nodes.Count > 0; + } + + value = current; + foreach (var segment in segments) + { + if (!segment.Selectors[0].TrySelectOne(value, out value)) + { + return false; + } + } + + return true; + } + + public bool SelectsAny(JsonElement current, PathEvaluation evaluation) => + IsSingular ? TrySelectOne(current, evaluation, out _) : Select(current, evaluation).Count > 0; +} + +internal abstract class Segment(Selector[] selectors) +{ + public Selector[] Selectors { get; } = selectors; + + public abstract void Apply(JsonElement node, List output, PathEvaluation evaluation); +} + +/// [selectors], .name or .*: what the selectors select among the children of a value. +internal sealed class ChildSegment(Selector[] selectors) : Segment(selectors) +{ + public override void Apply(JsonElement node, List output, PathEvaluation evaluation) + { + foreach (var selector in Selectors) + { + selector.Select(node, output, evaluation); + } + } +} + +/// ..[selectors], ..name or ..*: the same for a value and each of its descendants, each before its children. +internal sealed class DescendantSegment(Selector[] selectors) : Segment(selectors) +{ + public override void Apply(JsonElement node, List output, PathEvaluation evaluation) + { + RuntimeHelpers.EnsureSufficientExecutionStack(); + foreach (var selector in Selectors) + { + selector.Select(node, output, evaluation); + } + + evaluation.Step(); + if (node.ValueKind == JsonValueKind.Array) + { + foreach (var item in node.EnumerateArray()) + { + Apply(item, output, evaluation); + } + } + else if (node.ValueKind == JsonValueKind.Object) + { + foreach (var property in node.EnumerateObject()) + { + Apply(property.Value, output, evaluation); + } + } + } +} + +internal abstract class Selector +{ + public abstract void Select(JsonElement node, List output, PathEvaluation evaluation); + + /// For the selectors a singular query is made of (a name, an index): the value selected, if any. + public virtual bool TrySelectOne(JsonElement node, out JsonElement value) => throw new NotSupportedException(); +} + +internal sealed class NameSelector(string name) : Selector +{ + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (TrySelectOne(node, out var value)) + { + evaluation.Add(output, value); + } + } + + public override bool TrySelectOne(JsonElement node, out JsonElement value) + { + value = default; + return node.ValueKind == JsonValueKind.Object && node.TryGetProperty(name, out value); + } +} + +internal sealed class WildcardSelector : Selector +{ + public static readonly WildcardSelector Instance = new(); + + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (node.ValueKind == JsonValueKind.Array) + { + foreach (var item in node.EnumerateArray()) + { + evaluation.Add(output, item); + } + } + else if (node.ValueKind == JsonValueKind.Object) + { + foreach (var property in node.EnumerateObject()) + { + evaluation.Add(output, property.Value); + } + } + } +} + +internal sealed class IndexSelector(long index) : Selector +{ + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (TrySelectOne(node, out var value)) + { + evaluation.Add(output, value); + } + } + + public override bool TrySelectOne(JsonElement node, out JsonElement value) + { + if (node.ValueKind == JsonValueKind.Array) + { + var length = node.GetArrayLength(); + var i = index >= 0 ? index : length + index; + if (i >= 0 && i < length) + { + value = node[(int)i]; + return true; + } + } + + value = default; + return false; + } +} + +/// [start:end:step], with the bounds of RFC 9535: negative ones count from the end, and a negative step goes backwards. +internal sealed class SliceSelector(long? start, long? end, long step) : Selector +{ + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (node.ValueKind != JsonValueKind.Array || step == 0) + { + return; + } + + // The elements are enumerated, not indexed: finding an element of an array of objects by index reads all before it. + long length = node.GetArrayLength(); + if (step > 0) + { + var lower = Math.Clamp(Normalize(start ?? 0, length), 0, length); + var upper = Math.Clamp(Normalize(end ?? length, length), 0, length); + long i = 0; + var next = lower; + foreach (var item in node.EnumerateArray()) + { + if (i >= upper) + { + break; + } + + if (i == next) + { + evaluation.Add(output, item); + next += step; + } + + i++; + } + } + else + { + var upper = Math.Clamp(Normalize(start ?? length - 1, length), -1, length - 1); + var lower = Math.Clamp(Normalize(end ?? -length - 1, length), -1, length - 1); + if (upper <= lower) + { + return; + } + + var items = new JsonElement[upper + 1]; + var count = 0; + foreach (var item in node.EnumerateArray()) + { + if (count > upper) + { + break; + } + + items[count++] = item; + } + + for (var i = upper; i > lower; i += step) + { + evaluation.Add(output, items[i]); + } + } + } + + private static long Normalize(long index, long length) => index >= 0 ? index : length + index; +} + +/// [?test]: the children of a value for which the test is true. +internal sealed class FilterSelector(LogicalExpression condition) : Selector +{ + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (node.ValueKind == JsonValueKind.Array) + { + foreach (var item in node.EnumerateArray()) + { + evaluation.Step(); + if (condition.Test(item, evaluation)) + { + evaluation.Add(output, item); + } + } + } + else if (node.ValueKind == JsonValueKind.Object) + { + foreach (var property in node.EnumerateObject()) + { + evaluation.Step(); + if (condition.Test(property.Value, evaluation)) + { + evaluation.Add(output, property.Value); + } + } + } + } +} + +internal abstract class LogicalExpression +{ + public abstract bool Test(JsonElement current, PathEvaluation evaluation); +} + +internal sealed class OrExpression(LogicalExpression left, LogicalExpression right) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => left.Test(current, evaluation) || right.Test(current, evaluation); +} + +internal sealed class AndExpression(LogicalExpression left, LogicalExpression right) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => left.Test(current, evaluation) && right.Test(current, evaluation); +} + +internal sealed class NotExpression(LogicalExpression inner) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => !inner.Test(current, evaluation); +} + +/// A query as a test: whether it selects anything (a value that is false or null too). +internal sealed class ExistsExpression(PathQuery query) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => query.SelectsAny(current, evaluation); +} + +internal sealed class FunctionTestExpression(FunctionCall call) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => call.Test(current, evaluation); +} + +/// The comparison operators, in the order the parser tries them. +internal enum ComparisonOperator +{ + Equal, + NotEqual, + LessOrEqual, + GreaterOrEqual, + Less, + Greater, +} + +internal sealed class ComparisonExpression(ValueExpression left, ComparisonOperator op, ValueExpression right) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) + { + var a = left.Evaluate(current, evaluation); + var b = right.Evaluate(current, evaluation); + return op switch + { + ComparisonOperator.Equal => PathValue.AreEqual(a, b), + ComparisonOperator.NotEqual => !PathValue.AreEqual(a, b), + ComparisonOperator.Less => PathValue.IsLess(a, b), + ComparisonOperator.LessOrEqual => PathValue.IsLess(a, b) || PathValue.AreEqual(a, b), + ComparisonOperator.Greater => PathValue.IsLess(b, a), + _ => PathValue.IsLess(b, a) || PathValue.AreEqual(a, b), + }; + } +} + +internal abstract class ValueExpression +{ + public abstract PathValue Evaluate(JsonElement current, PathEvaluation evaluation); +} + +internal sealed class LiteralExpression(PathValue value) : ValueExpression +{ + public PathValue Value { get; } = value; + + public override PathValue Evaluate(JsonElement current, PathEvaluation evaluation) => Value; +} + +/// A singular query as a value: the value it selects, or nothing. +internal sealed class QueryValueExpression(PathQuery query) : ValueExpression +{ + public override PathValue Evaluate(JsonElement current, PathEvaluation evaluation) => + query.TrySelectOne(current, evaluation, out var value) ? PathValue.Of(value) : default; +} + +internal sealed class FunctionValueExpression(FunctionCall call) : ValueExpression +{ + public override PathValue Evaluate(JsonElement current, PathEvaluation evaluation) => call.Evaluate(current, evaluation); +} + +/// The types of RFC 9535 function parameters and results. +internal enum PathType +{ + Value, + Logical, + Nodes, +} + +internal enum PathFunction +{ + Length, + Count, + Match, + Search, + Value, +} + +internal sealed class FunctionCall +{ + private readonly PathFunction _function; + private readonly object[] _arguments; + private readonly bool _literalPattern; + private readonly Regex? _regex; + + public FunctionCall(string name, PathFunction function, PathType result, object[] arguments) + { + Name = name; + Result = result; + _function = function; + _arguments = arguments; + if (function is PathFunction.Match or PathFunction.Search && arguments[1] is LiteralExpression literal) + { + // Written in the query: translated once, not for each value tested. + _literalPattern = true; + _regex = literal.Value.Kind == JsonValueKind.String ? IRegexp.Create(literal.Value.GetString(), whole: function == PathFunction.Match) : null; + } + } + + public string Name { get; } + + public PathType Result { get; } + + public static (PathFunction Function, PathType[] Parameters, PathType Result)? Find(string name) => name switch + { + "length" => (PathFunction.Length, [PathType.Value], PathType.Value), + "count" => (PathFunction.Count, [PathType.Nodes], PathType.Value), + "match" => (PathFunction.Match, [PathType.Value, PathType.Value], PathType.Logical), + "search" => (PathFunction.Search, [PathType.Value, PathType.Value], PathType.Logical), + "value" => (PathFunction.Value, [PathType.Nodes], PathType.Value), + _ => null, + }; + + /// length, count or value. + public PathValue Evaluate(JsonElement current, PathEvaluation evaluation) + { + switch (_function) + { + case PathFunction.Length: + var value = ((ValueExpression)_arguments[0]).Evaluate(current, evaluation); + return value.Kind switch + { + JsonValueKind.String => PathValue.Of(CodePoints(value.GetString())), + JsonValueKind.Array => PathValue.Of(value.Element.GetArrayLength()), + JsonValueKind.Object => PathValue.Of(value.Element.GetPropertyCount()), + _ => default, + }; + case PathFunction.Count: + return PathValue.Of(((PathQuery)_arguments[0]).Select(current, evaluation).Count); + default: + var nodes = ((PathQuery)_arguments[0]).Select(current, evaluation); + return nodes.Count == 1 ? PathValue.Of(nodes[0]) : default; + } + } + + /// match (the whole string) or search (a part of it). + public bool Test(JsonElement current, PathEvaluation evaluation) + { + var subject = ((ValueExpression)_arguments[0]).Evaluate(current, evaluation); + if (subject.Kind != JsonValueKind.String) + { + return false; + } + + Regex? regex; + if (_literalPattern) + { + regex = _regex; + } + else + { + var pattern = ((ValueExpression)_arguments[1]).Evaluate(current, evaluation); + if (pattern.Kind != JsonValueKind.String) + { + return false; + } + + regex = evaluation.Regex(pattern.GetString(), whole: _function == PathFunction.Match); + } + + return regex is not null && IRegexp.IsMatch(regex, subject.GetString()); + } + + /// The length of a string in characters (code points): an emoji is one. + private static int CodePoints(string text) + { + var count = text.Length; + for (var i = 1; i < text.Length; i++) + { + if (char.IsLowSurrogate(text[i]) && char.IsHighSurrogate(text[i - 1])) + { + count--; + } + } + + return count; + } +} + +/// One application of a query: the document, what is worth keeping while it runs, and its cancellation. +internal sealed class PathEvaluation(JsonElement root, CancellationToken cancellationToken) +{ + private const int MaxCachedRegexes = 100; + + private int _steps; + private Dictionary>? _absolute; + private Dictionary<(string Pattern, bool Whole), Regex?>? _regexes; + + public JsonElement Root { get; } = root; + + public void Step() + { + if ((++_steps & 1023) == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + } + } + + public void Add(List nodes, JsonElement node) + { + if (nodes.Count >= JsonPath.MaxNodes) + { + throw new JsonPathException($"The query selects more than {JsonPath.MaxNodes.ToString("N0", CultureInfo.InvariantCulture)} values in one step."); + } + + nodes.Add(node); + Step(); + } + + public List? Cached(PathQuery query) => _absolute?.GetValueOrDefault(query); + + public void Cache(PathQuery query, List nodes) => (_absolute ??= [])[query] = nodes; + + /// A pattern taken from the document: translated once per distinct pattern. + public Regex? Regex(string pattern, bool whole) + { + _regexes ??= []; + if (!_regexes.TryGetValue((pattern, whole), out var regex)) + { + regex = IRegexp.Create(pattern, whole); + if (_regexes.Count < MaxCachedRegexes) + { + _regexes[(pattern, whole)] = regex; + } + } + + return regex; + } +} + +/// A value in a filter: a value of the document, a literal, a number a function computed, or nothing. +internal readonly struct PathValue +{ + private readonly JsonElement _element; + private readonly string? _text; + private readonly long _integer; + private readonly Source _source; + + private PathValue(Source source, JsonElement element, string? text, long integer) + { + _source = source; + _element = element; + _text = text; + _integer = integer; + } + + private enum Source : byte + { + Nothing, + Element, + Integer, + Text, + } + + /// The kind of value; for nothing (a query that selects no value). + public JsonValueKind Kind => _source switch + { + Source.Element => _element.ValueKind, + Source.Integer => JsonValueKind.Number, + Source.Text => JsonValueKind.String, + _ => JsonValueKind.Undefined, + }; + + public JsonElement Element => _element; + + public static PathValue Of(JsonElement element) => new(Source.Element, element, null, 0); + + public static PathValue Of(long integer) => new(Source.Integer, default, null, integer); + + public static PathValue Of(string text) => new(Source.Text, default, text, 0); + + public string GetString() => _text ?? _element.GetString()!; + + /// ==: nothing equals only nothing; numbers by value (1 == 1.0); arrays and objects by their contents. + public static bool AreEqual(in PathValue a, in PathValue b) + { + var kind = a.Kind; + if (kind != b.Kind) + { + return false; + } + + return kind switch + { + JsonValueKind.Number => CompareNumbers(a, b) == 0, + JsonValueKind.String => a._text is not null ? (b._text is not null ? a._text == b._text : b._element.ValueEquals(a._text)) + : b._text is not null ? a._element.ValueEquals(b._text) : StringsEqual(a._element, b._element), + JsonValueKind.Array or JsonValueKind.Object => DeepEquals(a._element, b._element), + _ => true, // true, false, null; and nothing + }; + } + + /// <: numbers by value, strings by code point; false for anything else. + public static bool IsLess(in PathValue a, in PathValue b) + { + var kind = a.Kind; + if (kind != b.Kind) + { + return false; + } + + return kind switch + { + JsonValueKind.Number => CompareNumbers(a, b) < 0, + JsonValueKind.String => CompareCodePoints(a.GetString(), b.GetString()) < 0, + _ => false, + }; + } + + /// + /// Compares strings by code point, as RFC 9535 requires: UTF-16 order puts U+E000 to U+FFFF after the surrogate pairs + /// that write U+10000 and above. + /// + internal static int CompareCodePoints(string a, string b) + { + var length = Math.Min(a.Length, b.Length); + for (var i = 0; i < length; i++) + { + if (a[i] != b[i]) + { + return Order(a[i]) - Order(b[i]); + } + } + + return a.Length - b.Length; + + static int Order(char c) => c < 0xD800 ? c : c >= 0xE000 ? c - 0x800 : c + 0x2000; + } + + private static int CompareNumbers(in PathValue a, in PathValue b) + { + if (a._source == Source.Integer && b._source == Source.Integer) + { + return a._integer.CompareTo(b._integer); + } + + Span x = stackalloc byte[20]; + Span y = stackalloc byte[20]; + return JsonNumbers.Compare(a.RawNumber(x), b.RawNumber(y)); + } + + private ReadOnlySpan RawNumber(Span buffer) + { + if (_source != Source.Integer) + { + return JsonMarshal.GetRawUtf8Value(_element); + } + + _integer.TryFormat(buffer, out var written, default, CultureInfo.InvariantCulture); + return buffer[..written]; + } + + private static bool StringsEqual(JsonElement a, JsonElement b) + { + // Equal strings written without escapes are the same bytes. + var x = JsonMarshal.GetRawUtf8Value(a); + var y = JsonMarshal.GetRawUtf8Value(b); + return x.Contains((byte)'\\') || y.Contains((byte)'\\') ? a.GetString() == b.GetString() : x.SequenceEqual(y); + } + + private static bool DeepEquals(JsonElement a, JsonElement b) + { + RuntimeHelpers.EnsureSufficientExecutionStack(); + if (a.ValueKind != b.ValueKind) + { + return false; + } + + switch (a.ValueKind) + { + case JsonValueKind.Number: + return JsonNumbers.Compare(JsonMarshal.GetRawUtf8Value(a), JsonMarshal.GetRawUtf8Value(b)) == 0; + case JsonValueKind.String: + return StringsEqual(a, b); + case JsonValueKind.Array: + if (a.GetArrayLength() != b.GetArrayLength()) + { + return false; + } + + var left = a.EnumerateArray(); + var right = b.EnumerateArray(); + while (left.MoveNext() && right.MoveNext()) + { + if (!DeepEquals(left.Current, right.Current)) + { + return false; + } + } + + return true; + case JsonValueKind.Object: + if (a.GetPropertyCount() != b.GetPropertyCount()) + { + return false; + } + + foreach (var property in a.EnumerateObject()) + { + if (!b.TryGetProperty(property.Name, out var other) || !DeepEquals(property.Value, other)) + { + return false; + } + } + + return true; + default: + return true; + } + } +} + +/// Exact comparison of JSON numbers as written: 1, 1.0 and 1e0 are equal; 9007199254740993 is not 9007199254740992. +internal static class JsonNumbers +{ + /// Exponents beyond this (in absolute value) are taken as this: no JSON number is that far from 1 in practice. + private const long MaxExponent = 1_000_000_000_000_000; + + public static int Compare(ReadOnlySpan x, ReadOnlySpan y) + { + var a = new Parts(x); + var b = new Parts(y); + if (a.Sign != b.Sign) + { + return a.Sign.CompareTo(b.Sign); + } + + if (a.Sign == 0) + { + return 0; + } + + var magnitude = a.Exponent != b.Exponent ? a.Exponent.CompareTo(b.Exponent) : CompareDigits(a, b); + return a.Sign > 0 ? magnitude : -magnitude; + } + + private static int CompareDigits(in Parts a, in Parts b) + { + var count = Math.Min(a.Count, b.Count); + for (var i = 0; i < count; i++) + { + var difference = a.Digit(i) - b.Digit(i); + if (difference != 0) + { + return difference; + } + } + + return a.Count.CompareTo(b.Count); + } + + /// A number as 0.d1d2…dn × 10^Exponent, its digits without leading or trailing zeros. + private readonly ref struct Parts + { + private readonly ReadOnlySpan _integer; + private readonly ReadOnlySpan _fraction; + private readonly int _first; + + public Parts(ReadOnlySpan text) + { + var negative = text.Length > 0 && text[0] == '-'; + if (negative) + { + text = text[1..]; + } + + var e = text.IndexOfAny((byte)'e', (byte)'E'); + var mantissa = e < 0 ? text : text[..e]; + var dot = mantissa.IndexOf((byte)'.'); + _integer = dot < 0 ? mantissa : mantissa[..dot]; + _fraction = dot < 0 ? default : mantissa[(dot + 1)..]; + + var total = _integer.Length + _fraction.Length; + var first = 0; + while (first < total && At(_integer, _fraction, first) == '0') + { + first++; + } + + _first = first; + if (first == total) + { + return; // zero, either sign + } + + var last = total - 1; + while (At(_integer, _fraction, last) == '0') + { + last--; + } + + Count = last - first + 1; + Sign = negative ? -1 : 1; + Exponent = _integer.Length - first + (e < 0 ? 0 : ParseExponent(text[(e + 1)..])); + } + + public int Sign { get; } + + public int Count { get; } + + public long Exponent { get; } + + public int Digit(int i) => At(_integer, _fraction, _first + i); + + private static int At(ReadOnlySpan integer, ReadOnlySpan fraction, int i) => i < integer.Length ? integer[i] : fraction[i - integer.Length]; + + private static long ParseExponent(ReadOnlySpan text) + { + var negative = text[0] == '-'; + if (text[0] is (byte)'-' or (byte)'+') + { + text = text[1..]; + } + + long value = 0; + foreach (var digit in text) + { + value = Math.Min(value * 10 + (digit - '0'), MaxExponent); + } + + return negative ? -value : value; + } + } +} diff --git a/src/TermRest.Core/Json/JsonPathParser.cs b/src/TermRest.Core/Json/JsonPathParser.cs new file mode 100644 index 0000000..3989783 --- /dev/null +++ b/src/TermRest.Core/Json/JsonPathParser.cs @@ -0,0 +1,669 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace TermRest.Core.Json; + +/// Parses JSONPath (RFC 9535), checking that function calls are well-typed as the RFC requires. +internal sealed class JsonPathParser +{ + /// How deep filters, parentheses and function calls may nest: deeper ones would only run out of stack. + private const int MaxNesting = 64; + + /// The largest index, 2^53 - 1: I-JSON numbers are exact up to it. + private const long MaxIndex = 9_007_199_254_740_991; + + private static readonly string[] ComparisonOperators = ["==", "!=", "<=", ">=", "<", ">"]; + + private readonly string _text; + private int _pos; + private int _nesting; + + private JsonPathParser(string text) => _text = text; + + private enum OperandKind + { + Literal, + Query, + Function, + Logical, + } + + public static PathQuery Parse(string text) + { + var parser = new JsonPathParser(text); + if (!parser.Peek('$')) + { + throw parser.Error(text.Length == 0 ? "The query is empty: a query starts with $" : "A query starts with $ (the whole document)"); + } + + parser._pos++; + var query = parser.Segments(absolute: true); + if (parser._pos < text.Length) + { + throw parser.Unexpected("a segment such as .name, [0] or ..name"); + } + + return query; + } + + // ----- segments and selectors --------------------------------------------------------- + + private PathQuery Segments(bool absolute) + { + var segments = new List(); + while (true) + { + var start = _pos; + SkipBlanks(); + if (Peek('.') && Peek('.', 1)) + { + _pos += 2; + segments.Add(new DescendantSegment(Peek('[') ? Bracketed() : [DotSelector(descendant: true)])); + } + else if (Take('.')) + { + segments.Add(new ChildSegment([DotSelector(descendant: false)])); + } + else if (Peek('[')) + { + segments.Add(new ChildSegment(Bracketed())); + } + else + { + _pos = start; // blanks after a query belong to what follows it + return new PathQuery(absolute, [.. segments]); + } + } + } + + private Selector DotSelector(bool descendant) + { + if (Take('*')) + { + return WildcardSelector.Instance; + } + + var start = _pos; + if (!TakeNameChar(first: true)) + { + throw Unexpected(descendant ? "a name, * or [ after .." : "a name or * after ."); + } + + while (TakeNameChar(first: false)) + { + } + + return new NameSelector(_text[start.._pos]); + } + + /// A character of a name after a dot: a letter, _, a digit (not first) or any non-ASCII character. + private bool TakeNameChar(bool first) + { + if (_pos >= _text.Length) + { + return false; + } + + var c = _text[_pos]; + if (char.IsAsciiLetter(c) || c == '_' || (!first && char.IsAsciiDigit(c)) || (c >= 0x80 && !char.IsSurrogate(c))) + { + _pos++; + return true; + } + + if (char.IsHighSurrogate(c) && _pos + 1 < _text.Length && char.IsLowSurrogate(_text[_pos + 1])) + { + _pos += 2; + return true; + } + + return false; + } + + private Selector[] Bracketed() + { + _pos++; + var selectors = new List(); + while (true) + { + SkipBlanks(); + selectors.Add(Selector()); + SkipBlanks(); + if (Take(']')) + { + return [.. selectors]; + } + + if (!Take(',')) + { + throw Unexpected("',' or ']'"); + } + } + } + + private Selector Selector() + { + if (Take('*')) + { + return WildcardSelector.Instance; + } + + if (Peek('\'') || Peek('"')) + { + return new NameSelector(StringLiteral()); + } + + if (Take('?')) + { + Enter(); + SkipBlanks(); + var condition = Test(Or()); + Leave(); + return new FilterSelector(condition); + } + + var start = Integer(); + if (start is not null) + { + var end = _pos; + SkipBlanks(); + if (!Peek(':')) + { + _pos = end; + return new IndexSelector(start.Value); + } + } + else if (!Peek(':')) + { + throw Unexpected("a selector: 'name', *, an index, a slice (start:end:step) or a filter (?…)"); + } + + _pos++; + SkipBlanks(); + var stop = Integer(); + SkipBlanks(); + long step = 1; + if (Take(':')) + { + var beforeStep = _pos; + SkipBlanks(); + if (Integer() is { } value) + { + step = value; + } + else + { + _pos = beforeStep; + } + } + + return new SliceSelector(start, stop, step); + } + + /// An index or a slice bound: 0, or digits that do not start with 0, perhaps after a -. Null when none starts here. + private long? Integer() + { + var start = _pos; + var negative = Take('-'); + var digits = _pos; + while (_pos < _text.Length && char.IsAsciiDigit(_text[_pos])) + { + _pos++; + } + + if (_pos == digits) + { + if (negative) + { + throw Error("Expected a digit after -", digits); + } + + return null; + } + + var span = _text.AsSpan(digits, _pos - digits); + if (span[0] == '0' && (span.Length > 1 || negative)) + { + throw Error("An index does not start with 0, and is not -0", start); + } + + var value = span.Length > 16 ? long.MaxValue : long.Parse(span, NumberStyles.None, CultureInfo.InvariantCulture); + if (value > MaxIndex) + { + throw Error("The index is out of range: at most 9007199254740991, either way", start); + } + + return negative ? -value : value; + } + + private string StringLiteral() + { + var quote = _text[_pos]; + var start = _pos++; + var builder = new StringBuilder(); + while (true) + { + if (_pos >= _text.Length) + { + throw Error("The string has no closing quote", start); + } + + var c = _text[_pos]; + if (c == quote) + { + _pos++; + return builder.ToString(); + } + + if (c == '\\') + { + Escape(builder, quote, start); + } + else if (c < 0x20) + { + throw Error($"A string cannot hold {Describe(_pos)}: write it as an escape (\\n, \\t, \\u0001 …)"); + } + else if (char.IsHighSurrogate(c) && _pos + 1 < _text.Length && char.IsLowSurrogate(_text[_pos + 1])) + { + builder.Append(c).Append(_text[_pos + 1]); + _pos += 2; + } + else if (char.IsSurrogate(c)) + { + throw Error("A string cannot hold half of a character (a lone surrogate)"); + } + else + { + builder.Append(c); + _pos++; + } + } + } + + private void Escape(StringBuilder builder, char quote, int stringStart) + { + var at = _pos++; + if (_pos >= _text.Length) + { + throw Error("The string has no closing quote", stringStart); + } + + var c = _text[_pos++]; + switch (c) + { + case 'b': builder.Append('\b'); break; + case 'f': builder.Append('\f'); break; + case 'n': builder.Append('\n'); break; + case 'r': builder.Append('\r'); break; + case 't': builder.Append('\t'); break; + case '/': builder.Append('/'); break; + case '\\': builder.Append('\\'); break; + case 'u': + var unit = Hex4(at); + if (char.IsHighSurrogate(unit)) + { + if (!(Peek('\\') && Peek('u', 1))) + { + throw Error("\\u" + ((int)unit).ToString("X4", CultureInfo.InvariantCulture) + " is half of a character: the other half (\\uDC00 to \\uDFFF) must follow it", at); + } + + var lowAt = _pos; + _pos += 2; + var low = Hex4(lowAt); + if (!char.IsLowSurrogate(low)) + { + throw Error("\\u" + ((int)unit).ToString("X4", CultureInfo.InvariantCulture) + " is half of a character: the other half (\\uDC00 to \\uDFFF) must follow it", at); + } + + builder.Append(unit).Append(low); + } + else if (char.IsLowSurrogate(unit)) + { + throw Error("\\u" + ((int)unit).ToString("X4", CultureInfo.InvariantCulture) + " is the second half of a character, without the first", at); + } + else + { + builder.Append(unit); + } + + break; + default: + if (c != quote) + { + throw Error($"\\{c} is not an escape: write \\{quote}, \\\\, \\/, \\b, \\f, \\n, \\r, \\t or \\uXXXX", at); + } + + builder.Append(c); + break; + } + } + + /// The four hexadecimal digits of a \u escape (the position is after the u). + private char Hex4(int escapeStart) + { + if (_pos + 4 > _text.Length || !int.TryParse(_text.AsSpan(_pos, 4), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var value)) + { + throw Error("\\u takes four hexadecimal digits", escapeStart); + } + + _pos += 4; + return (char)value; + } + + // ----- filter expressions ------------------------------------------------------------- + + private Operand Or() + { + var left = And(); + while (TakeOperator("||")) + { + var right = And(); + left = new Operand(OperandKind.Logical, new OrExpression(Test(left), Test(right)), left.Position); + } + + return left; + } + + private Operand And() + { + var left = Basic(); + while (TakeOperator("&&")) + { + var right = Basic(); + left = new Operand(OperandKind.Logical, new AndExpression(Test(left), Test(right)), left.Position); + } + + return left; + } + + private Operand Basic() + { + var start = _pos; + if (Take('!')) + { + SkipBlanks(); + var negated = Peek('(') ? Parenthesized() : Comparable(); + return new Operand(OperandKind.Logical, new NotExpression(Test(negated)), start); + } + + if (Peek('(')) + { + return Parenthesized(); + } + + var left = Comparable(); + var end = _pos; + SkipBlanks(); + if (ComparisonOperator() is { } op) + { + SkipBlanks(); + var right = Comparable(); + return new Operand(OperandKind.Logical, new ComparisonExpression(Value(left), op, Value(right)), start); + } + + if (Peek('=') && !Peek('=', 1)) + { + throw Error("Compare with == (a single = is not an operator)"); + } + + _pos = end; + return left; + } + + private Operand Parenthesized() + { + var start = _pos++; + Enter(); + SkipBlanks(); + var inner = Or(); + SkipBlanks(); + if (!Take(')')) + { + throw Unexpected("')'"); + } + + Leave(); + return new Operand(OperandKind.Logical, Test(inner), start); + } + + private ComparisonOperator? ComparisonOperator() + { + for (var i = 0; i < ComparisonOperators.Length; i++) + { + if (_text.AsSpan(_pos).StartsWith(ComparisonOperators[i], StringComparison.Ordinal)) + { + _pos += ComparisonOperators[i].Length; + return (ComparisonOperator)i; + } + } + + return null; + } + + /// A literal, a query or a function call. + private Operand Comparable() + { + var start = _pos; + var c = _pos < _text.Length ? _text[_pos] : '\0'; + switch (c) + { + case '@' or '$': + _pos++; + return new Operand(OperandKind.Query, Segments(absolute: c == '$'), start); + case '\'' or '"': + return new Operand(OperandKind.Literal, new LiteralExpression(PathValue.Of(StringLiteral())), start); + case '-' or (>= '0' and <= '9'): + return new Operand(OperandKind.Literal, NumberLiteral(), start); + case >= 'a' and <= 'z': + while (_pos < _text.Length && (char.IsAsciiLetterLower(_text[_pos]) || char.IsAsciiDigit(_text[_pos]) || _text[_pos] == '_')) + { + _pos++; + } + + var name = _text[start.._pos]; + if (Peek('(')) + { + return new Operand(OperandKind.Function, Function(name, start), start); + } + + return name is "true" or "false" or "null" + ? new Operand(OperandKind.Literal, new LiteralExpression(PathValue.Of(JsonElement.Parse(name))), start) + : throw Error($"Unknown name {name}: call a function as {name}(…), and quote a string", start); + default: + throw Unexpected("a value, a query (@… or $…) or a function"); + } + } + + /// A number as JSON writes it: -0, 1, 1.5, 1e-3; not 01, 1. or .5. + private LiteralExpression NumberLiteral() + { + var start = _pos; + Take('-'); + if (!Take('0')) + { + if (!(_pos < _text.Length && _text[_pos] is >= '1' and <= '9')) + { + throw Error("Expected a digit"); + } + + SkipDigits(); + } + + if (Take('.')) + { + RequireDigits("Expected a digit after the decimal point"); + } + + if (Take('e') || Take('E')) + { + _ = Take('+') || Take('-'); + RequireDigits("Expected a digit in the exponent"); + } + + return new LiteralExpression(PathValue.Of(JsonElement.Parse(_text[start.._pos]))); + } + + private FunctionCall Function(string name, int start) + { + var signature = FunctionCall.Find(name) + ?? throw Error($"Unknown function {name}(): the functions are length, count, match, search and value", start); + _pos++; + Enter(); + SkipBlanks(); + var operands = new List(); + if (!Peek(')')) + { + while (true) + { + operands.Add(Or()); + SkipBlanks(); + if (!Take(',')) + { + break; + } + + SkipBlanks(); + } + } + + if (!Take(')')) + { + throw Unexpected("',' or ')'"); + } + + Leave(); + var parameters = signature.Parameters; + if (operands.Count != parameters.Length) + { + throw Error($"{name}() takes {parameters.Length} argument{(parameters.Length == 1 ? "" : "s")}, not {operands.Count}", start); + } + + var arguments = new object[operands.Count]; + for (var i = 0; i < operands.Count; i++) + { + arguments[i] = parameters[i] switch + { + PathType.Value => Value(operands[i]), + PathType.Nodes => operands[i].Kind == OperandKind.Query + ? operands[i].Node + : throw Error($"{name}() takes a query, such as @.items or $..id", operands[i].Position), + _ => Test(operands[i]), + }; + } + + return new FunctionCall(name, signature.Function, signature.Result, arguments); + } + + /// An operand used as a value: a literal, a query that selects at most one value, or length, count or value. + private ValueExpression Value(Operand operand) => operand.Kind switch + { + OperandKind.Literal => (LiteralExpression)operand.Node, + OperandKind.Query when ((PathQuery)operand.Node).IsSingular => new QueryValueExpression((PathQuery)operand.Node), + OperandKind.Query => throw Error( + "This query can select more than one value, where one is expected: use names and indexes only (@.a[0]), or count() or value()", + operand.Position), + OperandKind.Function when ((FunctionCall)operand.Node).Result == PathType.Value => new FunctionValueExpression((FunctionCall)operand.Node), + OperandKind.Function => throw Error($"{((FunctionCall)operand.Node).Name}() is true or false, not a value: use it as a test", operand.Position), + _ => throw Error("A test (==, &&, ! …) is not a value: it cannot be compared", operand.Position), + }; + + /// An operand used as a test: a query (whether it selects anything), a comparison, or match or search. + private LogicalExpression Test(Operand operand) => operand.Kind switch + { + OperandKind.Logical => (LogicalExpression)operand.Node, + OperandKind.Query => new ExistsExpression((PathQuery)operand.Node), + OperandKind.Function when ((FunctionCall)operand.Node).Result != PathType.Value => new FunctionTestExpression((FunctionCall)operand.Node), + OperandKind.Function => throw Error($"{((FunctionCall)operand.Node).Name}() is a value, not a test: compare it, e.g. {((FunctionCall)operand.Node).Name}(…) > 0", operand.Position), + _ => throw Error("A value is not a test: compare it, e.g. @.name == 'x'", operand.Position), + }; + + // ----- characters --------------------------------------------------------------------- + + private bool Peek(char c, int offset = 0) => _pos + offset < _text.Length && _text[_pos + offset] == c; + + private bool Take(char c) + { + if (!Peek(c)) + { + return false; + } + + _pos++; + return true; + } + + private bool TakeOperator(string op) + { + var start = _pos; + SkipBlanks(); + if (_text.AsSpan(_pos).StartsWith(op, StringComparison.Ordinal)) + { + _pos += op.Length; + SkipBlanks(); + return true; + } + + _pos = start; + return false; + } + + private void SkipBlanks() + { + while (_pos < _text.Length && _text[_pos] is ' ' or '\t' or '\n' or '\r') + { + _pos++; + } + } + + private void SkipDigits() + { + while (_pos < _text.Length && char.IsAsciiDigit(_text[_pos])) + { + _pos++; + } + } + + private void RequireDigits(string message) + { + if (!(_pos < _text.Length && char.IsAsciiDigit(_text[_pos]))) + { + throw Error(message); + } + + SkipDigits(); + } + + private void Enter() + { + if (++_nesting > MaxNesting) + { + throw Error($"The query nests filters, parentheses and functions more than {MaxNesting} deep"); + } + } + + private void Leave() => _nesting--; + + private JsonPathException Unexpected(string expected) => + _pos >= _text.Length ? Error($"The query ends where {expected} is expected") : Error($"Unexpected {Describe(_pos)}: expected {expected}"); + + private JsonPathException Error(string message, int? at = null) + { + var position = at ?? _pos; + return new JsonPathException($"{message} (character {position + 1}).", position); + } + + private string Describe(int at) => _text[at] switch + { + ' ' => "space", + '\t' => "tab", + '\n' or '\r' => "line break", + var c when char.IsControl(c) => $"control character U+{(int)c:X4}", + var c when char.IsHighSurrogate(c) && at + 1 < _text.Length && char.IsLowSurrogate(_text[at + 1]) => $"'{_text.Substring(at, 2)}'", + var c when char.IsSurrogate(c) => $"half of a character (U+{(int)c:X4})", + var c => $"'{c}'", + }; + + /// A part of a filter expression, whose use (a value, a query or a test) is checked where it is used. + private readonly record struct Operand(OperandKind Kind, object Node, int Position); +} diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index b484f7e..1c90221 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -305,6 +305,8 @@ internal async Task SendAndShowAsync(CancellationToken cancellationToken = defau new MenuItem("_Import from cURL…", "", ShowCurlImport), new MenuItem("_History", Key.F9, ToggleHistory), new MenuItem("Focus _URL bar", Key.L.WithCtrl, () => _editor.FocusUrl()), + new MenuItem("Find in res_ponse", Key.F.WithCtrl, () => _response.OpenFind()), + new MenuItem("Filter response with _JSONPath", "", () => _response.ToggleFilter()), new Line(), new MenuItem("Collection or folder scrip_ts…", "", () => EditScripts(TargetFolder())), ]), @@ -1958,6 +1960,8 @@ private static readonly (string Keys, string Action)[] Shortcuts = ("F10", "Menu"), ("Shift+F10", "Context menu"), ("Ctrl+L", "Focus the URL bar"), + ("Ctrl+F", "Find in the response"), + ("F3, Shift+F3", "Next / previous match"), ("Ctrl+Q", "Quit"), ]; @@ -2172,6 +2176,19 @@ protected override bool OnKeyDown(Key key) return true; } + // Text fields and editors leave Ctrl+F (see TuiApp.ConfigureKeyBindings) and F3 to the window. + if (key == Key.F.WithCtrl) + { + _response.OpenFind(); + return true; + } + + if (key == Key.F3 || key == Key.F3.WithShift) + { + _response.FindNext(backwards: key.IsShift); + return true; + } + if (key == Key.F12) { ToggleRecording(); diff --git a/src/TermRest.Tui/Syntax/JsonLexer.cs b/src/TermRest.Tui/Syntax/JsonLexer.cs new file mode 100644 index 0000000..e922860 --- /dev/null +++ b/src/TermRest.Tui/Syntax/JsonLexer.cs @@ -0,0 +1,93 @@ +using System.Collections.Frozen; + +namespace TermRest.Tui.Syntax; + +/// +/// JSON (and JSON with comments, as request bodies may have): keys as variables, other strings, numbers, true, false and +/// null. A string followed by a colon on its line is a key. +/// +internal sealed class JsonLexer : SyntaxLexer +{ + public static readonly JsonLexer Instance = new(); + + private static readonly FrozenSet.AlternateLookup> Constants = Words("true false null"); + + public override LexState Lex(ReadOnlySpan line, Span kinds, LexState state) + { + var i = state.Mode == LexMode.Comment ? BlockComment(line, kinds, 0, "*/", ref state) : 0; + while (i < line.Length) + { + var c = line[i]; + var next = At(line, i + 1); + if (c == '/' && next == '/') + { + kinds[i..].Fill(SyntaxKind.Comment); + break; + } + + if (c == '/' && next == '*') + { + kinds[i] = kinds[i + 1] = SyntaxKind.Comment; + i = BlockComment(line, kinds, i + 2, "*/", ref state); + continue; + } + + if (c == '"') + { + // A string ends on its line (JSON writes a line break in one as \n). + var end = StringEnd(line, i + 1); + var after = end; + while (after < line.Length && line[after] is ' ' or '\t') + { + after++; + } + + kinds[i..end].Fill(At(line, after) == ':' ? SyntaxKind.Variable : SyntaxKind.String); + i = end; + continue; + } + + if ((c == '-' && char.IsAsciiDigit(next) && !(i > 0 && IsWordPart(line[i - 1]))) || IsNumberStart(line, i)) + { + var end = NumberEnd(line, c == '-' ? i + 1 : i); + kinds[i..end].Fill(SyntaxKind.Number); + i = end; + continue; + } + + if (IsWordStart(c)) + { + var end = WordEnd(line, i); + if (Constants.Contains(line[i..end])) + { + kinds[i..end].Fill(SyntaxKind.Keyword); + } + + i = end; + continue; + } + + i++; + } + + return state; + } + + /// The index after the closing quote of the string whose text starts at , or the line's end. + private static int StringEnd(ReadOnlySpan line, int i) + { + for (; i < line.Length; i++) + { + if (line[i] == '\\') + { + i++; + } + else if (line[i] == '"') + { + return i + 1; + } + } + + return line.Length; + } +} diff --git a/src/TermRest.Tui/Syntax/MarkupLexer.cs b/src/TermRest.Tui/Syntax/MarkupLexer.cs new file mode 100644 index 0000000..edcb204 --- /dev/null +++ b/src/TermRest.Tui/Syntax/MarkupLexer.cs @@ -0,0 +1,281 @@ +namespace TermRest.Tui.Syntax; + +/// +/// XML and HTML: tag names as keywords, attribute names as variables, their values as strings, comments, entities +/// (&amp;) as numbers, and the declarations (<?xml …?>, <!DOCTYPE …>, CDATA sections) as types. In HTML, +/// the content of script and style elements is left plain. +/// +/// +/// What a line leaves open, in : a tag (Code, Depth 1), an attribute value in one (String, its +/// quote, Depth 1), the content of a script or style element (Code, Depth 2), a comment (Comment, Quote '-') or a CDATA +/// section (Comment, Quote ']'). In a tag and its values, Quotes says which raw text element it starts: 1 script, 2 style. +/// +internal sealed class MarkupLexer : SyntaxLexer +{ + public static readonly MarkupLexer Xml = new(html: false); + + public static readonly MarkupLexer Html = new(html: true); + + private const byte InTag = 1; + private const byte InRawText = 2; + + private static readonly string[] RawTextElements = ["", "script", "style"]; + + private static readonly string[] RawTextEnds = ["", " _html = html; + + public override LexState Lex(ReadOnlySpan line, Span kinds, LexState state) + { + var i = 0; + switch (state) + { + case { Mode: LexMode.Comment, Quote: '-' }: + i = Until(line, kinds, 0, "-->", SyntaxKind.Comment, SyntaxKind.Comment, ref state); + break; + case { Mode: LexMode.Comment }: + i = Until(line, kinds, 0, "]]>", SyntaxKind.String, SyntaxKind.Type, ref state); + break; + case { Mode: LexMode.String }: + i = AttributeValue(line, kinds, 0, ref state); + break; + case { Depth: InRawText }: + i = RawText(line, 0, ref state); + break; + } + + while (i < line.Length) + { + if (state.Mode != LexMode.Code) + { + break; // a comment, CDATA section or value goes on past the line + } + + if (state.Depth == InTag) + { + i = TagBody(line, kinds, i, ref state); + continue; + } + + if (state.Depth == InRawText) + { + i = RawText(line, i, ref state); + continue; + } + + var c = line[i]; + if (c == '<') + { + i = TagStart(line, kinds, i, ref state); + continue; + } + + if (c == '&' && EntityEnd(line, i) is var entityEnd and > 0) + { + kinds[i..entityEnd].Fill(SyntaxKind.Number); + i = entityEnd; + continue; + } + + i++; + } + + return state; + } + + /// What starts with a < at : a tag, a comment, a declaration, or text (a < alone). + private int TagStart(ReadOnlySpan line, Span kinds, int i, ref LexState state) + { + var rest = line[i..]; + if (rest.StartsWith("", SyntaxKind.Comment, SyntaxKind.Comment, ref state); + } + + if (rest.StartsWith("", SyntaxKind.String, SyntaxKind.Type, ref state); + } + + var next = At(line, i + 1); + if (next is '!' or '?') + { + // , : the rest is read as attributes. + var end = NameEnd(line, i + 2); + kinds[i..end].Fill(SyntaxKind.Type); + state = new LexState(LexMode.Code, Depth: InTag); + return end; + } + + var closing = next == '/'; + var nameStart = closing ? i + 2 : i + 1; + if (!IsNameStart(At(line, nameStart))) + { + return i + 1; // a < in text + } + + var nameEnd = NameEnd(line, nameStart); + kinds[nameStart..nameEnd].Fill(SyntaxKind.Keyword); + byte raw = 0; + for (var element = 1; _html && !closing && element < RawTextElements.Length; element++) + { + if (line[nameStart..nameEnd].Equals(RawTextElements[element], StringComparison.OrdinalIgnoreCase)) + { + raw = (byte)element; + } + } + + state = new LexState(LexMode.Code, Quotes: raw, Depth: InTag); + return nameEnd; + } + + /// The attributes of a tag from , up to its end (or the line's). + private static int TagBody(ReadOnlySpan line, Span kinds, int i, ref LexState state) + { + var value = false; // after =: an unquoted value (HTML) + while (i < line.Length) + { + var c = line[i]; + var next = At(line, i + 1); + if (c == '>' || (c is '/' or '?' && next == '>')) + { + // The end of the tag; after a script or style start tag, the element's content. + var raw = c == '>' ? state.Quotes : (byte)0; + state = raw > 0 ? new LexState(LexMode.Code, Quotes: raw, Depth: InRawText) : LexState.Code; + return c == '>' ? i + 1 : i + 2; + } + + if (c == '<') + { + state = LexState.Code; // a tag left open: what follows is another one + return i; + } + + if (c is '"' or '\'') + { + kinds[i] = SyntaxKind.String; + state = state with { Mode = LexMode.String, Quote = c }; + return AttributeValue(line, kinds, i + 1, ref state); + } + + if (char.IsWhiteSpace(c) || c == '=') + { + value = c == '=' || (value && char.IsWhiteSpace(c)); + i++; + continue; + } + + var end = i + 1; + while (end < line.Length && !(char.IsWhiteSpace(line[end]) || line[end] is '"' or '\'' or '=' or '<' or '>' || (line[end] is '/' or '?' && At(line, end + 1) == '>'))) + { + end++; + } + + kinds[i..end].Fill(value ? SyntaxKind.String : SyntaxKind.Variable); + value = false; + i = end; + } + + return i; + } + + /// A quoted attribute value from to its closing quote (it may go on over lines). + private static int AttributeValue(ReadOnlySpan line, Span kinds, int i, ref LexState state) + { + var close = line[i..].IndexOf(state.Quote); + var end = close < 0 ? line.Length : i + close + 1; + kinds[i..end].Fill(SyntaxKind.String); + if (close >= 0) + { + state = state with { Mode = LexMode.Code, Quote = '\0' }; + } + + return end; + } + + /// The content of a script or style element from , up to its end tag (or the line's end). + private static int RawText(ReadOnlySpan line, int i, ref LexState state) + { + var found = line[i..].IndexOf(RawTextEnds[state.Quotes], StringComparison.OrdinalIgnoreCase); + if (found < 0) + { + return line.Length; + } + + state = LexState.Code; + return i + found; + } + + /// + /// Colors from up to , which gets + /// ; returns the index after it, or the line's end ( unchanged). + /// + private static int Until(ReadOnlySpan line, Span kinds, int i, string close, SyntaxKind kind, SyntaxKind closeKind, ref LexState state) + { + var found = line[i..].IndexOf(close.AsSpan()); + if (found < 0) + { + kinds[i..].Fill(kind); + return line.Length; + } + + kinds[i..(i + found)].Fill(kind); + kinds[(i + found)..(i + found + close.Length)].Fill(closeKind); + state = LexState.Code; + return i + found + close.Length; + } + + /// The end of an entity at (&amp; &#38; &#x26;), or -1. + private static int EntityEnd(ReadOnlySpan line, int i) + { + var j = i + 1; + if (At(line, j) == '#') + { + j++; + var hex = At(line, j) is 'x' or 'X'; + if (hex) + { + j++; + } + + var digits = j; + while (j < line.Length && (hex ? char.IsAsciiHexDigit(line[j]) : char.IsAsciiDigit(line[j]))) + { + j++; + } + + return j > digits && At(line, j) == ';' ? j + 1 : -1; + } + + if (!char.IsAsciiLetter(At(line, j))) + { + return -1; + } + + while (j < line.Length && char.IsAsciiLetterOrDigit(line[j])) + { + j++; + } + + return At(line, j) == ';' ? j + 1 : -1; + } + + private static bool IsNameStart(char c) => char.IsLetter(c) || c is '_' or ':'; + + /// The end of the tag or declaration name at : letters, digits and _ : . - + private static int NameEnd(ReadOnlySpan line, int i) + { + while (i < line.Length && (char.IsLetterOrDigit(line[i]) || line[i] is '_' or ':' or '.' or '-')) + { + i++; + } + + return i; + } +} diff --git a/src/TermRest.Tui/Syntax/SyntaxLexer.cs b/src/TermRest.Tui/Syntax/SyntaxLexer.cs index 478114a..0f006c2 100644 --- a/src/TermRest.Tui/Syntax/SyntaxLexer.cs +++ b/src/TermRest.Tui/Syntax/SyntaxLexer.cs @@ -76,13 +76,19 @@ internal abstract class SyntaxLexer [ThreadStatic] private static int _nesting; - /// The lexer of a script language (), or null for plain text. + /// + /// The lexer of a language: a script language (), or a body's (json, xml, html, javascript); + /// null for plain text. + /// public static SyntaxLexer? For(string? language) => language switch { ScriptLanguage.Python => PythonLexer.Instance, ScriptLanguage.JavaScript => JavaScriptLexer.Instance, ScriptLanguage.CSharp => CSharpLexer.Instance, ScriptLanguage.PowerShell => PowerShellLexer.Instance, + "json" => JsonLexer.Instance, + "xml" => MarkupLexer.Xml, + "html" => MarkupLexer.Html, _ => null, }; diff --git a/src/TermRest.Tui/TuiApp.cs b/src/TermRest.Tui/TuiApp.cs index 547e6da..b15a2df 100644 --- a/src/TermRest.Tui/TuiApp.cs +++ b/src/TermRest.Tui/TuiApp.cs @@ -1,6 +1,7 @@ using System.Text; using Terminal.Gui.App; using Terminal.Gui.Input; +using Terminal.Gui.Views; using TermRest.Core.History; using TermRest.Core.Workspace; using TermRest.Tui.Theming; @@ -141,6 +142,13 @@ internal static void ConfigureKeyBindings() { Application.RemoveDefaultKeyBinding(Command.Refresh); } + + // Ctrl+F finds in the response: not the cursor moving right (Emacs), which is all Command.Right adds to the arrow key + // in Terminal.Gui 2.5's text fields and editors. + TextField.DefaultKeyBindings?.Remove(Command.Right); +#pragma warning disable CS0618 // TextView: the editor TextArea derives from + TextView.DefaultKeyBindings?.Remove(Command.Right); +#pragma warning restore CS0618 } /// Creates the main window without running it (used by tests). diff --git a/src/TermRest.Tui/Views/BodyEditor.cs b/src/TermRest.Tui/Views/BodyEditor.cs index 48d7e25..e9f3877 100644 --- a/src/TermRest.Tui/Views/BodyEditor.cs +++ b/src/TermRest.Tui/Views/BodyEditor.cs @@ -80,6 +80,7 @@ public BodyEditor() _language = new OptionSelector { X = 0, Y = 1, Orientation = Orientation.Horizontal, Labels = LanguageLabels, Value = 0 }; _language.ValueChanged += (_, e) => { + ColorRaw(); if (!_loading && e.NewValue is int index) { _body.RawLanguage = Languages[index]; @@ -90,6 +91,7 @@ public BodyEditor() _beautify.Accepted += (_, _) => Beautify(); _raw = new TextArea { X = 0, Y = 2, Width = Dim.Fill(), Height = Dim.Fill() }; + ColorRaw(); _raw.UserEdited += (_, text) => { _body.Raw = text; @@ -160,7 +162,7 @@ public BodyEditor() _body.GraphQLQuery = text; RaiseChanged(); }; - _graphQLVariables = new TextArea { X = Pos.Right(_graphQLQuery) + 1, Y = 1, Width = Dim.Fill(), Height = Dim.Fill() }; + _graphQLVariables = new TextArea { X = Pos.Right(_graphQLQuery) + 1, Y = 1, Width = Dim.Fill(), Height = Dim.Fill(), SyntaxLanguage = "json" }; _graphQLVariables.UserEdited += (_, text) => { _body.GraphQLVariables = text; @@ -199,6 +201,12 @@ public bool Recording /// What the file panel says about the chosen file (for tests). internal string FileStatus => _fileStatus.Text; + /// The language the raw body is colored in (for tests). + internal string? RawSyntax => _raw.SyntaxLanguage; + + /// Colors the raw body in the language chosen for it (none for Text). + private void ColorRaw() => _raw.SyntaxLanguage = _language.Value is int index && Languages[index] != "text" ? Languages[index] : null; + public void Load(RequestBody body) { _loading = true; diff --git a/src/TermRest.Tui/Views/RequestEditor.cs b/src/TermRest.Tui/Views/RequestEditor.cs index d20e6cb..f8c7958 100644 --- a/src/TermRest.Tui/Views/RequestEditor.cs +++ b/src/TermRest.Tui/Views/RequestEditor.cs @@ -212,6 +212,9 @@ public Func? FilesFolder /// What the Body tab says about the body file (for tests). internal string BodyFileStatus => _body.FileStatus; + /// The language the raw body is colored in (for tests). + internal string? RawBodySyntax => _body.RawSyntax; + /// The Scripts tab (for tests). internal ScriptsEditor ScriptsTab => _scripts; diff --git a/src/TermRest.Tui/Views/ResponseView.cs b/src/TermRest.Tui/Views/ResponseView.cs index ef18d11..8fe7977 100644 --- a/src/TermRest.Tui/Views/ResponseView.cs +++ b/src/TermRest.Tui/Views/ResponseView.cs @@ -5,12 +5,16 @@ using Terminal.Gui.ViewBase; using Terminal.Gui.Views; using TermRest.Core.Http; +using TermRest.Core.Json; using TermRest.Tui.Dialogs; using TermRest.Tui.Theming; namespace TermRest.Tui.Views; -/// Response pane: status line plus Body / Headers / Timeline / TLS tabs. +/// +/// Response pane: status line plus Body / Headers / Timeline / TLS / Scripts tabs. The body is colored as its type says, +/// can be filtered with JSONPath, and Find (Ctrl+F) looks for text in the tab shown. +/// internal sealed class ResponseView : View { /// @@ -22,6 +26,9 @@ internal sealed class ResponseView : View /// Bodies of this many bytes or more are formatted (decoded, pretty printed) in the background. private const int BackgroundSize = 1_048_576; + /// A filter's values are written up to this many bytes (of UTF-8): the body tab shows their start, Copy all of them. + internal const long MaxFilteredBytes = 16 * 1024 * 1024; + /// The Timeline tab shows this many characters of a request's body at most. private const int TimelineBodyLength = 4000; @@ -43,10 +50,21 @@ internal sealed class ResponseView : View private readonly TextArea _timeline; private readonly TextArea _tls; private readonly TextArea _scripts; + private readonly View _filterRow; + private readonly TextField _filterField; + private readonly Label _filterStatus; + private readonly View _findBar; + private readonly TextField _findField; + private readonly CheckBox _matchCase; + private readonly Label _findCount; private HttpExchange? _exchange; private bool _fromHistory; // the exchange shown came from the history: its body as the history keeps it private bool _prettyOn = true; private int _bodyVersion; // a body formatted in the background is shown only if no other body replaced it meanwhile + private CancellationTokenSource? _rendering; // the body formatted or filtered in the background, stopped when replaced + private JsonPath? _filter; // the query the body is filtered with, kept for the responses that follow + private bool _filterInvalid; // the query typed is not valid JSONPath: the filter row says why + private TextArea? _findTarget; // the text of the tab that Find looks in private bool _disposed; public ResponseView() @@ -77,8 +95,20 @@ public ResponseView() copy.Accepted += (_, _) => CopyBody(); var save = new Button { Text = "Save as…", X = Pos.Right(copy) + 2, Y = 0, NoDecorations = true, ShadowStyle = null }; save.Accepted += (_, _) => SaveBody(); + var filter = new Button { Text = "Filter", X = Pos.Right(save) + 2, Y = 0, NoDecorations = true, ShadowStyle = null }; + filter.Accepted += (_, _) => ToggleFilter(); _body = new TextArea { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill(), ReadOnly = true }; - _bodyTab.Add(_pretty, _wrap, copy, save, _body); + + // JSONPath: the body shows the values the query selects, as a JSON array. + _filterRow = new View { X = 0, Y = 1, Width = Dim.Fill(), Height = 1, CanFocus = true, Visible = false }; + var filterLabel = new Label { Text = "JSONPath:", X = 0, Y = 0 }; + _filterField = new TextField { X = Pos.Right(filterLabel) + 1, Y = 0, Width = Dim.Percent(45) }; + _filterField.TextChanged += (_, _) => FilterChanged(); + _filterStatus = new Label { HotKeySpecifier = Ui.NoHotKey, X = Pos.Right(_filterField) + 1, Y = 0, Width = Dim.Fill(3), Text = "" }; + var closeFilter = new Button { Text = "✕", X = Pos.AnchorEnd(2), Y = 0, NoDecorations = true, ShadowStyle = null }; + closeFilter.Accepted += (_, _) => CloseFilter(); + _filterRow.Add(filterLabel, _filterField, _filterStatus, closeFilter); + _bodyTab.Add(_pretty, _wrap, copy, save, filter, _filterRow, _body); var headersTab = new View { Title = "Headers", Width = Dim.Fill(), Height = Dim.Fill(), CanFocus = true }; _headers = new TableView { Width = Dim.Fill(), Height = Dim.Fill(), FullRowSelect = true }; @@ -107,7 +137,51 @@ public ResponseView() scriptsTab.Add(_scripts); _tabs.AddTabs(_bodyTab, headersTab, timelineTab, tlsTab, scriptsTab); - Add(_status, _tabs); + + // Find (Ctrl+F): in the text of the tab shown. + _findBar = new View { X = 0, Y = Pos.AnchorEnd(1), Width = Dim.Fill(), Height = 1, CanFocus = true, Visible = false }; + var findLabel = new Label { Text = "Find:", X = 0, Y = 0 }; + _findField = new TextField { X = Pos.Right(findLabel) + 1, Y = 0, Width = Dim.Fill(38) }; + _findField.TextChanged += (_, _) => FindChanged(); + var previous = new Button { Text = "▲", X = Pos.Right(_findField) + 1, Y = 0, NoDecorations = true, ShadowStyle = null }; + previous.Accepted += (_, _) => FindNext(backwards: true); + var next = new Button { Text = "▼", X = Pos.Right(previous) + 1, Y = 0, NoDecorations = true, ShadowStyle = null }; + next.Accepted += (_, _) => FindNext(); + _matchCase = new CheckBox { Text = "Match case", X = Pos.Right(next) + 2, Y = 0 }; + _matchCase.ValueChanged += (_, _) => FindChanged(); + _findCount = new Label { HotKeySpecifier = Ui.NoHotKey, X = Pos.Right(_matchCase) + 2, Y = 0, Width = Dim.Fill(3), Text = "" }; + var closeFind = new Button { Text = "✕", X = Pos.AnchorEnd(2), Y = 0, NoDecorations = true, ShadowStyle = null }; + closeFind.Accepted += (_, _) => CloseFind(); + _findBar.Add(findLabel, _findField, previous, next, _matchCase, _findCount, closeFind); + + // Enter and Shift+Enter go to the next and previous match (Esc closes the bar: see OnKeyDown). + _findField.KeyDown += (_, key) => + { + if (key == Key.Enter || key == Key.Enter.WithShift) + { + FindNext(backwards: key.IsShift); + key.Handled = true; + } + }; + _tabs.ValueChanged += (_, _) => + { + if (_findBar.Visible) + { + FindIn(SearchedArea()); + } + }; + foreach (var area in new[] { _body, _timeline, _tls, _scripts }) + { + area.MatchesChanged += (sender, _) => + { + if (sender == _findTarget) + { + ShowFindCount(); + } + }; + } + + Add(_status, _tabs, _findBar); SetHeaders([]); _scripts.SetText(NoScripts); } @@ -139,6 +213,15 @@ public ResponseView() /// The TLS tab's text (for tests). internal string TlsText => _tls.GetText(); + /// The language the Body tab colors its text in (for tests). + internal string? BodySyntax => _body.SyntaxLanguage; + + /// What the filter row says: how many values the query selects, or why it can't (for tests). + internal string FilterStatus => _filterStatus.Text; + + /// What the find bar says: which match is selected, of how many (for tests). + internal string FindStatus => _findCount.Text; + public void Clear() { _exchange = null; @@ -146,6 +229,7 @@ public void Clear() _status.Text = "No response yet. Press F5 (or Enter in the URL bar) to send."; _status.SchemeName = null; ShowBody(""); + SetFilterStatus("", error: false); _timeline.SetText(""); _tls.SetText(""); _scripts.SetText(NoScripts); @@ -184,6 +268,7 @@ public void ShowExchange(HttpExchange exchange, bool fromHistory = false) // When a script stopped the request, its traceback is what the user needs to see. ShowBody(exchange.Cancelled ? "" : scripts?.Error is not null ? ShownScripts($"{exchange.ErrorMessage}\n\n{scripts.Describe()}") : exchange.ErrorMessage ?? ""); + SetFilterStatus(_filter is null ? "" : "No response to filter.", error: false); SetHeaders([]); } else @@ -218,12 +303,15 @@ public void ShowExchange(HttpExchange exchange, bool fromHistory = false) } /// - /// Shows the response body, pretty or not, formatted from the response each time (as Copy is): the editor's text has - /// its own line breaks (a lone CR shows as one) and only the start of a long body, and keeping the whole text as well - /// would take memory. A large body is formatted in the background, and shown if nothing replaced it meanwhile. + /// Shows the response body, pretty or not (or the values the filter selects in it), formatted from the response each time + /// (as Copy is): the editor's text has its own line breaks (a lone CR shows as one) and only the start of a long body, + /// and keeping the whole text as well would take memory. A large body is formatted in the background, and shown if + /// nothing replaced it meanwhile. /// private void RenderBody() { + _rendering?.Cancel(); + _rendering = null; if (_exchange?.Response is not { } response) { return; @@ -233,23 +321,38 @@ private void RenderBody() if (BodyNotKept) { ShowBody("(response body not kept in the history)"); + SetFilterStatus(_filter is null ? "" : "✗ The history kept no copy of this response body.", error: true); return; } - var pretty = _prettyOn; + var (pretty, filter) = (_prettyOn, _filter); if (App is not { } app || response.Body.Length < BackgroundSize) { - ShowBody(Shown(response, pretty)); + Show(Render(response, pretty, filter, CancellationToken.None)); return; } - var version = ShowBody("Formatting…"); - _ = Task.Run(() => Shown(response, pretty)).ContinueWith( + var rendering = _rendering = new CancellationTokenSource(); + var version = ShowBody(filter is null ? "Formatting…" : "Filtering…"); + _ = Task.Run(() => Render(response, pretty, filter, rendering.Token), rendering.Token).ContinueWith( task => app.AddTimeout(TimeSpan.Zero, () => { + if (_rendering == rendering) + { + _rendering = null; + } + + rendering.Dispose(); if (version == _bodyVersion && !_disposed) { - _body.SetText(task.IsCompletedSuccessfully ? task.Result : $"✗ {task.Exception?.GetBaseException().Message}"); + if (task.IsCompletedSuccessfully) + { + Show(task.Result); + } + else if (!task.IsCanceled) + { + ShowBody($"✗ {task.Exception?.GetBaseException().Message}"); + } } return false; @@ -257,17 +360,88 @@ private void RenderBody() TaskScheduler.Default); } + /// What the body tab shows of a response, the language it is colored in, and what the filter row says. + internal readonly record struct RenderedBody(string Text, string? Language, string FilterStatus = "", bool FilterFailed = false); + + /// + /// The body as the body tab shows it (see ), or, with a filter, the values it selects (as much of them + /// as allows). A body the filter can't apply to is shown as it is, and the filter row says why. + /// + internal static RenderedBody Render(ResponseSnapshot response, bool pretty, JsonPath? filter, CancellationToken cancellationToken) + { + if (filter is not null) + { + try + { + var filtered = BodyFilter.Apply(filter, response.Body, response.ContentType, pretty, MaxFilteredBytes, cancellationToken); + var text = filtered.Text.Length <= MaxShownLength + ? filtered.Text + : string.Concat(Start(filtered.Text), $"\n\n… showing the first {HttpExchange.FormatSize(MaxShownLength)} of {HttpExchange.FormatSize(filtered.Text.Length)}: Copy gives them all"); + return new RenderedBody(text, "json", Describe(filtered)); + } + catch (JsonPathException ex) + { + var shown = Shown(response, pretty); + var cut = response.BodyTruncated ? " The body was cut at the maximum response size (Tools > Settings)." : ""; + return new RenderedBody(shown, SyntaxOf(response, shown), $"✗ {ex.Message}{cut}", FilterFailed: true); + } + } + + var body = Shown(response, pretty); + return new RenderedBody(body, SyntaxOf(response, body)); + } + + /// How many values a filter selected, and how many of them it wrote. + private static string Describe(FilteredBody filtered) + { + var count = filtered.Count.ToString("N0", CultureInfo.InvariantCulture); + return filtered.Count == 0 ? "No values" + : filtered.Shown < filtered.Count ? $"{count} values: the first {filtered.Shown.ToString("N0", CultureInfo.InvariantCulture)}, {HttpExchange.FormatSize(MaxFilteredBytes)}, are shown" + : filtered.Count == 1 ? "1 value" + : $"{count} values"; + } + + /// + /// The language the body tab colors a response body in: the one its Content-Type names, or JSON, HTML or other markup + /// (as XML) that a body of another type (text/plain, say) or none holds. Null for other text and for a hex dump. + /// + internal static string? SyntaxOf(ResponseSnapshot response, string shown) + { + var language = BodyFormatter.Language(response.Body, response.ContentType); + if (language != "text") + { + return language == "binary" ? null : language; + } + + // Pretty printing drops an XML declaration: the text shown starts with the root element then. + var start = shown.AsSpan().TrimStart(); + return start.StartsWith('{') || start.StartsWith('[') ? "json" + : start.StartsWith(" 0) + { + SetFilterStatus(rendered.FilterStatus, rendered.FilterFailed); + } + } + /// The response comes from the history, which has no copy of its body, though the body was not empty. private bool BodyNotKept => _fromHistory && _exchange?.Response?.Body.Length == 0 && _exchange.HistoryEntry?.Size > 0; - /// Shows in the body tab, in place of a body still being formatted. - private int ShowBody(string text) + /// Shows in the body tab, colored in , in place of a body still being formatted. + private int ShowBody(string text, string? language = null) { + _body.SyntaxLanguage = language; _body.SetText(text); return ++_bodyVersion; } - /// Copies the whole body, as formatted (a large one is formatted in the background). + /// Copies the whole body, as formatted, or the values the filter selects (a large body is done in the background). private void CopyBody() { if (_exchange?.Response is not { } response) @@ -281,15 +455,15 @@ private void CopyBody() return; } - var pretty = _prettyOn; + var (pretty, filter) = (_prettyOn, _filter); if (App is not { } app || response.Body.Length < BackgroundSize) { - Copied(Whole(response, pretty)); + Copied(Whole(response, pretty, filter)); return; } - Notify("Copying the response body…"); - _ = Task.Run(() => Whole(response, pretty)).ContinueWith( + Notify(filter is null ? "Copying the response body…" : "Copying the values the filter selects…"); + _ = Task.Run(() => Whole(response, pretty, filter)).ContinueWith( task => app.AddTimeout(TimeSpan.Zero, () => { if (task.IsCompletedSuccessfully) @@ -306,19 +480,36 @@ private void CopyBody() TaskScheduler.Default); } - private void Copied(string text) + private void Copied((string Text, bool Filtered) copied) { if (!_disposed) { - Notify(Ui.CopyToClipboard(App, text) ? "Response body copied to the clipboard." : "Clipboard is not available in this terminal."); + Notify(!Ui.CopyToClipboard(App, copied.Text) ? "Clipboard is not available in this terminal." + : copied.Filtered ? "The values the filter selects copied to the clipboard." + : "Response body copied to the clipboard."); } } - /// The whole body as formatted, with a note when the size limit cut it. - private static string Whole(ResponseSnapshot response, bool pretty) + /// + /// What Copy copies: the values the filter selects (up to ), or the whole body as formatted, + /// with a note when the size limit cut it. + /// + private static (string Text, bool Filtered) Whole(ResponseSnapshot response, bool pretty, JsonPath? filter) { + if (filter is not null) + { + try + { + return (BodyFilter.Apply(filter, response.Body, response.ContentType, pretty, MaxFilteredBytes).Text, true); + } + catch (JsonPathException) + { + // Not JSON: the body tab shows the body, which is copied. + } + } + var text = BodyFormatter.Format(response.Body, response.ContentType, pretty); - return response.BodyTruncated ? text + "\n\n… (truncated)" : text; + return (response.BodyTruncated ? text + "\n\n… (truncated)" : text, false); } /// @@ -457,9 +648,206 @@ private void SaveBody() private void Notify(string message) => Notice?.Invoke(this, message); + // ----- filter --------------------------------------------------------------------------- + + /// The Filter button: shows the JSONPath row (or closes it, which clears the filter). + internal void ToggleFilter() + { + if (_filterRow.Visible) + { + CloseFilter(); + return; + } + + _filterRow.Visible = true; + _body.Y = 2; + _tabs.Select(_bodyTab, focusPage: false); + _filterField.SetFocus(); + FilterChanged(); + } + + private void CloseFilter() + { + _filterRow.Visible = false; + _body.Y = 1; + _filterField.Text = ""; // the filter goes with it + FilterChanged(); + _body.SetFocus(); + } + + /// The query in the filter row, as typed; the body shows what it selects in this response and the ones after it. + internal void SetFilter(string query) + { + if (!_filterRow.Visible) + { + ToggleFilter(); + } + + _filterField.Text = query; + } + + /// + /// The query was edited: the body shows what it selects. While it is not valid JSONPath (being typed), the row says why + /// and the body shows what the last valid one selected. + /// + private void FilterChanged() + { + var text = _filterField.Text.TrimEnd(); + _filterInvalid = false; + if (text.Length == 0) + { + SetFilterStatus("Type a JSONPath query, such as $.items[*].id", error: false); + if (_filter is not null) + { + _filter = null; + RenderBody(); + } + + return; + } + + try + { + _filter = JsonPath.Parse(text); + } + catch (JsonPathException ex) + { + SetFilterStatus($"✗ {ex.Message}", error: true); + _filterInvalid = true; + return; + } + + if (_exchange?.Response is null) + { + SetFilterStatus("No response to filter yet.", error: false); + return; + } + + RenderBody(); + } + + private void SetFilterStatus(string text, bool error) + { + if (_filterInvalid) + { + return; // the row says why the query typed is not valid + } + + _filterStatus.Text = text; + _filterStatus.SchemeName = error ? "Error" : null; + } + + // ----- find ----------------------------------------------------------------------------- + + /// Ctrl+F: shows the find bar, its text selected to type over, looking in the text of the tab shown. + internal void OpenFind() + { + if (!_findBar.Visible) + { + _findBar.Visible = true; + _tabs.Height = Dim.Fill(1); + FindIn(SearchedArea()); + } + + _findField.SetFocus(); + _findField.SelectAll(); + } + + /// + /// F3 or Enter in the find bar: selects the next match (Shift: the previous one), going round. Opens the find bar when it + /// is closed or has no text. + /// + internal void FindNext(bool backwards = false) + { + if (!_findBar.Visible || _findField.Text.Length == 0) + { + OpenFind(); + return; + } + + _findTarget?.SelectNextMatch(backwards); + ShowFindCount(); + } + + /// The text the find bar looks for (for tests). + internal void Find(string text, bool matchCase = false) + { + OpenFind(); + _matchCase.Value = matchCase ? CheckState.Checked : CheckState.UnChecked; + _findField.Text = text; + } + + private void CloseFind() + { + var area = _findTarget; + FindIn(null); + _findBar.Visible = false; + _tabs.Height = Dim.Fill(); + if (area is not null) + { + area.SetFocus(); + } + else + { + _tabs.FocusSelectedPage(); + } + } + + private void FindChanged() + { + _findTarget?.Find(_findField.Text, _matchCase.Value == CheckState.Checked); + ShowFindCount(); + } + + /// Looks for the find bar's text in (the text of the tab shown), and no longer in another. + private void FindIn(TextArea? area) + { + if (_findTarget is { } previous && previous != area) + { + previous.Find(null, matchCase: false); + } + + _findTarget = area; + area?.Find(_findField.Text, _matchCase.Value == CheckState.Checked); + ShowFindCount(); + } + + /// The text of the tab shown; none for Headers, a table. + private TextArea? SearchedArea() => _tabs.Value?.SubViews.OfType