xiii-cli-core 0.1.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.
- xiii_cli_core/__init__.py +1 -0
- xiii_cli_core/client.py +568 -0
- xiii_cli_core/config.py +527 -0
- xiii_cli_core/describe.py +196 -0
- xiii_cli_core/direct.py +1158 -0
- xiii_cli_core/errors.py +103 -0
- xiii_cli_core/main.py +732 -0
- xiii_cli_core/oauth.py +750 -0
- xiii_cli_core/openapi.py +643 -0
- xiii_cli_core/py.typed +0 -0
- xiii_cli_core/render.py +44 -0
- xiii_cli_core/skill.py +89 -0
- xiii_cli_core/thread.py +230 -0
- xiii_cli_core/tokens.py +115 -0
- xiii_cli_core-0.1.0.dist-info/METADATA +86 -0
- xiii_cli_core-0.1.0.dist-info/RECORD +18 -0
- xiii_cli_core-0.1.0.dist-info/WHEEL +4 -0
- xiii_cli_core-0.1.0.dist-info/licenses/LICENSE +202 -0
xiii_cli_core/direct.py
ADDED
|
@@ -0,0 +1,1158 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
import json
|
|
5
|
+
import mimetypes
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Iterator
|
|
9
|
+
from contextlib import ExitStack
|
|
10
|
+
from decimal import Decimal, InvalidOperation
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Annotated, Any, BinaryIO, Literal
|
|
13
|
+
from urllib.parse import quote, unquote, urlsplit
|
|
14
|
+
|
|
15
|
+
from cyclopts import App, Group, Parameter
|
|
16
|
+
from rich.console import Console
|
|
17
|
+
from rich.prompt import Confirm
|
|
18
|
+
|
|
19
|
+
from xiii_cli_core.client import ApiClient, ApiDownloadResult, ApiResult
|
|
20
|
+
from xiii_cli_core.config import Product, Surface
|
|
21
|
+
from xiii_cli_core.errors import CliError, ConfigurationError, UsageError
|
|
22
|
+
from xiii_cli_core.openapi import MANIFEST_VERSION
|
|
23
|
+
from xiii_cli_core.render import render_json, render_rows
|
|
24
|
+
from xiii_cli_core.tokens import get_token
|
|
25
|
+
|
|
26
|
+
console = Console()
|
|
27
|
+
MODULE_GROUP = Group("Product modules", sort_key=20)
|
|
28
|
+
HTTP_METHODS = Literal["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"]
|
|
29
|
+
MAX_JSON_INPUT_BYTES = 10 * 1024 * 1024
|
|
30
|
+
JSON_HELP = (
|
|
31
|
+
"Print the result as JSON on stdout; a failure is one JSON object on stderr "
|
|
32
|
+
"with error, code, detail and exit_code."
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def register_module_commands(
|
|
37
|
+
app: App,
|
|
38
|
+
product: Product,
|
|
39
|
+
surface: Surface,
|
|
40
|
+
*,
|
|
41
|
+
connection_type: type,
|
|
42
|
+
default_connection: Any,
|
|
43
|
+
) -> dict[str, App]:
|
|
44
|
+
"""Register every PAT-protected product operation from its generated manifest.
|
|
45
|
+
|
|
46
|
+
Returns the module apps by name so an entrypoint can add a hand-written
|
|
47
|
+
command to a generated group — `workspace use` is local-only and has no
|
|
48
|
+
operation in the manifest to be generated from.
|
|
49
|
+
"""
|
|
50
|
+
manifest = load_manifest(product)
|
|
51
|
+
module_apps: dict[str, App] = {}
|
|
52
|
+
for module in manifest["modules"]:
|
|
53
|
+
module_app = app.command(
|
|
54
|
+
App(
|
|
55
|
+
name=module["name"],
|
|
56
|
+
help=f"Direct {module['name']} API operations.",
|
|
57
|
+
group=MODULE_GROUP,
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
module_apps[module["name"]] = module_app
|
|
61
|
+
for operation in module["operations"]:
|
|
62
|
+
command = _build_command(
|
|
63
|
+
product,
|
|
64
|
+
surface,
|
|
65
|
+
operation,
|
|
66
|
+
connection_type=connection_type,
|
|
67
|
+
default_connection=default_connection,
|
|
68
|
+
)
|
|
69
|
+
module_app.command(command, name=operation["name"])
|
|
70
|
+
return module_apps
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def load_manifest(product: Product) -> dict[str, Any]:
|
|
74
|
+
try:
|
|
75
|
+
payload = json.loads(product.manifest.read_text(encoding="utf-8"))
|
|
76
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
77
|
+
raise ConfigurationError(
|
|
78
|
+
f"Could not load the {product.name} CLI contract: {exc}"
|
|
79
|
+
) from exc
|
|
80
|
+
if not isinstance(payload, dict):
|
|
81
|
+
raise ConfigurationError("CLI contract root must be an object")
|
|
82
|
+
if payload.get("manifest_version") != MANIFEST_VERSION:
|
|
83
|
+
raise ConfigurationError(
|
|
84
|
+
f"Unsupported CLI contract version {payload.get('manifest_version')}"
|
|
85
|
+
)
|
|
86
|
+
if payload.get("product") != product.name:
|
|
87
|
+
raise ConfigurationError(
|
|
88
|
+
f"CLI contract for {payload.get('product')} loaded as {product.name}"
|
|
89
|
+
)
|
|
90
|
+
modules = payload.get("modules")
|
|
91
|
+
if not isinstance(modules, list):
|
|
92
|
+
raise ConfigurationError("CLI contract has no modules list")
|
|
93
|
+
return payload
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def run_raw_api(
|
|
97
|
+
*,
|
|
98
|
+
endpoint: str,
|
|
99
|
+
method: str,
|
|
100
|
+
fields: list[str],
|
|
101
|
+
raw_fields: list[str],
|
|
102
|
+
params: list[str],
|
|
103
|
+
input_file: str | None,
|
|
104
|
+
content_type: str,
|
|
105
|
+
output: Path | None,
|
|
106
|
+
overwrite: bool,
|
|
107
|
+
yes: bool,
|
|
108
|
+
dry_run: bool,
|
|
109
|
+
json_output: bool,
|
|
110
|
+
connection: Any,
|
|
111
|
+
product: Product,
|
|
112
|
+
surface: Surface,
|
|
113
|
+
) -> None:
|
|
114
|
+
path = validate_relative_endpoint(endpoint)
|
|
115
|
+
normalized_method = method.upper()
|
|
116
|
+
if normalized_method not in HTTP_METHODS.__args__:
|
|
117
|
+
raise CliError(f"Unsupported HTTP method {method}")
|
|
118
|
+
streaming_operations = load_manifest(product).get(
|
|
119
|
+
"excluded_event_stream_operations", []
|
|
120
|
+
)
|
|
121
|
+
request_path = _decoded_route_path(urlsplit(path).path)
|
|
122
|
+
if any(
|
|
123
|
+
operation.get("method") == normalized_method
|
|
124
|
+
and _operation_path_matches(operation.get("path"), request_path)
|
|
125
|
+
for operation in streaming_operations
|
|
126
|
+
if isinstance(operation, dict)
|
|
127
|
+
):
|
|
128
|
+
raise CliError(
|
|
129
|
+
f"{normalized_method} {request_path} is an agent event stream; "
|
|
130
|
+
f"use `{product.name} agent run` so SSE and HITL are handled safely"
|
|
131
|
+
)
|
|
132
|
+
query = _parse_assignments(params, typed=True)
|
|
133
|
+
body_fields = dict(_parse_assignments(fields, typed=True))
|
|
134
|
+
body_fields.update(_parse_assignments(raw_fields, typed=False))
|
|
135
|
+
if input_file is not None and body_fields:
|
|
136
|
+
raise CliError("--input cannot be combined with --field or --raw-field")
|
|
137
|
+
body: Any = body_fields or None
|
|
138
|
+
content_input: str | None = None
|
|
139
|
+
if input_file is not None:
|
|
140
|
+
if content_type == "application/json":
|
|
141
|
+
raw = _read_input(input_file)
|
|
142
|
+
try:
|
|
143
|
+
body = json.loads(raw)
|
|
144
|
+
except json.JSONDecodeError as exc:
|
|
145
|
+
raise CliError(f"--input is not valid JSON: {exc}") from exc
|
|
146
|
+
else:
|
|
147
|
+
content_input = input_file
|
|
148
|
+
|
|
149
|
+
preview = {
|
|
150
|
+
"method": normalized_method,
|
|
151
|
+
"path": path,
|
|
152
|
+
"params": query,
|
|
153
|
+
"content_type": (
|
|
154
|
+
content_type if content_input is not None else "application/json"
|
|
155
|
+
),
|
|
156
|
+
"body": (
|
|
157
|
+
"<redacted>"
|
|
158
|
+
if body is not None
|
|
159
|
+
else "<redacted input>"
|
|
160
|
+
if content_input is not None
|
|
161
|
+
else None
|
|
162
|
+
),
|
|
163
|
+
}
|
|
164
|
+
if dry_run:
|
|
165
|
+
render_json(preview)
|
|
166
|
+
return
|
|
167
|
+
_confirm_if_dangerous(
|
|
168
|
+
dangerous=normalized_method not in {"GET", "HEAD"},
|
|
169
|
+
yes=yes,
|
|
170
|
+
description=f"{normalized_method} {path}",
|
|
171
|
+
)
|
|
172
|
+
config = connection.resolve(product, surface)
|
|
173
|
+
token, _source = get_token(config)
|
|
174
|
+
headers = {"Content-Type": content_type} if content_input is not None else None
|
|
175
|
+
redact_values = _body_strings(body)
|
|
176
|
+
content = _input_chunks(content_input) if content_input is not None else None
|
|
177
|
+
with ApiClient(config, token) as client:
|
|
178
|
+
request_arguments = {
|
|
179
|
+
"params": query,
|
|
180
|
+
"json": body if content is None else None,
|
|
181
|
+
"headers": headers,
|
|
182
|
+
"content": content,
|
|
183
|
+
"redact_values": redact_values,
|
|
184
|
+
}
|
|
185
|
+
if output is not None:
|
|
186
|
+
download = client.request_to_file(
|
|
187
|
+
normalized_method,
|
|
188
|
+
path,
|
|
189
|
+
output,
|
|
190
|
+
overwrite=overwrite,
|
|
191
|
+
**request_arguments,
|
|
192
|
+
)
|
|
193
|
+
_render_download(download, json_output=json_output)
|
|
194
|
+
return
|
|
195
|
+
result = client.request_result(normalized_method, path, **request_arguments)
|
|
196
|
+
render_api_result(result, json_output=json_output, output=None, overwrite=False)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def validate_relative_endpoint(endpoint: str) -> str:
|
|
200
|
+
value = endpoint.strip()
|
|
201
|
+
parsed = urlsplit(value)
|
|
202
|
+
if parsed.scheme or parsed.netloc or value.startswith("//"):
|
|
203
|
+
raise CliError("API endpoint must be relative to the configured product API")
|
|
204
|
+
if parsed.fragment:
|
|
205
|
+
raise CliError("API endpoint must not contain a fragment")
|
|
206
|
+
path = parsed.path if parsed.path.startswith("/") else f"/{parsed.path}"
|
|
207
|
+
if not path.strip("/"):
|
|
208
|
+
raise CliError("API endpoint must name a route")
|
|
209
|
+
decoded_path = _decoded_route_path(path)
|
|
210
|
+
if any(segment == ".." for segment in decoded_path.split("/")):
|
|
211
|
+
raise CliError("API endpoint must not contain parent path segments")
|
|
212
|
+
return f"{path}?{parsed.query}" if parsed.query else path
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _decoded_route_path(path: str) -> str:
|
|
216
|
+
decoded = path
|
|
217
|
+
for _round in range(8):
|
|
218
|
+
candidate = unquote(decoded).replace("\\", "/")
|
|
219
|
+
if candidate == decoded:
|
|
220
|
+
return candidate
|
|
221
|
+
decoded = candidate
|
|
222
|
+
if unquote(decoded).replace("\\", "/") != decoded:
|
|
223
|
+
raise CliError("API endpoint contains excessive nested encoding")
|
|
224
|
+
return decoded
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _operation_path_matches(template: Any, path: str) -> bool:
|
|
228
|
+
if not isinstance(template, str):
|
|
229
|
+
return False
|
|
230
|
+
template_segments = template.strip("/").split("/")
|
|
231
|
+
path_segments = path.strip("/").split("/")
|
|
232
|
+
return len(template_segments) == len(path_segments) and all(
|
|
233
|
+
template_segment == path_segment
|
|
234
|
+
or (template_segment.startswith("{") and template_segment.endswith("}"))
|
|
235
|
+
for template_segment, path_segment in zip(
|
|
236
|
+
template_segments, path_segments, strict=True
|
|
237
|
+
)
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def render_api_result(
|
|
242
|
+
result: ApiResult,
|
|
243
|
+
*,
|
|
244
|
+
json_output: bool,
|
|
245
|
+
output: Path | None,
|
|
246
|
+
overwrite: bool,
|
|
247
|
+
) -> None:
|
|
248
|
+
if output is not None:
|
|
249
|
+
raise CliError(
|
|
250
|
+
"Buffered output is disabled; use the streaming request output path"
|
|
251
|
+
)
|
|
252
|
+
if result.is_binary:
|
|
253
|
+
suggestion = result.filename or "response.bin"
|
|
254
|
+
raise CliError(
|
|
255
|
+
f"API returned {result.content_type or 'binary data'}; pass "
|
|
256
|
+
f"--output {suggestion}"
|
|
257
|
+
)
|
|
258
|
+
# An empty body is an answer of its own; a JSON `null` (no running timer,
|
|
259
|
+
# say) is data and is printed as such.
|
|
260
|
+
if not result.content and json_output:
|
|
261
|
+
render_json({"status": "completed", "status_code": result.status_code})
|
|
262
|
+
elif not result.content:
|
|
263
|
+
console.print(f"[green]Completed[/green] (HTTP {result.status_code})")
|
|
264
|
+
elif json_output:
|
|
265
|
+
render_json(result.payload())
|
|
266
|
+
else:
|
|
267
|
+
render_rows(result.payload())
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _render_download(download: ApiDownloadResult, *, json_output: bool) -> None:
|
|
271
|
+
if json_output:
|
|
272
|
+
render_json(
|
|
273
|
+
{
|
|
274
|
+
"status": "saved",
|
|
275
|
+
"status_code": download.status_code,
|
|
276
|
+
"output": str(download.output.resolve()),
|
|
277
|
+
"bytes_written": download.bytes_written,
|
|
278
|
+
"content_type": download.content_type,
|
|
279
|
+
"filename": download.filename,
|
|
280
|
+
}
|
|
281
|
+
)
|
|
282
|
+
return
|
|
283
|
+
console.print(
|
|
284
|
+
f"[green]Saved[/green] {download.bytes_written} bytes to {download.output}"
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _build_command(
|
|
289
|
+
product: Product,
|
|
290
|
+
surface: Surface,
|
|
291
|
+
operation: dict[str, Any],
|
|
292
|
+
*,
|
|
293
|
+
connection_type: type,
|
|
294
|
+
default_connection: Any,
|
|
295
|
+
):
|
|
296
|
+
path_parameters = [
|
|
297
|
+
parameter
|
|
298
|
+
for parameter in operation["parameters"]
|
|
299
|
+
if parameter["location"] == "path"
|
|
300
|
+
]
|
|
301
|
+
signature = _command_signature(
|
|
302
|
+
operation,
|
|
303
|
+
connection_type=connection_type,
|
|
304
|
+
default_connection=default_connection,
|
|
305
|
+
)
|
|
306
|
+
defaults = {
|
|
307
|
+
name: parameter.default
|
|
308
|
+
for name, parameter in signature.parameters.items()
|
|
309
|
+
if parameter.default is not inspect.Parameter.empty
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
def command(*args: Any, **kwargs: Any) -> None:
|
|
313
|
+
values = dict(defaults)
|
|
314
|
+
values.update(
|
|
315
|
+
zip(
|
|
316
|
+
(item["argument"] for item in path_parameters),
|
|
317
|
+
args,
|
|
318
|
+
strict=True,
|
|
319
|
+
)
|
|
320
|
+
)
|
|
321
|
+
values.update(kwargs)
|
|
322
|
+
_run_operation(product, surface, operation, values)
|
|
323
|
+
|
|
324
|
+
command.__name__ = operation["operation_id"]
|
|
325
|
+
command.__doc__ = _command_help(operation)
|
|
326
|
+
command_with_signature: Any = command
|
|
327
|
+
command_with_signature.__signature__ = signature
|
|
328
|
+
return command
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _command_signature(
|
|
332
|
+
operation: dict[str, Any], *, connection_type: type, default_connection: Any
|
|
333
|
+
) -> inspect.Signature:
|
|
334
|
+
parameters: list[inspect.Parameter] = []
|
|
335
|
+
for parameter in operation["parameters"]:
|
|
336
|
+
if parameter["location"] != "path":
|
|
337
|
+
continue
|
|
338
|
+
parameters.append(
|
|
339
|
+
inspect.Parameter(
|
|
340
|
+
parameter["argument"],
|
|
341
|
+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
|
342
|
+
annotation=_field_annotation(parameter, positional=True),
|
|
343
|
+
)
|
|
344
|
+
)
|
|
345
|
+
for parameter in operation["parameters"]:
|
|
346
|
+
if parameter["location"] == "path":
|
|
347
|
+
continue
|
|
348
|
+
parameters.append(
|
|
349
|
+
inspect.Parameter(
|
|
350
|
+
parameter["argument"],
|
|
351
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
352
|
+
annotation=_field_annotation(parameter),
|
|
353
|
+
default=inspect.Parameter.empty if parameter["required"] else None,
|
|
354
|
+
)
|
|
355
|
+
)
|
|
356
|
+
body = operation.get("body")
|
|
357
|
+
if isinstance(body, dict):
|
|
358
|
+
for field in body["properties"]:
|
|
359
|
+
if field.get("sensitive"):
|
|
360
|
+
continue
|
|
361
|
+
parameters.append(
|
|
362
|
+
inspect.Parameter(
|
|
363
|
+
f"body_{field['argument']}",
|
|
364
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
365
|
+
annotation=_field_annotation(field, body=True),
|
|
366
|
+
default=None,
|
|
367
|
+
)
|
|
368
|
+
)
|
|
369
|
+
if body["content_type"] == "application/json":
|
|
370
|
+
parameters.append(
|
|
371
|
+
inspect.Parameter(
|
|
372
|
+
"input_file",
|
|
373
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
374
|
+
annotation=Annotated[
|
|
375
|
+
str | None,
|
|
376
|
+
Parameter(
|
|
377
|
+
name="--input",
|
|
378
|
+
help="Read the complete JSON body from FILE; use - for stdin.",
|
|
379
|
+
),
|
|
380
|
+
],
|
|
381
|
+
default=None,
|
|
382
|
+
)
|
|
383
|
+
)
|
|
384
|
+
parameters.extend(
|
|
385
|
+
[
|
|
386
|
+
inspect.Parameter(
|
|
387
|
+
"output",
|
|
388
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
389
|
+
annotation=Annotated[
|
|
390
|
+
Path | None,
|
|
391
|
+
Parameter(help="Write the raw response body to FILE."),
|
|
392
|
+
],
|
|
393
|
+
default=None,
|
|
394
|
+
),
|
|
395
|
+
inspect.Parameter(
|
|
396
|
+
"overwrite",
|
|
397
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
398
|
+
annotation=Annotated[
|
|
399
|
+
bool,
|
|
400
|
+
Parameter(
|
|
401
|
+
negative=(),
|
|
402
|
+
help="Replace an existing --output file.",
|
|
403
|
+
),
|
|
404
|
+
],
|
|
405
|
+
default=False,
|
|
406
|
+
),
|
|
407
|
+
]
|
|
408
|
+
)
|
|
409
|
+
if operation.get("pagination"):
|
|
410
|
+
parameters.extend(
|
|
411
|
+
[
|
|
412
|
+
inspect.Parameter(
|
|
413
|
+
"all_pages",
|
|
414
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
415
|
+
annotation=Annotated[
|
|
416
|
+
bool,
|
|
417
|
+
Parameter(
|
|
418
|
+
name="--all",
|
|
419
|
+
negative=(),
|
|
420
|
+
help=(
|
|
421
|
+
"Fetch every page and print one object {items, total}."
|
|
422
|
+
),
|
|
423
|
+
),
|
|
424
|
+
],
|
|
425
|
+
default=False,
|
|
426
|
+
),
|
|
427
|
+
inspect.Parameter(
|
|
428
|
+
"max_items",
|
|
429
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
430
|
+
annotation=Annotated[
|
|
431
|
+
int | None,
|
|
432
|
+
Parameter(
|
|
433
|
+
name="--max-items",
|
|
434
|
+
help="Stop --all after this many items.",
|
|
435
|
+
),
|
|
436
|
+
],
|
|
437
|
+
default=None,
|
|
438
|
+
),
|
|
439
|
+
]
|
|
440
|
+
)
|
|
441
|
+
if operation["dangerous"]:
|
|
442
|
+
parameters.append(
|
|
443
|
+
inspect.Parameter(
|
|
444
|
+
"yes",
|
|
445
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
446
|
+
annotation=Annotated[
|
|
447
|
+
bool,
|
|
448
|
+
Parameter(
|
|
449
|
+
negative=(),
|
|
450
|
+
help="Skip the mutating-operation confirmation.",
|
|
451
|
+
),
|
|
452
|
+
],
|
|
453
|
+
default=False,
|
|
454
|
+
)
|
|
455
|
+
)
|
|
456
|
+
if operation["method"] != "GET":
|
|
457
|
+
parameters.append(
|
|
458
|
+
inspect.Parameter(
|
|
459
|
+
"dry_run",
|
|
460
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
461
|
+
annotation=Annotated[
|
|
462
|
+
bool,
|
|
463
|
+
Parameter(
|
|
464
|
+
name="--dry-run",
|
|
465
|
+
negative=(),
|
|
466
|
+
help="Show the request without sending it.",
|
|
467
|
+
),
|
|
468
|
+
],
|
|
469
|
+
default=False,
|
|
470
|
+
)
|
|
471
|
+
)
|
|
472
|
+
parameters.extend(
|
|
473
|
+
[
|
|
474
|
+
inspect.Parameter(
|
|
475
|
+
"json_output",
|
|
476
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
477
|
+
annotation=Annotated[
|
|
478
|
+
bool,
|
|
479
|
+
Parameter(name="--json", negative=(), help=JSON_HELP),
|
|
480
|
+
],
|
|
481
|
+
default=False,
|
|
482
|
+
),
|
|
483
|
+
inspect.Parameter(
|
|
484
|
+
"connection",
|
|
485
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
486
|
+
annotation=connection_type,
|
|
487
|
+
default=default_connection,
|
|
488
|
+
),
|
|
489
|
+
]
|
|
490
|
+
)
|
|
491
|
+
return inspect.Signature(parameters)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _run_operation(
|
|
495
|
+
product: Product,
|
|
496
|
+
surface: Surface,
|
|
497
|
+
operation: dict[str, Any],
|
|
498
|
+
values: dict[str, Any],
|
|
499
|
+
) -> None:
|
|
500
|
+
path = operation["path"]
|
|
501
|
+
query: list[tuple[str, Any]] = []
|
|
502
|
+
headers: dict[str, str] = {}
|
|
503
|
+
for parameter in operation["parameters"]:
|
|
504
|
+
value = values.get(parameter["argument"])
|
|
505
|
+
if value is None:
|
|
506
|
+
continue
|
|
507
|
+
_validate_value(parameter, value)
|
|
508
|
+
if parameter["location"] == "path":
|
|
509
|
+
path = path.replace(f"{{{parameter['name']}}}", quote(str(value), safe=""))
|
|
510
|
+
elif parameter["location"] == "query":
|
|
511
|
+
_append_values(query, parameter["name"], value)
|
|
512
|
+
else:
|
|
513
|
+
headers[parameter["name"]] = _wire_scalar(value)
|
|
514
|
+
if "{" in path or "}" in path:
|
|
515
|
+
raise CliError(f"Not all path parameters were provided for {path}")
|
|
516
|
+
|
|
517
|
+
body_spec = operation.get("body")
|
|
518
|
+
json_body: Any = None
|
|
519
|
+
data: dict[str, Any] | None = None
|
|
520
|
+
files: list[tuple[str, Any]] | None = None
|
|
521
|
+
body_values: dict[str, Any] = {}
|
|
522
|
+
if isinstance(body_spec, dict):
|
|
523
|
+
body_values = {
|
|
524
|
+
field["name"]: values.get(f"body_{field['argument']}")
|
|
525
|
+
for field in body_spec["properties"]
|
|
526
|
+
if values.get(f"body_{field['argument']}") is not None
|
|
527
|
+
}
|
|
528
|
+
input_file = values.get("input_file")
|
|
529
|
+
if input_file is not None and body_values:
|
|
530
|
+
raise CliError("--input cannot be combined with body field options")
|
|
531
|
+
if input_file is not None:
|
|
532
|
+
try:
|
|
533
|
+
json_body = json.loads(_read_input(input_file))
|
|
534
|
+
except json.JSONDecodeError as exc:
|
|
535
|
+
raise CliError(f"--input is not valid JSON: {exc}") from exc
|
|
536
|
+
_validate_json_schema(
|
|
537
|
+
json_body,
|
|
538
|
+
body_spec.get("schema", {}),
|
|
539
|
+
label="--input",
|
|
540
|
+
)
|
|
541
|
+
else:
|
|
542
|
+
if body_spec["required"] and not body_spec["structured"]:
|
|
543
|
+
raise CliError("This operation requires a request body; pass --input")
|
|
544
|
+
sensitive_required = [
|
|
545
|
+
field["name"]
|
|
546
|
+
for field in body_spec["properties"]
|
|
547
|
+
if field["required"] and field.get("sensitive")
|
|
548
|
+
]
|
|
549
|
+
if sensitive_required:
|
|
550
|
+
fields = ", ".join(sensitive_required)
|
|
551
|
+
raise CliError(
|
|
552
|
+
f"Required sensitive body field(s) {fields} must be read via --input"
|
|
553
|
+
)
|
|
554
|
+
missing = [
|
|
555
|
+
field["option"]
|
|
556
|
+
for field in body_spec["properties"]
|
|
557
|
+
if field["required"] and field["name"] not in body_values
|
|
558
|
+
]
|
|
559
|
+
if missing:
|
|
560
|
+
flags = ", ".join(f"--{name}" for name in missing)
|
|
561
|
+
raise CliError(
|
|
562
|
+
f"Missing required body options: {flags}; alternatively pass --input"
|
|
563
|
+
)
|
|
564
|
+
for field in body_spec["properties"]:
|
|
565
|
+
if field["name"] in body_values:
|
|
566
|
+
_validate_value(field, body_values[field["name"]])
|
|
567
|
+
if body_spec["content_type"] == "application/json":
|
|
568
|
+
json_body = {
|
|
569
|
+
field["name"]: _json_value(field, body_values[field["name"]])
|
|
570
|
+
for field in body_spec["properties"]
|
|
571
|
+
if field["name"] in body_values
|
|
572
|
+
}
|
|
573
|
+
_validate_json_schema(
|
|
574
|
+
json_body,
|
|
575
|
+
body_spec.get("schema", {}),
|
|
576
|
+
label="request body",
|
|
577
|
+
)
|
|
578
|
+
|
|
579
|
+
preview = {
|
|
580
|
+
"operation_id": operation["operation_id"],
|
|
581
|
+
"method": operation["method"],
|
|
582
|
+
"path": path,
|
|
583
|
+
"params": query,
|
|
584
|
+
"body": _redact_json_body(
|
|
585
|
+
json_body if json_body is not None else body_values or None,
|
|
586
|
+
body_spec.get("schema", {}) if isinstance(body_spec, dict) else {},
|
|
587
|
+
),
|
|
588
|
+
}
|
|
589
|
+
all_pages = values.get("all_pages", False)
|
|
590
|
+
max_items = values.get("max_items")
|
|
591
|
+
if max_items is not None and not all_pages:
|
|
592
|
+
raise UsageError("--max-items only applies together with --all")
|
|
593
|
+
if max_items is not None and max_items < 1:
|
|
594
|
+
raise UsageError("--max-items must be at least 1")
|
|
595
|
+
if all_pages and values.get("output") is not None:
|
|
596
|
+
raise UsageError("--all prints JSON and cannot be combined with --output")
|
|
597
|
+
if values.get("dry_run", False):
|
|
598
|
+
render_json(preview)
|
|
599
|
+
return
|
|
600
|
+
_confirm_if_dangerous(
|
|
601
|
+
dangerous=operation["dangerous"],
|
|
602
|
+
yes=values.get("yes", False),
|
|
603
|
+
description=f"{operation['method']} {path}",
|
|
604
|
+
)
|
|
605
|
+
connection = values["connection"]
|
|
606
|
+
config = connection.resolve(product, surface)
|
|
607
|
+
token, _source = get_token(config)
|
|
608
|
+
with ExitStack() as stack:
|
|
609
|
+
if (
|
|
610
|
+
isinstance(body_spec, dict)
|
|
611
|
+
and body_spec["content_type"] == "multipart/form-data"
|
|
612
|
+
):
|
|
613
|
+
data, files = _multipart_payload(body_spec, body_values, stack)
|
|
614
|
+
with ApiClient(config, token) as client:
|
|
615
|
+
request_arguments = {
|
|
616
|
+
"params": query,
|
|
617
|
+
"json": json_body,
|
|
618
|
+
"data": data,
|
|
619
|
+
"files": files,
|
|
620
|
+
"headers": headers or None,
|
|
621
|
+
"redact_values": _sensitive_body_strings(
|
|
622
|
+
json_body if json_body is not None else body_values,
|
|
623
|
+
body_spec.get("schema", {}) if isinstance(body_spec, dict) else {},
|
|
624
|
+
),
|
|
625
|
+
}
|
|
626
|
+
if all_pages:
|
|
627
|
+
collected = _collect_pages(
|
|
628
|
+
client,
|
|
629
|
+
operation,
|
|
630
|
+
path,
|
|
631
|
+
query,
|
|
632
|
+
request_arguments,
|
|
633
|
+
max_items=max_items,
|
|
634
|
+
)
|
|
635
|
+
elif values["output"] is not None:
|
|
636
|
+
download = client.request_to_file(
|
|
637
|
+
operation["method"],
|
|
638
|
+
path,
|
|
639
|
+
values["output"],
|
|
640
|
+
overwrite=values["overwrite"],
|
|
641
|
+
**request_arguments,
|
|
642
|
+
)
|
|
643
|
+
_render_download(download, json_output=values["json_output"])
|
|
644
|
+
return
|
|
645
|
+
else:
|
|
646
|
+
result = client.request_result(
|
|
647
|
+
operation["method"], path, **request_arguments
|
|
648
|
+
)
|
|
649
|
+
if all_pages:
|
|
650
|
+
render_json(collected) if values["json_output"] else render_rows(collected)
|
|
651
|
+
return
|
|
652
|
+
render_api_result(
|
|
653
|
+
result, json_output=values["json_output"], output=None, overwrite=False
|
|
654
|
+
)
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def _collect_pages(
|
|
658
|
+
client: ApiClient,
|
|
659
|
+
operation: dict[str, Any],
|
|
660
|
+
path: str,
|
|
661
|
+
query: list[tuple[str, Any]],
|
|
662
|
+
request_arguments: dict[str, Any],
|
|
663
|
+
*,
|
|
664
|
+
max_items: int | None,
|
|
665
|
+
) -> dict[str, Any]:
|
|
666
|
+
"""Follow `has_more` from the requested offset and merge the pages.
|
|
667
|
+
|
|
668
|
+
Without `--limit` each page is as large as the API allows, so a long list
|
|
669
|
+
costs as few requests as possible.
|
|
670
|
+
"""
|
|
671
|
+
items_key = operation["pagination"]["items"]
|
|
672
|
+
page_size = next(
|
|
673
|
+
parameter["schema"].get("maximum")
|
|
674
|
+
for parameter in operation["parameters"]
|
|
675
|
+
if parameter["name"] == "limit"
|
|
676
|
+
)
|
|
677
|
+
base = [(key, value) for key, value in query if key not in {"limit", "offset"}]
|
|
678
|
+
given = {key: value for key, value in query if key in {"limit", "offset"}}
|
|
679
|
+
limit = given.get("limit") or page_size
|
|
680
|
+
offset = int(given.get("offset") or 0)
|
|
681
|
+
items: list[Any] = []
|
|
682
|
+
total: Any = None
|
|
683
|
+
while True:
|
|
684
|
+
page_query = [
|
|
685
|
+
*base,
|
|
686
|
+
*([("limit", limit)] if limit is not None else []),
|
|
687
|
+
("offset", str(offset)),
|
|
688
|
+
]
|
|
689
|
+
payload = client.request_result(
|
|
690
|
+
operation["method"],
|
|
691
|
+
path,
|
|
692
|
+
**{**request_arguments, "params": page_query},
|
|
693
|
+
).payload()
|
|
694
|
+
page = payload.get(items_key) if isinstance(payload, dict) else None
|
|
695
|
+
if not isinstance(page, list) or not isinstance(payload.get("has_more"), bool):
|
|
696
|
+
raise CliError(
|
|
697
|
+
f"{operation['operation_id']} did not answer with a page of "
|
|
698
|
+
f"`{items_key}` and `has_more`"
|
|
699
|
+
)
|
|
700
|
+
items.extend(page)
|
|
701
|
+
total = payload.get("total", total)
|
|
702
|
+
if max_items is not None and len(items) >= max_items:
|
|
703
|
+
return {"items": items[:max_items], "total": total}
|
|
704
|
+
if not payload["has_more"] or not page:
|
|
705
|
+
return {"items": items, "total": total}
|
|
706
|
+
offset += len(page)
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def _field_annotation(
|
|
710
|
+
field: dict[str, Any], *, positional: bool = False, body: bool = False
|
|
711
|
+
) -> Any:
|
|
712
|
+
schema = field["schema"]
|
|
713
|
+
base = _python_type(schema)
|
|
714
|
+
if not field.get("required") or body:
|
|
715
|
+
base = base | None
|
|
716
|
+
help_text = field.get("description") or _field_help(field)
|
|
717
|
+
if positional:
|
|
718
|
+
return Annotated[base, Parameter(help=help_text)]
|
|
719
|
+
return Annotated[
|
|
720
|
+
base,
|
|
721
|
+
Parameter(name=f"--{field['option']}", help=help_text),
|
|
722
|
+
]
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def _python_type(schema: dict[str, Any]) -> Any:
|
|
726
|
+
kind = schema.get("kind")
|
|
727
|
+
if kind == "enum":
|
|
728
|
+
return Literal[*schema["values"]]
|
|
729
|
+
if kind == "integer":
|
|
730
|
+
return int
|
|
731
|
+
if kind == "number":
|
|
732
|
+
return float
|
|
733
|
+
if kind == "decimal":
|
|
734
|
+
return str
|
|
735
|
+
if kind == "boolean":
|
|
736
|
+
return bool
|
|
737
|
+
if kind == "file":
|
|
738
|
+
return Path
|
|
739
|
+
if kind == "array":
|
|
740
|
+
return list[_python_type(schema["items"])]
|
|
741
|
+
return str
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
def _field_help(field: dict[str, Any]) -> str:
|
|
745
|
+
schema = field["schema"]
|
|
746
|
+
parts = [field["name"].replace("_", " ").capitalize()]
|
|
747
|
+
if field.get("required"):
|
|
748
|
+
parts.append("required")
|
|
749
|
+
if "default" in schema:
|
|
750
|
+
parts.append(f"default: {schema['default']}")
|
|
751
|
+
if schema.get("kind") == "json":
|
|
752
|
+
parts.append("JSON value")
|
|
753
|
+
return f"{' ('.join(parts)}{')' if len(parts) > 1 else ''}."
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def _command_help(operation: dict[str, Any]) -> str:
|
|
757
|
+
description = operation.get("description") or operation["summary"]
|
|
758
|
+
return f"{description}\n\nOpenAPI operation: {operation['operation_id']}."
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _parse_assignments(values: list[str], *, typed: bool) -> list[tuple[str, Any]]:
|
|
762
|
+
parsed: list[tuple[str, Any]] = []
|
|
763
|
+
for value in values:
|
|
764
|
+
key, separator, raw = value.partition("=")
|
|
765
|
+
if not separator or not key:
|
|
766
|
+
raise CliError(f"Invalid value `{value}`; expected key=value")
|
|
767
|
+
if typed:
|
|
768
|
+
try:
|
|
769
|
+
parsed_value = json.loads(raw)
|
|
770
|
+
except json.JSONDecodeError:
|
|
771
|
+
parsed_value = raw
|
|
772
|
+
else:
|
|
773
|
+
parsed_value = raw
|
|
774
|
+
parsed.append((key, parsed_value))
|
|
775
|
+
return parsed
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def _read_input(value: str) -> bytes:
|
|
779
|
+
source: BinaryIO
|
|
780
|
+
try:
|
|
781
|
+
if value == "-":
|
|
782
|
+
source = sys.stdin.buffer
|
|
783
|
+
content = source.read(MAX_JSON_INPUT_BYTES + 1)
|
|
784
|
+
else:
|
|
785
|
+
with Path(value).open("rb") as source:
|
|
786
|
+
content = source.read(MAX_JSON_INPUT_BYTES + 1)
|
|
787
|
+
except OSError as exc:
|
|
788
|
+
raise CliError(f"Could not read input file {value}: {exc}") from exc
|
|
789
|
+
if len(content) > MAX_JSON_INPUT_BYTES:
|
|
790
|
+
raise CliError(
|
|
791
|
+
f"JSON input exceeds the {MAX_JSON_INPUT_BYTES}-byte in-memory limit"
|
|
792
|
+
)
|
|
793
|
+
return content
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def _input_chunks(value: str) -> Iterator[bytes]:
|
|
797
|
+
def chunks() -> Iterator[bytes]:
|
|
798
|
+
try:
|
|
799
|
+
if value == "-":
|
|
800
|
+
while chunk := sys.stdin.buffer.read(1024 * 1024):
|
|
801
|
+
yield chunk
|
|
802
|
+
return
|
|
803
|
+
with Path(value).open("rb") as source:
|
|
804
|
+
while chunk := source.read(1024 * 1024):
|
|
805
|
+
yield chunk
|
|
806
|
+
except OSError as exc:
|
|
807
|
+
raise CliError(f"Could not read input file {value}: {exc}") from exc
|
|
808
|
+
|
|
809
|
+
return chunks()
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def _append_values(target: list[tuple[str, Any]], name: str, value: Any) -> None:
|
|
813
|
+
if isinstance(value, list):
|
|
814
|
+
target.extend((name, _wire_scalar(item)) for item in value)
|
|
815
|
+
else:
|
|
816
|
+
target.append((name, _wire_scalar(value)))
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def _wire_scalar(value: Any) -> str:
|
|
820
|
+
if isinstance(value, bool):
|
|
821
|
+
return "true" if value else "false"
|
|
822
|
+
return str(value)
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
def _json_value(field: dict[str, Any], value: Any) -> Any:
|
|
826
|
+
schema = field["schema"]
|
|
827
|
+
if schema.get("kind") == "decimal":
|
|
828
|
+
return str(value)
|
|
829
|
+
if schema.get("kind") != "json" or not isinstance(value, str):
|
|
830
|
+
return value
|
|
831
|
+
try:
|
|
832
|
+
return json.loads(value)
|
|
833
|
+
except json.JSONDecodeError as exc:
|
|
834
|
+
raise CliError(
|
|
835
|
+
f"--{field['option']} must contain a valid JSON value: {exc}"
|
|
836
|
+
) from exc
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
def _multipart_payload(
|
|
840
|
+
body_spec: dict[str, Any],
|
|
841
|
+
values: dict[str, Any],
|
|
842
|
+
stack: ExitStack,
|
|
843
|
+
) -> tuple[dict[str, Any], list[tuple[str, Any]]]:
|
|
844
|
+
data: dict[str, Any] = {}
|
|
845
|
+
files: list[tuple[str, Any]] = []
|
|
846
|
+
for field in body_spec["properties"]:
|
|
847
|
+
if field["name"] not in values:
|
|
848
|
+
continue
|
|
849
|
+
value = values[field["name"]]
|
|
850
|
+
schema = field["schema"]
|
|
851
|
+
is_file = schema.get("kind") == "file"
|
|
852
|
+
is_file_array = (
|
|
853
|
+
schema.get("kind") == "array"
|
|
854
|
+
and schema.get("items", {}).get("kind") == "file"
|
|
855
|
+
)
|
|
856
|
+
if is_file or is_file_array:
|
|
857
|
+
paths = value if isinstance(value, list) else [value]
|
|
858
|
+
file_schema = schema.get("items", {}) if is_file_array else schema
|
|
859
|
+
for raw_path in paths:
|
|
860
|
+
path = Path(raw_path)
|
|
861
|
+
try:
|
|
862
|
+
size = path.stat().st_size
|
|
863
|
+
handle = stack.enter_context(path.open("rb"))
|
|
864
|
+
except OSError as exc:
|
|
865
|
+
raise CliError(f"Could not read upload file {path}: {exc}") from exc
|
|
866
|
+
maximum_size = file_schema.get("x-maxSizeBytes") or schema.get(
|
|
867
|
+
"x-maxSizeBytes"
|
|
868
|
+
)
|
|
869
|
+
if maximum_size is not None and size > maximum_size:
|
|
870
|
+
raise CliError(
|
|
871
|
+
f"--{field['option']} file {path} exceeds {maximum_size} bytes"
|
|
872
|
+
)
|
|
873
|
+
media_type = mimetypes.guess_type(path.name)[0]
|
|
874
|
+
allowed_types = file_schema.get("x-allowedContentTypes") or schema.get(
|
|
875
|
+
"x-allowedContentTypes"
|
|
876
|
+
)
|
|
877
|
+
if allowed_types and media_type not in allowed_types:
|
|
878
|
+
allowed = ", ".join(allowed_types)
|
|
879
|
+
raise CliError(
|
|
880
|
+
f"--{field['option']} file {path} has unsupported type "
|
|
881
|
+
f"{media_type or 'application/octet-stream'}; allowed: {allowed}"
|
|
882
|
+
)
|
|
883
|
+
files.append(
|
|
884
|
+
(
|
|
885
|
+
field["name"],
|
|
886
|
+
(path.name, handle, media_type or "application/octet-stream"),
|
|
887
|
+
)
|
|
888
|
+
)
|
|
889
|
+
elif isinstance(value, list):
|
|
890
|
+
data[field["name"]] = [_wire_scalar(item) for item in value]
|
|
891
|
+
else:
|
|
892
|
+
rendered = _json_value(field, value)
|
|
893
|
+
data[field["name"]] = (
|
|
894
|
+
json.dumps(rendered)
|
|
895
|
+
if isinstance(rendered, (dict, list))
|
|
896
|
+
else _wire_scalar(rendered)
|
|
897
|
+
)
|
|
898
|
+
return data, files
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def _validate_value(field: dict[str, Any], value: Any) -> None:
|
|
902
|
+
schema = field["schema"]
|
|
903
|
+
if isinstance(value, list):
|
|
904
|
+
_check_bound(field, len(value), "minItems", "at least")
|
|
905
|
+
_check_bound(field, len(value), "maxItems", "at most")
|
|
906
|
+
if schema.get("uniqueItems") and len(
|
|
907
|
+
{_stable_value(item) for item in value}
|
|
908
|
+
) != len(value):
|
|
909
|
+
raise CliError(f"--{field['option']} must contain unique values")
|
|
910
|
+
item_schema = schema.get("items")
|
|
911
|
+
if isinstance(item_schema, dict):
|
|
912
|
+
for item in value:
|
|
913
|
+
_validate_value({**field, "schema": item_schema}, item)
|
|
914
|
+
return
|
|
915
|
+
if isinstance(value, dict):
|
|
916
|
+
_check_bound(field, len(value), "minProperties", "at least")
|
|
917
|
+
_check_bound(field, len(value), "maxProperties", "at most")
|
|
918
|
+
constant = schema.get("const")
|
|
919
|
+
if "const" in schema and value != constant:
|
|
920
|
+
raise CliError(f"--{field['option']} must equal {constant!r}")
|
|
921
|
+
if isinstance(value, str):
|
|
922
|
+
_check_bound(field, len(value), "minLength", "at least")
|
|
923
|
+
_check_bound(field, len(value), "maxLength", "at most")
|
|
924
|
+
pattern = schema.get("pattern")
|
|
925
|
+
if pattern and re.fullmatch(pattern, value) is None:
|
|
926
|
+
raise CliError(
|
|
927
|
+
f"--{field['option']} does not match required pattern {pattern}"
|
|
928
|
+
)
|
|
929
|
+
if (
|
|
930
|
+
isinstance(value, (int, float, Decimal, str))
|
|
931
|
+
and not isinstance(value, bool)
|
|
932
|
+
and schema.get("kind") in {"integer", "number", "decimal"}
|
|
933
|
+
):
|
|
934
|
+
_validate_number(field, value)
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def _validate_number(field: dict[str, Any], value: Any) -> None:
|
|
938
|
+
schema = field["schema"]
|
|
939
|
+
try:
|
|
940
|
+
number = Decimal(str(value))
|
|
941
|
+
except InvalidOperation as exc:
|
|
942
|
+
raise CliError(f"--{field['option']} must be numeric") from exc
|
|
943
|
+
if not number.is_finite():
|
|
944
|
+
raise CliError(f"--{field['option']} must be a finite number")
|
|
945
|
+
bounds = (
|
|
946
|
+
("minimum", lambda actual, expected: actual < expected, "at least"),
|
|
947
|
+
("maximum", lambda actual, expected: actual > expected, "at most"),
|
|
948
|
+
(
|
|
949
|
+
"exclusiveMinimum",
|
|
950
|
+
lambda actual, expected: actual <= expected,
|
|
951
|
+
"greater than",
|
|
952
|
+
),
|
|
953
|
+
("exclusiveMaximum", lambda actual, expected: actual >= expected, "less than"),
|
|
954
|
+
)
|
|
955
|
+
for key, invalid, description in bounds:
|
|
956
|
+
expected = schema.get(key)
|
|
957
|
+
if expected is not None and invalid(number, Decimal(str(expected))):
|
|
958
|
+
raise CliError(f"--{field['option']} must be {description} {expected}")
|
|
959
|
+
multiple = schema.get("multipleOf")
|
|
960
|
+
if multiple is not None and number % Decimal(str(multiple)) != 0:
|
|
961
|
+
raise CliError(f"--{field['option']} must be a multiple of {multiple}")
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
def _check_bound(
|
|
965
|
+
field: dict[str, Any], actual: int, key: str, description: str
|
|
966
|
+
) -> None:
|
|
967
|
+
expected = field["schema"].get(key)
|
|
968
|
+
if expected is None:
|
|
969
|
+
return
|
|
970
|
+
invalid = actual < expected if key.startswith("min") else actual > expected
|
|
971
|
+
if invalid:
|
|
972
|
+
raise CliError(
|
|
973
|
+
f"--{field['option']} must contain {description} {expected} value(s)"
|
|
974
|
+
)
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def _confirm_if_dangerous(*, dangerous: bool, yes: bool, description: str) -> None:
|
|
978
|
+
if not dangerous or yes:
|
|
979
|
+
return
|
|
980
|
+
if not sys.stdin.isatty():
|
|
981
|
+
raise CliError(f"{description} mutates data; pass --yes in non-interactive use")
|
|
982
|
+
if not Confirm.ask(f"Run mutating operation {description}?", default=False):
|
|
983
|
+
raise CliError("Operation cancelled")
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
def _stable_value(value: Any) -> str:
|
|
987
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
def _validate_json_schema(value: Any, schema: Any, *, label: str) -> None:
|
|
991
|
+
if not isinstance(schema, dict) or not schema:
|
|
992
|
+
return
|
|
993
|
+
if value is None and (schema.get("nullable") or schema.get("type") == "null"):
|
|
994
|
+
return
|
|
995
|
+
variants = schema.get("anyOf") or schema.get("oneOf")
|
|
996
|
+
if isinstance(variants, list) and variants:
|
|
997
|
+
decimal_schema = _decimal_union_schema(variants)
|
|
998
|
+
if decimal_schema is not None:
|
|
999
|
+
_validate_value(
|
|
1000
|
+
{"option": label, "schema": decimal_schema},
|
|
1001
|
+
value,
|
|
1002
|
+
)
|
|
1003
|
+
return
|
|
1004
|
+
failures: list[CliError] = []
|
|
1005
|
+
for variant in variants:
|
|
1006
|
+
try:
|
|
1007
|
+
_validate_json_schema(value, variant, label=label)
|
|
1008
|
+
return
|
|
1009
|
+
except CliError as exc:
|
|
1010
|
+
failures.append(exc)
|
|
1011
|
+
raise CliError(f"{label} does not match any allowed schema") from failures[-1]
|
|
1012
|
+
|
|
1013
|
+
raw_schema_type = schema.get("type")
|
|
1014
|
+
schema_type = raw_schema_type if isinstance(raw_schema_type, str) else None
|
|
1015
|
+
validators = {
|
|
1016
|
+
"array": lambda item: isinstance(item, list),
|
|
1017
|
+
"boolean": lambda item: isinstance(item, bool),
|
|
1018
|
+
"integer": lambda item: isinstance(item, int) and not isinstance(item, bool),
|
|
1019
|
+
"null": lambda item: item is None,
|
|
1020
|
+
"number": lambda item: isinstance(item, (int, float))
|
|
1021
|
+
and not isinstance(item, bool),
|
|
1022
|
+
"object": lambda item: isinstance(item, dict),
|
|
1023
|
+
"string": lambda item: isinstance(item, str),
|
|
1024
|
+
}
|
|
1025
|
+
valid_type = validators.get(schema_type) if schema_type is not None else None
|
|
1026
|
+
if valid_type is not None and not valid_type(value):
|
|
1027
|
+
raise CliError(f"{label} must be {schema_type}")
|
|
1028
|
+
if "const" in schema and value != schema["const"]:
|
|
1029
|
+
raise CliError(f"{label} must equal {schema['const']!r}")
|
|
1030
|
+
enum = schema.get("enum")
|
|
1031
|
+
if isinstance(enum, list) and value not in enum:
|
|
1032
|
+
raise CliError(f"{label} must be one of {enum}")
|
|
1033
|
+
|
|
1034
|
+
field = {"option": label, "schema": {**schema, "kind": schema_type or "json"}}
|
|
1035
|
+
if isinstance(value, (str, int, float, list, dict)) and not isinstance(value, bool):
|
|
1036
|
+
_validate_value(field, value)
|
|
1037
|
+
if isinstance(value, list):
|
|
1038
|
+
items = schema.get("items")
|
|
1039
|
+
if isinstance(items, dict):
|
|
1040
|
+
for index, item in enumerate(value):
|
|
1041
|
+
_validate_json_schema(item, items, label=f"{label}[{index}]")
|
|
1042
|
+
if isinstance(value, dict):
|
|
1043
|
+
required = schema.get("required", [])
|
|
1044
|
+
if isinstance(required, list):
|
|
1045
|
+
missing = [name for name in required if name not in value]
|
|
1046
|
+
if missing:
|
|
1047
|
+
raise CliError(
|
|
1048
|
+
f"{label} is missing required field(s): {', '.join(missing)}"
|
|
1049
|
+
)
|
|
1050
|
+
properties = schema.get("properties", {})
|
|
1051
|
+
if isinstance(properties, dict):
|
|
1052
|
+
if schema.get("additionalProperties") is False:
|
|
1053
|
+
unknown = sorted(set(value) - set(properties))
|
|
1054
|
+
if unknown:
|
|
1055
|
+
raise CliError(
|
|
1056
|
+
f"{label} contains unknown field(s): {', '.join(unknown)}"
|
|
1057
|
+
)
|
|
1058
|
+
for name, item in value.items():
|
|
1059
|
+
property_schema = properties.get(name)
|
|
1060
|
+
if isinstance(property_schema, dict):
|
|
1061
|
+
_validate_json_schema(
|
|
1062
|
+
item, property_schema, label=f"{label}.{name}"
|
|
1063
|
+
)
|
|
1064
|
+
|
|
1065
|
+
|
|
1066
|
+
def _redact_json_body(value: Any, schema: Any) -> Any:
|
|
1067
|
+
if not isinstance(schema, dict):
|
|
1068
|
+
return value
|
|
1069
|
+
if schema.get("writeOnly") is True or schema.get("x-sensitive") is True:
|
|
1070
|
+
return "<redacted>"
|
|
1071
|
+
if isinstance(value, list):
|
|
1072
|
+
item_schema = schema.get("items", {})
|
|
1073
|
+
return [_redact_json_body(item, item_schema) for item in value]
|
|
1074
|
+
if isinstance(value, dict):
|
|
1075
|
+
properties = _schema_properties(schema)
|
|
1076
|
+
return {
|
|
1077
|
+
name: _redact_json_body(item, properties.get(name, {}))
|
|
1078
|
+
for name, item in value.items()
|
|
1079
|
+
}
|
|
1080
|
+
return value
|
|
1081
|
+
|
|
1082
|
+
|
|
1083
|
+
def _sensitive_body_strings(value: Any, schema: Any) -> list[str]:
|
|
1084
|
+
if not isinstance(schema, dict):
|
|
1085
|
+
return []
|
|
1086
|
+
if schema.get("writeOnly") is True or schema.get("x-sensitive") is True:
|
|
1087
|
+
return _body_strings(value)
|
|
1088
|
+
if isinstance(value, list):
|
|
1089
|
+
item_schema = schema.get("items", {})
|
|
1090
|
+
return [
|
|
1091
|
+
candidate
|
|
1092
|
+
for item in value
|
|
1093
|
+
for candidate in _sensitive_body_strings(item, item_schema)
|
|
1094
|
+
]
|
|
1095
|
+
if isinstance(value, dict):
|
|
1096
|
+
properties = _schema_properties(schema)
|
|
1097
|
+
return [
|
|
1098
|
+
candidate
|
|
1099
|
+
for name, item in value.items()
|
|
1100
|
+
for candidate in _sensitive_body_strings(item, properties.get(name, {}))
|
|
1101
|
+
]
|
|
1102
|
+
return []
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
def _body_strings(value: Any) -> list[str]:
|
|
1106
|
+
if isinstance(value, str):
|
|
1107
|
+
return [value]
|
|
1108
|
+
if isinstance(value, list):
|
|
1109
|
+
return [candidate for item in value for candidate in _body_strings(item)]
|
|
1110
|
+
if isinstance(value, dict):
|
|
1111
|
+
return [
|
|
1112
|
+
candidate for item in value.values() for candidate in _body_strings(item)
|
|
1113
|
+
]
|
|
1114
|
+
return []
|
|
1115
|
+
|
|
1116
|
+
|
|
1117
|
+
def _schema_properties(schema: dict[str, Any]) -> dict[str, Any]:
|
|
1118
|
+
properties: dict[str, Any] = {}
|
|
1119
|
+
direct = schema.get("properties")
|
|
1120
|
+
if isinstance(direct, dict):
|
|
1121
|
+
properties.update(direct)
|
|
1122
|
+
for keyword in ("anyOf", "oneOf"):
|
|
1123
|
+
variants = schema.get(keyword)
|
|
1124
|
+
if isinstance(variants, list):
|
|
1125
|
+
for variant in variants:
|
|
1126
|
+
if isinstance(variant, dict):
|
|
1127
|
+
properties.update(_schema_properties(variant))
|
|
1128
|
+
return properties
|
|
1129
|
+
|
|
1130
|
+
|
|
1131
|
+
def _decimal_union_schema(variants: list[Any]) -> dict[str, Any] | None:
|
|
1132
|
+
number: dict[str, Any] | None = None
|
|
1133
|
+
string: dict[str, Any] | None = None
|
|
1134
|
+
nullable = False
|
|
1135
|
+
for variant in variants:
|
|
1136
|
+
if not isinstance(variant, dict):
|
|
1137
|
+
return None
|
|
1138
|
+
if variant.get("type") == "number" and number is None:
|
|
1139
|
+
number = variant
|
|
1140
|
+
elif variant.get("type") == "string" and string is None:
|
|
1141
|
+
string = variant
|
|
1142
|
+
elif variant.get("type") == "null":
|
|
1143
|
+
nullable = True
|
|
1144
|
+
else:
|
|
1145
|
+
return None
|
|
1146
|
+
if number is None or string is None or not string.get("pattern"):
|
|
1147
|
+
return None
|
|
1148
|
+
return {**number, **string, "kind": "decimal", "nullable": nullable}
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
__all__ = [
|
|
1152
|
+
"HTTP_METHODS",
|
|
1153
|
+
"load_manifest",
|
|
1154
|
+
"register_module_commands",
|
|
1155
|
+
"render_api_result",
|
|
1156
|
+
"run_raw_api",
|
|
1157
|
+
"validate_relative_endpoint",
|
|
1158
|
+
]
|