incur-cli 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
incur/_errors.py ADDED
@@ -0,0 +1,234 @@
1
+ """Command errors and call-to-action suggestions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from . import _js
9
+ from ._js import Json
10
+ from ._schema import Issue
11
+
12
+
13
+ @dataclass
14
+ class Cta:
15
+ """A suggested command.
16
+
17
+ `args` append as bare values and `options` as `--key value`; a value of `True` renders a
18
+ placeholder such as `<name>` or `--key <key>`.
19
+ """
20
+
21
+ command: str
22
+ """The command to run, without the CLI name."""
23
+ description: str | None = None
24
+ """What the command does."""
25
+ args: dict[str, Json] = field(default_factory=dict[str, Json])
26
+ """Positional arguments appended as bare values."""
27
+ options: dict[str, Json] = field(default_factory=dict[str, Json])
28
+ """Options appended as `--key value`."""
29
+
30
+
31
+ @dataclass
32
+ class CtaBlock:
33
+ """A list of suggested commands with an optional label."""
34
+
35
+ commands: list[Cta | str]
36
+ """Suggested commands. Strings are commands without a description."""
37
+ description: str | None = None
38
+ """Label. Defaults to `Suggested command:` or `Suggested commands:`."""
39
+
40
+
41
+ @dataclass
42
+ class FieldError:
43
+ """A field-level validation error."""
44
+
45
+ code: str
46
+ """The Zod issue code."""
47
+ expected: str
48
+ """The expected type."""
49
+ message: str
50
+ """Human-readable message."""
51
+ missing: bool
52
+ """Whether the input omitted the field."""
53
+ path: str
54
+ """The dotted field path."""
55
+ received: str
56
+ """The received value, when reported."""
57
+
58
+ def to_json(self) -> dict[str, Json]:
59
+ """Returns the field error as output data."""
60
+ return {
61
+ "code": self.code,
62
+ "missing": self.missing,
63
+ "path": self.path,
64
+ "expected": self.expected,
65
+ "received": self.received,
66
+ "message": self.message,
67
+ }
68
+
69
+
70
+ class Error(Exception):
71
+ """A command failure with a machine-readable code, rendered like the TypeScript `c.error()`.
72
+
73
+ Raise it from a handler or middleware. Any other exception reports as code `UNKNOWN` with the
74
+ exception's message.
75
+
76
+ >>> error = Error("NOT_AUTHENTICATED", "GitHub token not found", hint="Log in first.")
77
+ >>> error.code, str(error)
78
+ ('NOT_AUTHENTICATED', 'GitHub token not found')
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ code: str,
84
+ message: str,
85
+ *,
86
+ hint: str | None = None,
87
+ retryable: bool | None = None,
88
+ exit_code: int | None = None,
89
+ cta: CtaBlock | None = None,
90
+ field_errors: list[FieldError] | None = None,
91
+ ) -> None:
92
+ super().__init__(message)
93
+ self.code = code
94
+ """Machine-readable error code."""
95
+ self.message = message
96
+ """Human-readable message."""
97
+ self.hint = hint
98
+ """Actionable hint."""
99
+ self.retryable = retryable
100
+ """Whether the operation can be retried."""
101
+ self.exit_code = exit_code
102
+ """Process exit code. Defaults to 1."""
103
+ self.cta = cta
104
+ """Suggested commands to run next."""
105
+ self.field_errors = field_errors
106
+ """Per-field validation errors."""
107
+
108
+ def to_json(self) -> dict[str, Json]:
109
+ """Returns the `error` object of the output envelope."""
110
+ out: dict[str, Json] = {"code": self.code, "message": self.message}
111
+ if self.hint is not None:
112
+ out["hint"] = self.hint
113
+ if self.retryable is not None:
114
+ out["retryable"] = self.retryable
115
+ if self.field_errors is not None:
116
+ out["fieldErrors"] = [f.to_json() for f in self.field_errors]
117
+ return out
118
+
119
+
120
+ def unknown(message: str) -> Error:
121
+ """Creates an `UNKNOWN` error."""
122
+ return Error("UNKNOWN", message)
123
+
124
+
125
+ def validation(issues: list[Issue], data: Json) -> Error:
126
+ """Builds a validation error from schema issues, with Zod's message and details."""
127
+ short = "; ".join(issue.message for issue in issues)
128
+ details = _js.stringify_pretty([issue.to_json() for issue in issues])
129
+ field_errors = [
130
+ FieldError(
131
+ code=issue.code,
132
+ expected=issue.expected,
133
+ message=issue.message,
134
+ missing=not _has_path(data, issue.path),
135
+ path=".".join(_js.to_string(part) for part in issue.path),
136
+ received=issue.received or "",
137
+ )
138
+ for issue in issues
139
+ ]
140
+ return Error("VALIDATION_ERROR", f"{short}\n\nDetails: {details}", field_errors=field_errors)
141
+
142
+
143
+ def _has_path(data: Any, path: list[str | int]) -> bool:
144
+ """Whether the input contains the full issue path."""
145
+ current = data
146
+ for part in path:
147
+ # Issues report the indices of present array items, and keys of present objects.
148
+ if isinstance(part, str) and part not in current:
149
+ return False
150
+ current = current[part]
151
+ return True
152
+
153
+
154
+ @dataclass
155
+ class FormattedCta:
156
+ """A suggestion with the CLI name and arguments folded into one command line."""
157
+
158
+ command: str
159
+ description: str | None = None
160
+
161
+
162
+ @dataclass
163
+ class FormattedCtaBlock:
164
+ """A formatted block of suggestions."""
165
+
166
+ commands: list[FormattedCta]
167
+ description: str
168
+
169
+ @staticmethod
170
+ def of(commands: list[FormattedCta]) -> FormattedCtaBlock:
171
+ """Creates a block with the default label."""
172
+ label = "Suggested command:" if len(commands) == 1 else "Suggested commands:"
173
+ return FormattedCtaBlock(commands, label)
174
+
175
+ def to_json(self) -> dict[str, Json]:
176
+ """Returns the block as output data."""
177
+ commands: list[Json] = []
178
+ for cta in self.commands:
179
+ entry: dict[str, Json] = {"command": cta.command}
180
+ if cta.description is not None:
181
+ entry["description"] = cta.description
182
+ commands.append(entry)
183
+ return {"description": self.description, "commands": commands}
184
+
185
+ def text(self) -> str:
186
+ """Renders the block as plain text, as MCP tool results append it."""
187
+ lines = [self.description]
188
+ for cta in self.commands:
189
+ suffix = f" - {cta.description}" if cta.description else ""
190
+ lines.append(f" {cta.command}{suffix}")
191
+ return "\n".join(lines)
192
+
193
+ def human(self) -> str:
194
+ """Renders the block for a terminal."""
195
+ width = max(_js.utf16_len(cta.command) for cta in self.commands)
196
+ lines = ["", self.description]
197
+ for cta in self.commands:
198
+ suffix = ""
199
+ if cta.description is not None:
200
+ pad = " " * (width - _js.utf16_len(cta.command))
201
+ suffix = f" {pad}# {cta.description}"
202
+ lines.append(f" {cta.command}{suffix}")
203
+ return "\n".join(lines)
204
+
205
+
206
+ def format_cta(name: str, block: CtaBlock | None) -> FormattedCtaBlock | None:
207
+ """Formats a block, prefixing commands with the CLI name. Empty blocks format as `None`."""
208
+ if block is None or not block.commands:
209
+ return None
210
+ program = name.split(" ", maxsplit=1)[0]
211
+ commands: list[FormattedCta] = []
212
+ for item in block.commands:
213
+ cta = Cta(item) if isinstance(item, str) else item
214
+ prefixed = cta.command == program or cta.command.startswith(program + " ")
215
+ command = cta.command if prefixed else f"{name} {cta.command}"
216
+ for key, value in cta.args.items():
217
+ command += f" <{key}>" if value is True else f" {_js.to_string(value)}"
218
+ for key, value in cta.options.items():
219
+ command += f" --{key} <{key}>" if value is True else f" --{key} {_js.to_string(value)}"
220
+ commands.append(FormattedCta(command, cta.description or None))
221
+ if block.description is not None:
222
+ return FormattedCtaBlock(commands, block.description)
223
+ return FormattedCtaBlock.of(commands)
224
+
225
+
226
+ def human_error(error: Error) -> str:
227
+ """Renders an error for a terminal."""
228
+ prefix = "Error" if error.code in ("UNKNOWN", "COMMAND_NOT_FOUND") else f"Error ({error.code})"
229
+ out = f"{prefix}: {error.message}"
230
+ for f in error.field_errors or []:
231
+ out += f"\n {f.path}: {f.message}"
232
+ if error.hint:
233
+ out += f"\nHint: {error.hint}"
234
+ return out
incur/_filter.py ADDED
@@ -0,0 +1,173 @@
1
+ """Output filtering with `--filter-output` key paths such as `foo,bar.baz,a[0,3]`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import math
7
+ from dataclasses import dataclass
8
+ from typing import TypeAlias
9
+
10
+ from . import _js
11
+ from ._js import Json
12
+
13
+
14
+ @dataclass
15
+ class Slice:
16
+ """An array slice from `start` (inclusive) to `end` (exclusive)."""
17
+
18
+ start: float
19
+ end: float
20
+
21
+
22
+ #: One step of a filter path: an object key or an array slice.
23
+ Segment = str | Slice
24
+
25
+
26
+ class Missing:
27
+ """The type of `MISSING`."""
28
+
29
+
30
+ #: The `undefined` result of filtering, and the absence of command data.
31
+ MISSING = Missing()
32
+
33
+ #: A filtered value, or `MISSING`.
34
+ Filtered: TypeAlias = "Json | Missing"
35
+
36
+ _Container: TypeAlias = "list[Json] | dict[str, Json]"
37
+
38
+
39
+ def parse(expression: str) -> list[list[Segment]]:
40
+ """Parses a filter expression into paths."""
41
+ tokens: list[str] = []
42
+ current = ""
43
+ depth = 0
44
+ for ch in expression:
45
+ if ch == "[":
46
+ depth += 1
47
+ elif ch == "]":
48
+ depth -= 1
49
+ if ch == "," and depth == 0:
50
+ tokens.append(current)
51
+ current = ""
52
+ else:
53
+ current += ch
54
+ if current:
55
+ tokens.append(current)
56
+
57
+ paths: list[list[Segment]] = []
58
+ for token in tokens:
59
+ path: list[Segment] = []
60
+ remaining = token
61
+ while remaining:
62
+ open_ = remaining.find("[")
63
+ if open_ < 0:
64
+ path.extend(part for part in remaining.split(".") if part)
65
+ break
66
+ path.extend(part for part in remaining[:open_].split(".") if part)
67
+ close = remaining.find("]", open_)
68
+ inner = remaining[open_ + 1 : close if close >= 0 else len(remaining)]
69
+ bounds = inner.split(",")
70
+ start = _js.to_number(bounds[0])
71
+ end = _js.to_number(bounds[1]) if len(bounds) > 1 else math.nan
72
+ path.append(Slice(start, end))
73
+ remaining = remaining[close + 1 :] if close >= 0 else ""
74
+ remaining = remaining.removeprefix(".")
75
+ paths.append(path)
76
+ return paths
77
+
78
+
79
+ def apply(data: Json, paths: list[list[Segment]]) -> Filtered:
80
+ """Applies filter paths to a value and returns the filtered copy. `MISSING` is `undefined`."""
81
+ if len(paths) == 1 and len(paths[0]) == 1 and isinstance(paths[0][0], str):
82
+ key = paths[0][0]
83
+ if isinstance(data, list):
84
+ return [_defined(apply(item, paths)) for item in data]
85
+ if isinstance(data, dict):
86
+ value = _get(data, key)
87
+ if isinstance(value, (dict, list)):
88
+ return {key: value}
89
+ return value
90
+ return MISSING
91
+ if isinstance(data, list):
92
+ return [_defined(apply(item, paths)) for item in data]
93
+ out: dict[str, Json] = {}
94
+ for path in paths:
95
+ _merge(out, data, path, 0)
96
+ return out
97
+
98
+
99
+ def _defined(value: Filtered) -> Json:
100
+ return None if isinstance(value, Missing) else value
101
+
102
+
103
+ def _merge(target: _Container, data: Json, segments: list[Segment], index: int) -> None:
104
+ """Copies the value at `segments[index:]` from `data` into `target`, an object or array."""
105
+ key = segments[index] if index < len(segments) else None
106
+ if not isinstance(key, str):
107
+ return
108
+ value = _get(data, key)
109
+ if isinstance(value, Missing):
110
+ return
111
+ nxt = segments[index + 1] if index + 1 < len(segments) else None
112
+ if nxt is None:
113
+ _set(target, key, copy.deepcopy(value))
114
+ elif isinstance(nxt, Slice):
115
+ if not isinstance(value, list):
116
+ return
117
+ begin = _js.relative_index(nxt.start, len(value))
118
+ stop = _js.relative_index(nxt.end, len(value))
119
+ sliced = value[begin:stop]
120
+ if index + 2 >= len(segments):
121
+ _set(target, key, copy.deepcopy(sliced))
122
+ return
123
+ mapped: list[Json] = []
124
+ for item in sliced:
125
+ sub: dict[str, Json] = {}
126
+ _merge(sub, item, segments, index + 2)
127
+ mapped.append(sub)
128
+ _set(target, key, mapped)
129
+ else:
130
+ if not isinstance(value, (dict, list)):
131
+ return
132
+ # Existing objects and arrays are reused; anything else is replaced.
133
+ if not isinstance(_entry(target, key), (dict, list)):
134
+ _set(target, key, {})
135
+ entry = _entry(target, key)
136
+ assert isinstance(entry, (dict, list))
137
+ _merge(entry, value, segments, index + 1)
138
+
139
+
140
+ def _get(data: Json, key: str) -> Filtered:
141
+ """Reads a property as JavaScript does: object keys, and the indices and `length` of arrays."""
142
+ if isinstance(data, list):
143
+ if key == "length":
144
+ return len(data)
145
+ return _entry(data, key)
146
+ if isinstance(data, dict):
147
+ return _entry(data, key)
148
+ return MISSING
149
+
150
+
151
+ def _entry(target: _Container, key: str) -> Filtered:
152
+ """Returns an object property or array element."""
153
+ if isinstance(target, list):
154
+ index = _js.array_index(key)
155
+ return target[index] if index is not None and index < len(target) else MISSING
156
+ return target.get(key, MISSING)
157
+
158
+
159
+ def _set(target: _Container, key: str, value: Json) -> None:
160
+ """Writes a property as JavaScript does; arrays take indices and `length` only."""
161
+ if isinstance(target, dict):
162
+ target[key] = value
163
+ return
164
+ index = _js.array_index(key)
165
+ if index is not None:
166
+ if len(target) <= index:
167
+ target.extend([None] * (index + 1 - len(target)))
168
+ target[index] = value
169
+ else:
170
+ # Array targets mirror array data, whose only other readable property is `length`.
171
+ assert isinstance(value, int)
172
+ del target[value:]
173
+ target.extend([None] * (value - len(target)))
incur/_formatter.py ADDED
@@ -0,0 +1,112 @@
1
+ """Output serialization in TOON, JSON, YAML, Markdown, and JSONL."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, TypeGuard
6
+
7
+ from . import _js, _toon, _yaml
8
+ from ._js import Json
9
+
10
+ #: A supported output format.
11
+ Format = Literal["toon", "json", "yaml", "md", "jsonl"]
12
+
13
+ #: Every format, in the order help output lists them.
14
+ FORMATS: tuple[Format, ...] = ("toon", "json", "yaml", "md", "jsonl")
15
+
16
+
17
+ def format_value(value: Json, fmt: Format) -> str:
18
+ """Serializes a value in the given format. `None` formats as an empty string."""
19
+ if value is None:
20
+ return ""
21
+ if fmt == "json":
22
+ if isinstance(value, str):
23
+ trimmed = _js.trim(value)
24
+ if trimmed.startswith(("{", "[")) and _js.json_parse_error(value) is None:
25
+ return _js.stringify_pretty(_js.parse_json(value))
26
+ return _js.stringify_pretty(value)
27
+ if fmt == "jsonl":
28
+ if isinstance(value, list):
29
+ return "\n".join(_js.stringify(item) for item in value)
30
+ return _js.stringify(value)
31
+ if fmt == "yaml":
32
+ return _yaml.stringify(value)
33
+ if fmt == "md":
34
+ return _markdown(value)
35
+ return _toon.encode(value)
36
+
37
+
38
+ def _is_scalar(value: Json) -> bool:
39
+ return not isinstance(value, (list, dict))
40
+
41
+
42
+ def _is_flat(data: dict[str, Json]) -> bool:
43
+ return all(_is_scalar(v) for v in data.values())
44
+
45
+
46
+ def _is_array_of_objects(value: Json) -> TypeGuard[list[dict[str, Json]]]:
47
+ return isinstance(value, list) and bool(value) and all(isinstance(v, dict) for v in value)
48
+
49
+
50
+ def _pad(value: str, width: int) -> str:
51
+ return value + " " * max(width - _js.utf16_len(value), 0)
52
+
53
+
54
+ def _table(headers: list[str], rows: list[list[str]]) -> str:
55
+ """Renders an aligned Markdown table."""
56
+ widths = [
57
+ max([_js.utf16_len(row[i]) for row in rows] + [_js.utf16_len(header)])
58
+ for i, header in enumerate(headers)
59
+ ]
60
+ head = " | ".join(_pad(h, w) for h, w in zip(headers, widths, strict=True))
61
+ sep = "|".join("-" * (w + 2) for w in widths)
62
+ body = "\n".join(
63
+ "| " + " | ".join(_pad(row[i], w) for i, w in enumerate(widths)) + " |" for row in rows
64
+ )
65
+ return f"| {head} |\n|{sep}|\n{body}"
66
+
67
+
68
+ def _kv_table(data: dict[str, Json]) -> str:
69
+ return _table(["Key", "Value"], [[k, _js.to_string(v)] for k, v in data.items()])
70
+
71
+
72
+ def _columnar_table(items: list[dict[str, Json]]) -> str:
73
+ keys: list[str] = []
74
+ for item in items:
75
+ for key in item:
76
+ if key not in keys:
77
+ keys.append(key)
78
+ rows = [
79
+ ["" if item.get(key) is None else _js.to_string(item[key]) for key in keys]
80
+ for item in items
81
+ ]
82
+ return _table(keys, rows)
83
+
84
+
85
+ def _markdown(value: Json) -> str:
86
+ """Formats a value as Markdown: tables, and headed sections for nested objects."""
87
+ if _is_array_of_objects(value):
88
+ return _columnar_table(value)
89
+ if isinstance(value, dict):
90
+ return _kv_table(value) if _is_flat(value) else _sections(value, [])
91
+ return _js.to_string(value)
92
+
93
+
94
+ def _sections(data: dict[str, Json], path: list[str]) -> str:
95
+ """Formats each entry of a nested object as a section headed by its dotted path."""
96
+
97
+ def heading(child: list[str], body: str) -> str:
98
+ return f"## {'.'.join(child)}\n\n{body}"
99
+
100
+ out: list[str] = []
101
+ for key, value in data.items():
102
+ child = [*path, key]
103
+ if isinstance(value, dict):
104
+ if _is_flat(value):
105
+ out.append(heading(child, _kv_table(value)))
106
+ else:
107
+ out.append(_sections(value, child))
108
+ elif _is_array_of_objects(value):
109
+ out.append(heading(child, _columnar_table(value)))
110
+ else:
111
+ out.append(heading(child, _js.to_string(value)))
112
+ return "\n\n".join(out)
incur/_gateway.py ADDED
@@ -0,0 +1,173 @@
1
+ """Fetch gateways: curl-style argv as HTTP requests, and responses as command output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import AsyncIterator
7
+ from dataclasses import dataclass, field
8
+
9
+ from . import _js
10
+ from ._http import Headers, Request, Response, encode_params, join_url, search_params
11
+ from ._js import Json
12
+
13
+ _RESERVED = frozenset({"method", "body", "data", "header"})
14
+ _SHORT = {"X": "method", "d": "data", "H": "header"}
15
+
16
+
17
+ @dataclass
18
+ class Input:
19
+ """A request parsed from curl-style argv."""
20
+
21
+ path: str
22
+ method: str
23
+ headers: Headers
24
+ body: str | None
25
+ query: list[tuple[str, str]] = field(default_factory=list[tuple[str, str]])
26
+
27
+
28
+ def _set(query: list[tuple[str, str]], key: str, value: str) -> None:
29
+ """Sets a query parameter as `URLSearchParams.set` does: replaces the first, drops others."""
30
+ index = next((i for i, (k, _) in enumerate(query) if k == key), None)
31
+ if index is None:
32
+ query.append((key, value))
33
+ return
34
+ query[index] = (key, value)
35
+ query[index + 1 :] = [(k, v) for k, v in query[index + 1 :] if k != key]
36
+
37
+
38
+ def parse_argv(argv: list[str]) -> Input:
39
+ """Parses curl-style argv: path segments, `--key value` query parameters, and reserved flags.
40
+
41
+ Raises:
42
+ ValueError: When a flag has no value.
43
+ """
44
+ segments: list[str] = []
45
+ headers = Headers()
46
+ query: list[tuple[str, str]] = []
47
+ method: str | None = None
48
+ body: str | None = None
49
+
50
+ def reserved(key: str, value: str) -> None:
51
+ nonlocal method, body
52
+ if key == "method":
53
+ method = value.upper()
54
+ elif key in ("body", "data"):
55
+ body = value
56
+ elif ":" in value:
57
+ name, _, rest = value.partition(":")
58
+ headers.set(_js.trim(name), _js.trim(rest))
59
+
60
+ i = 0
61
+ while i < len(argv):
62
+ token = argv[i]
63
+ if token.startswith("--"):
64
+ if "=" in token:
65
+ key, _, value = token[2:].partition("=")
66
+ i += 1
67
+ else:
68
+ key = token[2:]
69
+ if i + 1 >= len(argv):
70
+ raise ValueError(f"Missing value for --{key}")
71
+ value = argv[i + 1]
72
+ i += 2
73
+ if key in _RESERVED:
74
+ reserved(key, value)
75
+ else:
76
+ _set(query, key, value)
77
+ elif token.startswith("-") and len(token) == 2:
78
+ mapped = _SHORT.get(token[1])
79
+ if mapped is None:
80
+ # An unknown short flag stands alone.
81
+ i += 1
82
+ continue
83
+ if i + 1 >= len(argv):
84
+ raise ValueError(f"Missing value for {token}")
85
+ reserved(mapped, argv[i + 1])
86
+ i += 2
87
+ else:
88
+ segments.append(token)
89
+ i += 1
90
+ # Collapse slashes so a path token like `/users` cannot become a protocol-relative `//users`.
91
+ path = re.sub("/{2,}", "/", "/" + "/".join(segments))
92
+ return Input(path, method or ("POST" if body is not None else "GET"), headers, body, query)
93
+
94
+
95
+ def build_request(data: Input) -> Request:
96
+ """Builds the request a gateway sends."""
97
+ url = join_url("http://localhost", data.path)
98
+ query = list(search_params(url.partition("?")[2]))
99
+ for key, value in data.query:
100
+ _set(query, key, value)
101
+ base = url.partition("?")[0]
102
+ if query:
103
+ base += "?" + encode_params(query)
104
+ if data.body is not None and "content-type" not in data.headers:
105
+ data.headers.set("content-type", "application/json")
106
+ return Request(base, method=data.method, headers=data.headers, body=data.body)
107
+
108
+
109
+ def is_streaming(response: Response) -> bool:
110
+ """Whether a response streams NDJSON."""
111
+ return response.headers.get("content-type") == "application/x-ndjson"
112
+
113
+
114
+ async def stream(response: Response) -> AsyncIterator[Json]:
115
+ """Parses an NDJSON body as it arrives. Lines that are not JSON yield as text."""
116
+ buffer = ""
117
+
118
+ def value(line: str) -> Json:
119
+ return _js.parse_json(line) if _js.json_parse_error(line) is None else line
120
+
121
+ async for chunk in response.chunks():
122
+ buffer += chunk.decode("utf-8", "replace")
123
+ while "\n" in buffer:
124
+ line, _, buffer = buffer.partition("\n")
125
+ line = _js.trim(line)
126
+ if line:
127
+ yield value(line)
128
+ remaining = _js.trim(buffer)
129
+ if remaining:
130
+ yield value(remaining)
131
+
132
+
133
+ async def read(response: Response) -> Json:
134
+ """Reads a response body as JSON, or as text when it is not JSON."""
135
+ text = await response.text()
136
+ return _js.parse_json(text) if _js.json_parse_error(text) is None else text
137
+
138
+
139
+ def error_of(data: Json, status: int) -> tuple[str, str]:
140
+ """Extracts an error code and message from a failed response body."""
141
+ nested = data.get("error") if isinstance(data, dict) else None
142
+ error = nested if isinstance(nested, dict) else None
143
+ code = error.get("code") if error else None
144
+ code = code if isinstance(code, str) and code else f"HTTP_{status}"
145
+ if isinstance(data, dict) and "message" in data:
146
+ message = _js.to_string(data["message"])
147
+ elif error is not None and "message" in error:
148
+ message = _js.to_string(error["message"])
149
+ elif isinstance(data, str):
150
+ message = data
151
+ else:
152
+ message = f"HTTP {status}"
153
+ return code, message
154
+
155
+
156
+ def help_text(name: str, description: str | None) -> str:
157
+ """Renders the help of a gateway command."""
158
+ return "\n".join(
159
+ [
160
+ f"{name} \u2014 {description}" if description else name,
161
+ "",
162
+ f"Usage: {name} <path> [options]",
163
+ "",
164
+ "Path segments are joined into the request URL path.",
165
+ "",
166
+ "Options:",
167
+ " -X, --method <METHOD> HTTP method (default: GET, POST if body present)",
168
+ ' -H, --header "Key: Val" Set a request header (repeatable)',
169
+ " -d, --data <json> Request body (implies POST)",
170
+ " --body <json> Request body (implies POST)",
171
+ " --<key> <value> Query string parameter",
172
+ ]
173
+ )