zoodealio 0.0.0-stage → 0.1.0
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.
- package/README.md +203 -2
- package/bin/zoodealio.js +11 -0
- package/package.json +37 -4
- package/src/args.js +94 -0
- package/src/cli.js +113 -0
- package/src/commands.js +206 -0
- package/src/errors.js +29 -0
- package/src/http.js +110 -0
- package/src/input.js +43 -0
package/README.md
CHANGED
|
@@ -1,3 +1,204 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Zoodealio CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`zoodealio` is a command line wrapper over the partner API (`/openapi`). It prints JSON,
|
|
4
|
+
takes JSON bodies, and describes itself, so people, scripts and AI agents can drive the
|
|
5
|
+
same contract as the Zoodealio MCP server (`Mcp/OpenApiMcpTools.cs`) and the
|
|
6
|
+
[Zapier app](../zapier/README.md). It adds no API surface: every command is one
|
|
7
|
+
documented `/openapi` request, and bodies pass through unchanged.
|
|
8
|
+
|
|
9
|
+
It has no runtime dependencies and needs Node 22 or newer.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
Run it without installing:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npx zoodealio whoami
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
or install it globally:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install -g zoodealio
|
|
23
|
+
zoodealio whoami
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
From a checkout of this repo, `node integrations/cli/bin/zoodealio.js` runs the working copy.
|
|
27
|
+
|
|
28
|
+
## Authenticate
|
|
29
|
+
|
|
30
|
+
Copy a personal API key from **Settings → API** in Zoodealio AI and export it:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
export ZOODEALIO_API_KEY=zoo_...
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The key is read only from this variable and sent only as the `ApiKey` header. It is never
|
|
37
|
+
printed: errors, `--dry-run` output and `whoami` show it as `zoo_…<last4>`. Redirects are
|
|
38
|
+
refused so the header cannot be forwarded. A missing key is a usage error (exit 2) and no
|
|
39
|
+
request is sent. The key keeps its owner's workspace and property scope.
|
|
40
|
+
|
|
41
|
+
`zoodealio whoami` confirms the key works and shows the target origin.
|
|
42
|
+
|
|
43
|
+
## Environments
|
|
44
|
+
|
|
45
|
+
| Selection | API origin |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| default | `https://api.zoodealio.ai` |
|
|
48
|
+
| `--env dev` | `https://dev.api.zoodealio.ai` |
|
|
49
|
+
| `ZOODEALIO_API_URL=http://localhost:5256` | that origin (overrides both) |
|
|
50
|
+
|
|
51
|
+
Keys are per environment. Use a local API URL only for a local API; the port above is an
|
|
52
|
+
example, use whichever yours runs on.
|
|
53
|
+
|
|
54
|
+
## Output and errors
|
|
55
|
+
|
|
56
|
+
stdout carries JSON and nothing else: pretty-printed on a terminal, compact when piped
|
|
57
|
+
(`--pretty` forces pretty). An empty or 204 response prints `null`. Help text is the only
|
|
58
|
+
non-JSON stdout.
|
|
59
|
+
|
|
60
|
+
Failures print one JSON object on stderr and exit non-zero:
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{"error":{"status":404,"code":"not_found","title":"Not Found","detail":"..."}}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`title` and `detail` come from the API's problem response when present. `status` is `null`
|
|
67
|
+
for usage and network errors. A 429 adds `retryAfter` in seconds.
|
|
68
|
+
|
|
69
|
+
| Exit | Meaning | `code` |
|
|
70
|
+
| --- | --- | --- |
|
|
71
|
+
| 0 | Success | |
|
|
72
|
+
| 1 | Other API or network error | `http_error`, `network_error` |
|
|
73
|
+
| 2 | Usage: unknown command or flag, missing argument, bad ID or JSON, missing `--yes`, missing key, or HTTP 400 | `usage`, `bad_request` |
|
|
74
|
+
| 3 | Not authenticated or not allowed (401, 403) | `unauthorized`, `forbidden` |
|
|
75
|
+
| 4 | Not found (404) | `not_found` |
|
|
76
|
+
| 5 | Conflict, precondition or validation failure (409, 412, 422) | `conflict`, `precondition_failed`, `validation_failed` |
|
|
77
|
+
| 6 | Rate limited (429) | `rate_limited` |
|
|
78
|
+
|
|
79
|
+
Route IDs are GUIDs and are checked before any request is made.
|
|
80
|
+
|
|
81
|
+
## Global flags
|
|
82
|
+
|
|
83
|
+
| Flag | Effect |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `--env prod\|dev` | Pick the environment (default `prod`) |
|
|
86
|
+
| `--pretty` | Pretty-print JSON even when piped |
|
|
87
|
+
| `--dry-run` | Print `{method, url, headers, body}` with the key redacted and send nothing; works without a key |
|
|
88
|
+
| `--yes` | Confirm a destructive command (not needed with `--dry-run`) |
|
|
89
|
+
| `--help` | Help for the CLI or one command |
|
|
90
|
+
|
|
91
|
+
Write bodies come from `--body '<json>'`, `--body @file.json` or `--body -` (stdin). Where
|
|
92
|
+
a body is trivial, convenience flags build it instead; use one or the other, not both.
|
|
93
|
+
List commands accept `--page` and `--page-size`. `--if-match <etag>` sends optimistic
|
|
94
|
+
concurrency on `properties update`, `offers accept` and `offers request-details`.
|
|
95
|
+
|
|
96
|
+
## Commands
|
|
97
|
+
|
|
98
|
+
`zoodealio commands` prints the authoritative catalogue. In short:
|
|
99
|
+
|
|
100
|
+
| Command | Request | Notes |
|
|
101
|
+
| --- | --- | --- |
|
|
102
|
+
| `properties list` | GET Properties | `--search`, `--state` |
|
|
103
|
+
| `properties get <id>` | GET Properties/{id} | |
|
|
104
|
+
| `properties create` | POST Properties | `--body` |
|
|
105
|
+
| `properties update <id>` | PUT Properties/{id} | `--body`, `--if-match`; replaces wholesale |
|
|
106
|
+
| `properties photos list\|add\|delete` | photos | `add`: `--url` (repeatable) or `--body`; `delete <id> <photoId>` needs `--yes` |
|
|
107
|
+
| `properties documents list\|add\|delete` | documents | same shape as photos |
|
|
108
|
+
| `properties import-status <id> <importId>` | GET imports/{importId} | Photo and document imports |
|
|
109
|
+
| `offers list` | GET Offers | `--property` required, `--status` |
|
|
110
|
+
| `offers get <id>`, `offers history <id>` | GET | |
|
|
111
|
+
| `offers accept <id>` | POST accept | `--yes` required; `--attributes <json\|@file>`, `--if-match` |
|
|
112
|
+
| `offers request-details <id>` | POST request-details | `--if-match` |
|
|
113
|
+
| `transactions get <id>` | GET Transactions/{id} | |
|
|
114
|
+
| `transactions active` | GET Transactions/active | `--property` required |
|
|
115
|
+
| `comping status <transactionId>` | GET Transactions/{id}/comping | |
|
|
116
|
+
| `team members`, `team get <id>`, `teams list` | GET Team | `--search` |
|
|
117
|
+
| `team invite` | POST Team/members | `--email` (+ `--first-name`, `--last-name`, `--team`, `--admin-team`) or `--body` |
|
|
118
|
+
| `team remove <id>` | DELETE Team/members/{id} | `--yes` required |
|
|
119
|
+
| `webhooks event-types\|list\|deliveries` | GET Webhooks | `deliveries`: `--subscription`, `--status` |
|
|
120
|
+
| `webhooks create` | POST Webhooks | `--url` and `--event` (repeatable) or `--body` |
|
|
121
|
+
| `webhooks update <id>` | PUT Webhooks/{id} | `--body` (`endpointUrl`, `eventTypes`, `isActive`) |
|
|
122
|
+
| `webhooks rotate <id>`, `webhooks delete <id>` | POST, DELETE | `--yes` required |
|
|
123
|
+
| `whoami` | | Key check; prints `{ok, origin, key}` |
|
|
124
|
+
| `openapi` | GET `/_openapi/partner.json` | Partner OpenAPI document; no key needed |
|
|
125
|
+
| `api <METHOD> <path>` | any `/openapi/...` | `--query k=v` (repeatable), `--body`; `DELETE` needs `--yes` |
|
|
126
|
+
| `commands` | | Command catalogue as JSON |
|
|
127
|
+
|
|
128
|
+
Destructive commands (`offers accept`, `team remove`, `properties photos delete`,
|
|
129
|
+
`properties documents delete`, `webhooks rotate`, `webhooks delete`, and `api ... DELETE`)
|
|
130
|
+
refuse to run without `--yes`, exit 2, and send nothing. `--dry-run` previews them
|
|
131
|
+
without `--yes`, since it sends nothing either.
|
|
132
|
+
|
|
133
|
+
`api` accepts `Properties` or `/openapi/Properties`. Paths that are absolute URLs, contain
|
|
134
|
+
`..`, or fall outside `/openapi/` are rejected.
|
|
135
|
+
|
|
136
|
+
## Examples
|
|
137
|
+
|
|
138
|
+
```sh
|
|
139
|
+
# Properties: search, then import photos from URLs
|
|
140
|
+
zoodealio properties list --search "Elm St" --state AZ
|
|
141
|
+
zoodealio properties photos add <propertyId> --url https://example.com/front.jpg
|
|
142
|
+
zoodealio properties import-status <propertyId> <importId>
|
|
143
|
+
|
|
144
|
+
# Offers: list for a property, preview an accept, then accept
|
|
145
|
+
zoodealio offers list --property <propertyId>
|
|
146
|
+
zoodealio offers accept <offerId> --dry-run
|
|
147
|
+
zoodealio offers accept <offerId> --yes
|
|
148
|
+
|
|
149
|
+
# Transactions and comping
|
|
150
|
+
zoodealio transactions active --property <propertyId>
|
|
151
|
+
zoodealio comping status <transactionId>
|
|
152
|
+
|
|
153
|
+
# Team
|
|
154
|
+
zoodealio team invite --email new@example.com --first-name Ada --team <teamId>
|
|
155
|
+
|
|
156
|
+
# Webhooks: create a subscription (the signing secret is shown once)
|
|
157
|
+
zoodealio webhooks create --url https://example.com/hooks --event offer.created --event comping.completed
|
|
158
|
+
|
|
159
|
+
# Anything else under /openapi
|
|
160
|
+
zoodealio api GET Properties --query pageSize=5
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## For AI agents
|
|
164
|
+
|
|
165
|
+
- Start with `zoodealio commands`. It lists every command with its method, path, arguments,
|
|
166
|
+
flags and a `destructive` marker, generated from the same table the parser uses.
|
|
167
|
+
- stdout is JSON only and errors are JSON on stderr, so parse stdout on exit 0 and
|
|
168
|
+
stderr otherwise. Branch on the exit code (for example back off on 6 using `retryAfter`).
|
|
169
|
+
- Run writes with `--dry-run` first and check the URL and body, then run them again
|
|
170
|
+
without it.
|
|
171
|
+
- `--yes` is a gate for explicit human intent. Pass it only when the person asked for that
|
|
172
|
+
destructive action (accepting an offer, removing a member, deleting or rotating a
|
|
173
|
+
webhook); do not add it to make an error go away.
|
|
174
|
+
- For request body shapes run `zoodealio openapi`, which prints the partner OpenAPI document.
|
|
175
|
+
- Prefer webhooks, or polling `comping status` and `import-status`, to long waits. See
|
|
176
|
+
[OPEN_API_WEBHOOKS.md](../../docs/OPEN_API_WEBHOOKS.md) for events, signatures and delivery.
|
|
177
|
+
|
|
178
|
+
## Limits
|
|
179
|
+
|
|
180
|
+
- No multipart uploads of local files. Photos and documents are imported from URLs only
|
|
181
|
+
(`photos add --url`); `api` cannot send multipart either.
|
|
182
|
+
- No config file, keychain or interactive prompts; the environment variable is the only
|
|
183
|
+
credential source.
|
|
184
|
+
|
|
185
|
+
## Development
|
|
186
|
+
|
|
187
|
+
```sh
|
|
188
|
+
cd integrations/cli
|
|
189
|
+
npm install
|
|
190
|
+
npm run check # eslint, tsc --noEmit (checkJs), node --test
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## Releasing
|
|
194
|
+
|
|
195
|
+
Maintainers publish from their machine with a granular npm token kept outside the repo:
|
|
196
|
+
|
|
197
|
+
```sh
|
|
198
|
+
cd integrations/cli
|
|
199
|
+
npm version <patch|minor|major> --no-git-tag-version # in a PR, then merge
|
|
200
|
+
npm run check
|
|
201
|
+
npm publish --userconfig ~/.config/zoodealio/npm-publish.npmrc
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
A version with a `-` suffix (`0.2.0-beta.1`) goes out with `--tag next` so `latest` stays stable.
|
package/bin/zoodealio.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zoodealio",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Zoodealio command line tool: the partner API as JSON, built for people, scripts and AI agents",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Zoodealio-admin/zoodealioai-services.git",
|
|
9
|
+
"directory": "integrations/cli"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://zoodealio.ai/developers",
|
|
12
|
+
"bin": {
|
|
13
|
+
"zoodealio": "bin/zoodealio.js"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"bin",
|
|
17
|
+
"src",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"test": "node --test --test-isolation=none test/*.test.js",
|
|
28
|
+
"lint": "eslint .",
|
|
29
|
+
"typecheck": "tsc --noEmit",
|
|
30
|
+
"check": "npm run lint && npm run typecheck && npm test"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@eslint/js": "9.39.1",
|
|
34
|
+
"@types/node": "22.19.0",
|
|
35
|
+
"eslint": "9.39.1",
|
|
36
|
+
"globals": "16.5.0",
|
|
37
|
+
"typescript": "5.9.3"
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/args.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
const { parseArgs } = require('node:util');
|
|
2
|
+
const { usage } = require('./errors');
|
|
3
|
+
const { COMMANDS, GLOBAL_FLAGS, GUID, helpText, usageLine } = require('./commands');
|
|
4
|
+
|
|
5
|
+
/** @typedef {import('./commands').Command} Command */
|
|
6
|
+
|
|
7
|
+
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
|
|
8
|
+
|
|
9
|
+
/** One parseArgs option set covering every flag any command knows; per-command validity is checked after. */
|
|
10
|
+
const OPTIONS = (() => {
|
|
11
|
+
/** @type {Record<string, {type: 'string' | 'boolean', multiple?: boolean}>} */
|
|
12
|
+
const options = {};
|
|
13
|
+
for (const f of [...GLOBAL_FLAGS, ...COMMANDS.flatMap((c) => c.flags)]) {
|
|
14
|
+
options[f.name] = f.type === 'string' ? { type: 'string', multiple: true } : { type: 'boolean' };
|
|
15
|
+
}
|
|
16
|
+
return options;
|
|
17
|
+
})();
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {string[]} argv
|
|
21
|
+
* @returns {{help: string} | {command: Command, args: Record<string, string>, flags: Record<string, any>}}
|
|
22
|
+
*/
|
|
23
|
+
function parse(argv) {
|
|
24
|
+
let parsed;
|
|
25
|
+
try {
|
|
26
|
+
parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
|
|
27
|
+
} catch (err) {
|
|
28
|
+
throw usage(/** @type {Error} */ (err).message);
|
|
29
|
+
}
|
|
30
|
+
const { values, positionals } = parsed;
|
|
31
|
+
if (values.help) return { help: helpText(positionals) };
|
|
32
|
+
if (positionals.length === 0) throw usage('missing command; run `zoodealio --help`');
|
|
33
|
+
|
|
34
|
+
let command;
|
|
35
|
+
for (const c of COMMANDS) {
|
|
36
|
+
const words = c.name.split(' ');
|
|
37
|
+
if (words.every((w, i) => positionals[i] === w) && (!command || words.length > command.name.split(' ').length)) command = c;
|
|
38
|
+
}
|
|
39
|
+
if (!command) throw usage(`unknown command: ${positionals.join(' ')}`);
|
|
40
|
+
|
|
41
|
+
const rest = positionals.slice(command.name.split(' ').length);
|
|
42
|
+
if (rest.length !== command.args.length) throw usage(`expected: ${usageLine(command)}`);
|
|
43
|
+
/** @type {Record<string, string>} */
|
|
44
|
+
const args = {};
|
|
45
|
+
command.args.forEach((a, i) => {
|
|
46
|
+
if (a.guid && !GUID.test(rest[i])) throw usage(`<${a.name}> must be a GUID, got: ${rest[i]}`);
|
|
47
|
+
args[a.name] = rest[i];
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const allowed = new Map([...GLOBAL_FLAGS, ...command.flags].map((f) => [f.name, f]));
|
|
51
|
+
/** @type {Record<string, any>} */
|
|
52
|
+
const flags = {};
|
|
53
|
+
for (const [name, value] of Object.entries(values)) {
|
|
54
|
+
const spec = allowed.get(name);
|
|
55
|
+
if (!spec) throw usage(`--${name} is not valid for \`${command.name}\``);
|
|
56
|
+
if (spec.type === 'boolean') flags[name] = value;
|
|
57
|
+
else if (spec.multiple) flags[name] = value;
|
|
58
|
+
else if (/** @type {string[]} */ (value).length > 1) throw usage(`--${name} may be given only once`);
|
|
59
|
+
else flags[name] = /** @type {string[]} */ (value)[0];
|
|
60
|
+
}
|
|
61
|
+
for (const f of command.flags) if (f.required && flags[f.name] === undefined) throw usage(`missing required flag --${f.name}`);
|
|
62
|
+
return { command, args, flags };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Validates an `api` escape-hatch path and returns it rooted at /openapi/.
|
|
67
|
+
* @param {string} input
|
|
68
|
+
* @returns {string}
|
|
69
|
+
*/
|
|
70
|
+
function normalizeApiPath(input) {
|
|
71
|
+
const bad = () => usage(`api path must be under /openapi/ (got: ${input})`);
|
|
72
|
+
let decoded = input;
|
|
73
|
+
for (let i = 0; i < 4; i++) {
|
|
74
|
+
if (/(^|[\\/])\.\.?([\\/]|$)/.test(decoded) || /[\\?#]|:\/\/|^\/\//.test(decoded) || [...decoded].some((ch) => ch.charCodeAt(0) < 32)) throw bad();
|
|
75
|
+
let next;
|
|
76
|
+
try {
|
|
77
|
+
next = decodeURIComponent(decoded);
|
|
78
|
+
} catch {
|
|
79
|
+
throw bad();
|
|
80
|
+
}
|
|
81
|
+
if (next === decoded) break;
|
|
82
|
+
decoded = next;
|
|
83
|
+
}
|
|
84
|
+
const trimmed = input.replace(/^\/+/, '');
|
|
85
|
+
const first = trimmed.split('/')[0].toLowerCase();
|
|
86
|
+
if (first === 'openapi') {
|
|
87
|
+
if (trimmed.split('/').length < 2 || !trimmed.split('/')[1]) throw bad();
|
|
88
|
+
return `/openapi/${trimmed.slice(first.length + 1)}`;
|
|
89
|
+
}
|
|
90
|
+
if (input.startsWith('/') || trimmed === '') throw bad();
|
|
91
|
+
return `/openapi/${trimmed}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
module.exports = { parse, normalizeApiPath, METHODS };
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
const { CliError, usage } = require('./errors');
|
|
2
|
+
const { parse, normalizeApiPath, METHODS } = require('./args');
|
|
3
|
+
const { catalogue } = require('./commands');
|
|
4
|
+
const { resolveBody } = require('./input');
|
|
5
|
+
const { redactKey, resolveOrigin, buildUrl, send } = require('./http');
|
|
6
|
+
const pkg = require('../package.json');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {{env: Record<string, string | undefined>, stdout: {write(s: string): unknown, isTTY?: boolean},
|
|
10
|
+
* stderr: {write(s: string): unknown}, stdin: AsyncIterable<string | Buffer>, fetch?: typeof fetch}} Io
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Runs the CLI.
|
|
15
|
+
* @param {string[]} argv
|
|
16
|
+
* @param {Io} io
|
|
17
|
+
* @returns {Promise<number>} exit code
|
|
18
|
+
*/
|
|
19
|
+
async function run(argv, io) {
|
|
20
|
+
const key = (io.env.ZOODEALIO_API_KEY || '').trim();
|
|
21
|
+
try {
|
|
22
|
+
await execute(argv, io, key);
|
|
23
|
+
return 0;
|
|
24
|
+
} catch (err) {
|
|
25
|
+
const error = err instanceof CliError
|
|
26
|
+
? err
|
|
27
|
+
: new CliError({ exit: 1, code: 'internal', title: 'Unexpected error', detail: /** @type {Error} */ (err).message });
|
|
28
|
+
let text = JSON.stringify(error.toJSON());
|
|
29
|
+
if (key) {
|
|
30
|
+
// The key can appear JSON-escaped (newline, quote, backslash) inside the serialized error.
|
|
31
|
+
for (const form of [key, JSON.stringify(key).slice(1, -1)]) text = text.split(form).join(redactKey(key));
|
|
32
|
+
}
|
|
33
|
+
io.stderr.write(`${text}\n`);
|
|
34
|
+
return error.exit;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {string[]} argv
|
|
40
|
+
* @param {Io} io
|
|
41
|
+
* @param {string} key
|
|
42
|
+
*/
|
|
43
|
+
async function execute(argv, io, key) {
|
|
44
|
+
const parsed = parse(argv);
|
|
45
|
+
if ('help' in parsed) {
|
|
46
|
+
io.stdout.write(parsed.help);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const { command, args, flags } = parsed;
|
|
50
|
+
const pretty = !!flags.pretty || !!io.stdout.isTTY;
|
|
51
|
+
/** @param {unknown} value */
|
|
52
|
+
const emit = (value) => io.stdout.write(`${JSON.stringify(value ?? null, null, pretty ? 2 : 0)}\n`);
|
|
53
|
+
|
|
54
|
+
if (command.name === 'commands') return emit(catalogue());
|
|
55
|
+
|
|
56
|
+
/** @type {string} */
|
|
57
|
+
let method;
|
|
58
|
+
/** @type {string} */
|
|
59
|
+
let path;
|
|
60
|
+
/** @type {[string, string][]} */
|
|
61
|
+
const query = [];
|
|
62
|
+
let destructive = !!command.destructive;
|
|
63
|
+
if (command.name === 'api') {
|
|
64
|
+
method = args.method.toUpperCase();
|
|
65
|
+
if (!METHODS.includes(method)) throw usage(`method must be one of ${METHODS.join(', ')}`);
|
|
66
|
+
path = normalizeApiPath(args.path);
|
|
67
|
+
destructive = method === 'DELETE';
|
|
68
|
+
for (const kv of flags.query || []) {
|
|
69
|
+
const eq = kv.indexOf('=');
|
|
70
|
+
if (eq < 1) throw usage(`--query expects k=v, got: ${kv}`);
|
|
71
|
+
query.push([kv.slice(0, eq), kv.slice(eq + 1)]);
|
|
72
|
+
}
|
|
73
|
+
} else {
|
|
74
|
+
method = /** @type {string} */ (command.method);
|
|
75
|
+
path = /** @type {string} */ (command.path).replace(/\{(\w+)\}/g, (_, name) => encodeURIComponent(args[name]));
|
|
76
|
+
for (const f of command.flags) if (f.query && flags[f.name] !== undefined) query.push([f.query, flags[f.name]]);
|
|
77
|
+
}
|
|
78
|
+
if (destructive && !flags.yes && !flags['dry-run']) throw usage(`\`${command.name}\` is destructive; pass --yes to confirm`);
|
|
79
|
+
|
|
80
|
+
/** @type {unknown} */
|
|
81
|
+
let body;
|
|
82
|
+
if (flags.body !== undefined) {
|
|
83
|
+
if ((command.convenience || []).some((n) => flags[n] !== undefined)) throw usage('use either --body or the convenience flags, not both');
|
|
84
|
+
body = await resolveBody(flags.body, io.stdin);
|
|
85
|
+
} else if (command.build) {
|
|
86
|
+
body = command.build(flags);
|
|
87
|
+
if (body === undefined && command.body === 'required') throw usage('provide --body or the convenience flags');
|
|
88
|
+
} else if (command.body === 'required') {
|
|
89
|
+
throw usage('--body is required');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const needsKey = command.auth !== false;
|
|
93
|
+
if (needsKey && !key && !flags['dry-run']) throw usage('ZOODEALIO_API_KEY is not set');
|
|
94
|
+
|
|
95
|
+
const origin = resolveOrigin(io.env, flags.env);
|
|
96
|
+
const url = buildUrl(origin, path, query);
|
|
97
|
+
/** @param {string} apiKey */
|
|
98
|
+
const headers = (apiKey) => ({
|
|
99
|
+
Accept: 'application/json',
|
|
100
|
+
'User-Agent': `zoodealio-cli/${pkg.version}`,
|
|
101
|
+
...(needsKey ? { ApiKey: apiKey } : {}),
|
|
102
|
+
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
103
|
+
...(flags['if-match'] === undefined ? {} : { 'If-Match': flags['if-match'] }),
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
if (flags['dry-run']) return emit({ method, url, headers: headers(redactKey(key)), body: body ?? null });
|
|
107
|
+
|
|
108
|
+
const result = await send(io.fetch || fetch, { method, url, headers: headers(key), body });
|
|
109
|
+
if (command.name === 'whoami') return emit({ ok: true, origin, key: redactKey(key) });
|
|
110
|
+
return emit(result);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
module.exports = { run };
|
package/src/commands.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
const { usage } = require('./errors');
|
|
2
|
+
const { parseJsonArg } = require('./input');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @typedef {{name: string, type: 'string' | 'boolean', description: string, multiple?: boolean,
|
|
6
|
+
* required?: boolean, query?: string}} Flag
|
|
7
|
+
* @typedef {{name: string, description: string, guid?: boolean}} Arg
|
|
8
|
+
* @typedef {{name: string, summary: string, method: string | null, path: string | null, args: Arg[],
|
|
9
|
+
* flags: Flag[], body?: 'required' | 'optional', convenience?: string[], destructive?: boolean,
|
|
10
|
+
* auth?: boolean, build?: (flags: Record<string, any>) => unknown}} Command
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {string} name
|
|
15
|
+
* @param {string} description
|
|
16
|
+
* @param {Partial<Flag>} [extra]
|
|
17
|
+
* @returns {Flag}
|
|
18
|
+
*/
|
|
19
|
+
const str = (name, description, extra = {}) => ({ name, type: 'string', description, ...extra });
|
|
20
|
+
|
|
21
|
+
const PAGING = [
|
|
22
|
+
str('page', 'Page number (default 1)', { query: 'page' }),
|
|
23
|
+
str('page-size', 'Items per page (default 20)', { query: 'pageSize' }),
|
|
24
|
+
];
|
|
25
|
+
const IF_MATCH = str('if-match', 'ETag for optimistic concurrency');
|
|
26
|
+
const BODY = str('body', 'JSON request body: inline, @file.json, or - for stdin');
|
|
27
|
+
|
|
28
|
+
/** @param {string} name @param {string} description @returns {Arg} */
|
|
29
|
+
const id = (name, description) => ({ name, description, guid: true });
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Builds a body from the convenience flags, dropping unset fields.
|
|
33
|
+
* @param {Record<string, unknown>} fields
|
|
34
|
+
*/
|
|
35
|
+
const compact = (fields) => Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined));
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {string} name
|
|
39
|
+
* @param {string} summary
|
|
40
|
+
* @param {string | null} method
|
|
41
|
+
* @param {string | null} path
|
|
42
|
+
* @param {Partial<Command>} [extra]
|
|
43
|
+
* @returns {Command}
|
|
44
|
+
*/
|
|
45
|
+
const cmd = (name, summary, method, path, extra = {}) => ({ name, summary, method, path, args: [], flags: [], ...extra });
|
|
46
|
+
|
|
47
|
+
/** @type {Command[]} */
|
|
48
|
+
const COMMANDS = [
|
|
49
|
+
cmd('properties list', 'List properties', 'GET', '/openapi/Properties', {
|
|
50
|
+
flags: [str('search', 'Free-text search', { query: 'search' }), str('state', 'Two-letter state code', { query: 'stateCode' }), ...PAGING],
|
|
51
|
+
}),
|
|
52
|
+
cmd('properties get', 'Get one property', 'GET', '/openapi/Properties/{id}', { args: [id('id', 'Property id')] }),
|
|
53
|
+
cmd('properties create', 'Create a property', 'POST', '/openapi/Properties', { body: 'required', flags: [BODY] }),
|
|
54
|
+
cmd('properties update', 'Replace a property (wholesale)', 'PUT', '/openapi/Properties/{id}', {
|
|
55
|
+
args: [id('id', 'Property id')], body: 'required', flags: [BODY, IF_MATCH],
|
|
56
|
+
}),
|
|
57
|
+
cmd('properties photos list', 'List a property\'s photos', 'GET', '/openapi/Properties/{id}/photos', { args: [id('id', 'Property id')] }),
|
|
58
|
+
cmd('properties photos add', 'Import photos from URLs (background import)', 'POST', '/openapi/Properties/{id}/photos', {
|
|
59
|
+
args: [id('id', 'Property id')], body: 'required', convenience: ['url'],
|
|
60
|
+
flags: [str('url', 'Photo URL; repeat for several (or use --body)', { multiple: true }), BODY],
|
|
61
|
+
build: (f) => (f.url ? { photos: f.url.map((/** @type {string} */ url) => ({ url })) } : undefined),
|
|
62
|
+
}),
|
|
63
|
+
cmd('properties photos delete', 'Delete a photo', 'DELETE', '/openapi/Properties/{id}/photos/{photoId}', {
|
|
64
|
+
args: [id('id', 'Property id'), id('photoId', 'Photo id')], destructive: true,
|
|
65
|
+
}),
|
|
66
|
+
cmd('properties documents list', 'List a property\'s documents', 'GET', '/openapi/Properties/{id}/documents', { args: [id('id', 'Property id')] }),
|
|
67
|
+
cmd('properties documents add', 'Import documents from URLs (background import)', 'POST', '/openapi/Properties/{id}/documents', {
|
|
68
|
+
args: [id('id', 'Property id')], body: 'required', convenience: ['url'],
|
|
69
|
+
flags: [str('url', 'Document URL; repeat for several (or use --body)', { multiple: true }), BODY],
|
|
70
|
+
build: (f) => (f.url ? { documents: f.url.map((/** @type {string} */ url) => ({ url })) } : undefined),
|
|
71
|
+
}),
|
|
72
|
+
cmd('properties documents delete', 'Delete a document', 'DELETE', '/openapi/Properties/{id}/documents/{documentId}', {
|
|
73
|
+
args: [id('id', 'Property id'), id('documentId', 'Document id')], destructive: true,
|
|
74
|
+
}),
|
|
75
|
+
cmd('properties import-status', 'Get the status of a photo/document import', 'GET', '/openapi/Properties/{id}/imports/{importId}', {
|
|
76
|
+
args: [id('id', 'Property id'), id('importId', 'Import id')],
|
|
77
|
+
}),
|
|
78
|
+
cmd('offers list', 'List offers for a property', 'GET', '/openapi/Offers', {
|
|
79
|
+
flags: [str('property', 'Property id', { query: 'propertyId', required: true }), str('status', 'Offer status filter', { query: 'status' }), ...PAGING],
|
|
80
|
+
}),
|
|
81
|
+
cmd('offers get', 'Get one offer', 'GET', '/openapi/Offers/{id}', { args: [id('id', 'Offer id')] }),
|
|
82
|
+
cmd('offers history', 'Get an offer\'s revision history', 'GET', '/openapi/Offers/{id}/history', { args: [id('id', 'Offer id')] }),
|
|
83
|
+
cmd('offers accept', 'Accept an offer; returns the transaction', 'POST', '/openapi/Offers/{id}/accept', {
|
|
84
|
+
args: [id('id', 'Offer id')], destructive: true, body: 'optional', convenience: ['attributes'],
|
|
85
|
+
flags: [str('attributes', 'Homeowner-confirmed property attributes: JSON or @file'), IF_MATCH],
|
|
86
|
+
build: (f) => (f.attributes === undefined ? undefined : { attributes: parseJsonArg(f.attributes, '--attributes') }),
|
|
87
|
+
}),
|
|
88
|
+
cmd('offers request-details', 'Ask the agent for the offer\'s full breakdown', 'POST', '/openapi/Offers/{id}/request-details', {
|
|
89
|
+
args: [id('id', 'Offer id')], flags: [IF_MATCH],
|
|
90
|
+
}),
|
|
91
|
+
cmd('transactions get', 'Get one transaction', 'GET', '/openapi/Transactions/{id}', { args: [id('id', 'Transaction id')] }),
|
|
92
|
+
cmd('transactions active', 'Get a property\'s active transaction', 'GET', '/openapi/Transactions/active', {
|
|
93
|
+
flags: [str('property', 'Property id', { query: 'propertyId', required: true })],
|
|
94
|
+
}),
|
|
95
|
+
cmd('comping status', 'Get AI comping status for a transaction', 'GET', '/openapi/Transactions/{transactionId}/comping', {
|
|
96
|
+
args: [id('transactionId', 'Transaction id')],
|
|
97
|
+
}),
|
|
98
|
+
cmd('team members', 'List team members', 'GET', '/openapi/Team/members', {
|
|
99
|
+
flags: [str('search', 'Free-text search', { query: 'search' }), ...PAGING],
|
|
100
|
+
}),
|
|
101
|
+
cmd('team get', 'Get one team member', 'GET', '/openapi/Team/members/{id}', { args: [id('id', 'Member id')] }),
|
|
102
|
+
cmd('team invite', 'Invite a team member', 'POST', '/openapi/Team/members', {
|
|
103
|
+
body: 'required', convenience: ['email', 'first-name', 'last-name', 'team', 'admin-team'],
|
|
104
|
+
flags: [
|
|
105
|
+
str('email', 'Invitee email (or use --body)'), str('first-name', 'First name'), str('last-name', 'Last name'),
|
|
106
|
+
str('team', 'Team id to join; repeatable', { multiple: true }),
|
|
107
|
+
str('admin-team', 'Team id to administer; repeatable', { multiple: true }), BODY,
|
|
108
|
+
],
|
|
109
|
+
build: (f) => {
|
|
110
|
+
if (f.email === undefined) return undefined;
|
|
111
|
+
for (const t of [...(f.team || []), ...(f['admin-team'] || [])]) if (!GUID.test(t)) throw usage(`team id is not a GUID: ${t}`);
|
|
112
|
+
return compact({ email: f.email, teamIds: f.team, adminTeamIds: f['admin-team'], firstName: f['first-name'], lastName: f['last-name'] });
|
|
113
|
+
},
|
|
114
|
+
}),
|
|
115
|
+
cmd('team remove', 'Remove a team member', 'DELETE', '/openapi/Team/members/{id}', { args: [id('id', 'Member id')], destructive: true }),
|
|
116
|
+
cmd('teams list', 'List teams', 'GET', '/openapi/Team/teams', {
|
|
117
|
+
flags: [str('search', 'Free-text search', { query: 'search' }), ...PAGING],
|
|
118
|
+
}),
|
|
119
|
+
cmd('webhooks event-types', 'List webhook event types', 'GET', '/openapi/Webhooks/event-types'),
|
|
120
|
+
cmd('webhooks list', 'List webhook subscriptions', 'GET', '/openapi/Webhooks'),
|
|
121
|
+
cmd('webhooks create', 'Create a webhook subscription', 'POST', '/openapi/Webhooks', {
|
|
122
|
+
body: 'required', convenience: ['url', 'event'],
|
|
123
|
+
flags: [str('url', 'Endpoint URL (or use --body)'), str('event', 'Event type; repeatable', { multiple: true }), BODY],
|
|
124
|
+
build: (f) => (f.url === undefined ? undefined : compact({ endpointUrl: f.url, eventTypes: f.event })),
|
|
125
|
+
}),
|
|
126
|
+
cmd('webhooks update', 'Update a webhook subscription (endpointUrl, eventTypes, isActive)', 'PUT', '/openapi/Webhooks/{id}', {
|
|
127
|
+
args: [id('id', 'Subscription id')], body: 'required', flags: [BODY],
|
|
128
|
+
}),
|
|
129
|
+
cmd('webhooks rotate', 'Rotate a webhook signing secret', 'POST', '/openapi/Webhooks/{id}/rotate', {
|
|
130
|
+
args: [id('id', 'Subscription id')], destructive: true,
|
|
131
|
+
}),
|
|
132
|
+
cmd('webhooks delete', 'Delete a webhook subscription', 'DELETE', '/openapi/Webhooks/{id}', {
|
|
133
|
+
args: [id('id', 'Subscription id')], destructive: true,
|
|
134
|
+
}),
|
|
135
|
+
cmd('webhooks deliveries', 'List webhook deliveries', 'GET', '/openapi/Webhooks/deliveries', {
|
|
136
|
+
flags: [str('subscription', 'Subscription id', { query: 'subscriptionId' }), str('status', 'Delivery status', { query: 'status' }), ...PAGING],
|
|
137
|
+
}),
|
|
138
|
+
cmd('whoami', 'Check the API key and show the target origin', 'GET', '/openapi/Webhooks/event-types'),
|
|
139
|
+
cmd('openapi', 'Print the partner OpenAPI document (no key needed)', 'GET', '/_openapi/partner.json', { auth: false }),
|
|
140
|
+
cmd('api', 'Call any /openapi endpoint directly (DELETE needs --yes)', null, null, {
|
|
141
|
+
args: [{ name: 'method', description: 'GET, POST, PUT, PATCH or DELETE' }, { name: 'path', description: 'e.g. Properties or /openapi/Properties' }],
|
|
142
|
+
body: 'optional', flags: [str('query', 'Query parameter k=v; repeatable', { multiple: true }), BODY],
|
|
143
|
+
}),
|
|
144
|
+
cmd('commands', 'Print this command catalogue as JSON', null, null),
|
|
145
|
+
];
|
|
146
|
+
|
|
147
|
+
const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
148
|
+
|
|
149
|
+
/** Flags accepted by every command. */
|
|
150
|
+
const GLOBAL_FLAGS = /** @type {Flag[]} */ ([
|
|
151
|
+
str('env', 'prod (default) or dev; ZOODEALIO_API_URL overrides'),
|
|
152
|
+
{ name: 'pretty', type: 'boolean', description: 'Pretty-print JSON even when piped' },
|
|
153
|
+
{ name: 'dry-run', type: 'boolean', description: 'Print the request (key redacted) without sending it' },
|
|
154
|
+
{ name: 'yes', type: 'boolean', description: 'Confirm a destructive command (not needed with --dry-run)' },
|
|
155
|
+
{ name: 'help', type: 'boolean', description: 'Show help' },
|
|
156
|
+
]);
|
|
157
|
+
|
|
158
|
+
/** The machine-readable catalogue printed by `zoodealio commands`. */
|
|
159
|
+
function catalogue() {
|
|
160
|
+
return COMMANDS.map((c) => ({
|
|
161
|
+
name: c.name,
|
|
162
|
+
method: c.method,
|
|
163
|
+
path: c.path,
|
|
164
|
+
summary: c.summary,
|
|
165
|
+
args: c.args.map((a) => ({ name: a.name, required: true, description: a.description })),
|
|
166
|
+
flags: c.flags.map((f) => ({ name: f.name, type: f.type, required: !!f.required, multiple: !!f.multiple, description: f.description })),
|
|
167
|
+
destructive: !!c.destructive || c.name === 'api',
|
|
168
|
+
}));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* @param {Command} c
|
|
173
|
+
* @returns {string}
|
|
174
|
+
*/
|
|
175
|
+
function usageLine(c) {
|
|
176
|
+
const args = c.args.map((a) => `<${a.name}>`).join(' ');
|
|
177
|
+
const flags = c.flags.map((f) => (f.required ? `--${f.name} <v>` : `[--${f.name}${f.type === 'string' ? ' <v>' : ''}]`)).join(' ');
|
|
178
|
+
return ['zoodealio', c.name, args, flags].filter(Boolean).join(' ');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Help text for the given command-name prefix (empty = everything).
|
|
183
|
+
* @param {string[]} prefix
|
|
184
|
+
* @returns {string}
|
|
185
|
+
*/
|
|
186
|
+
function helpText(prefix) {
|
|
187
|
+
const matches = COMMANDS.filter((c) => prefix.every((p, i) => c.name.split(' ')[i] === p));
|
|
188
|
+
const exact = matches.find((c) => c.name === prefix.join(' '));
|
|
189
|
+
const lines = [];
|
|
190
|
+
if (exact) {
|
|
191
|
+
lines.push(usageLine(exact), '', exact.summary);
|
|
192
|
+
if (exact.method && exact.path) lines.push(`${exact.method} ${exact.path}`);
|
|
193
|
+
if (exact.destructive) lines.push('Destructive: requires --yes.');
|
|
194
|
+
for (const a of exact.args) lines.push(` <${a.name}> ${a.description}`);
|
|
195
|
+
for (const f of exact.flags) lines.push(` --${f.name} ${f.description}${f.required ? ' (required)' : ''}`);
|
|
196
|
+
} else {
|
|
197
|
+
lines.push('zoodealio <command> [args] [flags]', '', 'JSON on stdout; errors as JSON on stderr. Key: ZOODEALIO_API_KEY.', '');
|
|
198
|
+
for (const c of matches) lines.push(` ${c.name.padEnd(28)}${c.summary}`);
|
|
199
|
+
lines.push('', 'Global flags:');
|
|
200
|
+
for (const f of GLOBAL_FLAGS) lines.push(` --${f.name.padEnd(10)}${f.description}`);
|
|
201
|
+
lines.push('', 'Exit codes: 0 ok, 1 error, 2 usage, 3 auth, 4 not found, 5 conflict/validation, 6 rate limited.');
|
|
202
|
+
}
|
|
203
|
+
return `${lines.join('\n')}\n`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
module.exports = { COMMANDS, GLOBAL_FLAGS, GUID, catalogue, helpText, usageLine };
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An error the CLI reports as one JSON object on stderr and maps to an exit code.
|
|
3
|
+
*/
|
|
4
|
+
class CliError extends Error {
|
|
5
|
+
/**
|
|
6
|
+
* @param {{exit: number, status?: number | null, code: string, title: string, detail?: string, retryAfter?: number}} info
|
|
7
|
+
*/
|
|
8
|
+
constructor(info) {
|
|
9
|
+
super(info.detail || info.title);
|
|
10
|
+
this.exit = info.exit;
|
|
11
|
+
this.status = info.status ?? null;
|
|
12
|
+
this.code = info.code;
|
|
13
|
+
this.title = info.title;
|
|
14
|
+
this.detail = info.detail;
|
|
15
|
+
this.retryAfter = info.retryAfter;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
toJSON() {
|
|
19
|
+
const error = { status: this.status, code: this.code, title: this.title };
|
|
20
|
+
if (this.detail) error.detail = this.detail;
|
|
21
|
+
if (this.retryAfter !== undefined) error.retryAfter = this.retryAfter;
|
|
22
|
+
return { error };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {string} detail */
|
|
27
|
+
const usage = (detail) => new CliError({ exit: 2, code: 'usage', title: 'Usage error', detail });
|
|
28
|
+
|
|
29
|
+
module.exports = { CliError, usage };
|
package/src/http.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
const { CliError, usage } = require('./errors');
|
|
2
|
+
|
|
3
|
+
const ENVS = { prod: 'https://api.zoodealio.ai', dev: 'https://dev.api.zoodealio.ai' };
|
|
4
|
+
|
|
5
|
+
/** @type {Record<number, [number, string]>} status -> [exit code, error code slug] */
|
|
6
|
+
const STATUS_MAP = {
|
|
7
|
+
400: [2, 'bad_request'],
|
|
8
|
+
401: [3, 'unauthorized'],
|
|
9
|
+
403: [3, 'forbidden'],
|
|
10
|
+
404: [4, 'not_found'],
|
|
11
|
+
409: [5, 'conflict'],
|
|
12
|
+
412: [5, 'precondition_failed'],
|
|
13
|
+
422: [5, 'validation_failed'],
|
|
14
|
+
429: [6, 'rate_limited'],
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {string | undefined} key
|
|
19
|
+
* @returns {string}
|
|
20
|
+
*/
|
|
21
|
+
function redactKey(key) {
|
|
22
|
+
if (!key) return '<not set>';
|
|
23
|
+
return key.length >= 12 ? `zoo_…${key.slice(-4)}` : 'zoo_…';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {Record<string, string | undefined>} env
|
|
28
|
+
* @param {string | undefined} envName
|
|
29
|
+
* @returns {string} origin without trailing slash
|
|
30
|
+
*/
|
|
31
|
+
function resolveOrigin(env, envName) {
|
|
32
|
+
const override = env.ZOODEALIO_API_URL;
|
|
33
|
+
if (override) return override.replace(/\/+$/, '');
|
|
34
|
+
const name = envName || 'prod';
|
|
35
|
+
if (!Object.hasOwn(ENVS, name)) throw usage('--env must be prod or dev');
|
|
36
|
+
return ENVS[/** @type {'prod'|'dev'} */ (name)];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {string} origin
|
|
41
|
+
* @param {string} path
|
|
42
|
+
* @param {[string, string][]} query
|
|
43
|
+
*/
|
|
44
|
+
function buildUrl(origin, path, query) {
|
|
45
|
+
const qs = new URLSearchParams(query).toString();
|
|
46
|
+
return `${origin}${path}${qs ? `?${qs}` : ''}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** @param {unknown} err */
|
|
50
|
+
function describe(err) {
|
|
51
|
+
const e = /** @type {{message?: string, cause?: {message?: string}}} */ (err);
|
|
52
|
+
return (e && (e.cause?.message || e.message)) || 'request failed';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {Response} res
|
|
57
|
+
* @param {string} text
|
|
58
|
+
*/
|
|
59
|
+
function errorFromResponse(res, text) {
|
|
60
|
+
let problem = /** @type {{title?: string, detail?: string}} */ ({});
|
|
61
|
+
try {
|
|
62
|
+
const parsed = JSON.parse(text);
|
|
63
|
+
if (parsed && typeof parsed === 'object') problem = parsed;
|
|
64
|
+
} catch {
|
|
65
|
+
// non-JSON error body
|
|
66
|
+
}
|
|
67
|
+
const [exit, code] = STATUS_MAP[res.status] || [1, 'http_error'];
|
|
68
|
+
const retryHeader = res.headers.get('retry-after');
|
|
69
|
+
const retry = retryHeader === null ? NaN : Number(retryHeader);
|
|
70
|
+
return new CliError({
|
|
71
|
+
exit,
|
|
72
|
+
status: res.status,
|
|
73
|
+
code,
|
|
74
|
+
title: typeof problem.title === 'string' ? problem.title : res.statusText || `HTTP ${res.status}`,
|
|
75
|
+
detail: typeof problem.detail === 'string' ? problem.detail : undefined,
|
|
76
|
+
retryAfter: res.status === 429 && Number.isFinite(retry) && retry >= 0 ? retry : undefined,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Sends one request. Redirects are refused so the ApiKey header cannot be forwarded elsewhere.
|
|
82
|
+
* @param {typeof fetch} doFetch
|
|
83
|
+
* @param {{method: string, url: string, headers: Record<string, string>, body?: unknown}} req
|
|
84
|
+
* @returns {Promise<unknown>} parsed JSON, or null for an empty/204 response
|
|
85
|
+
*/
|
|
86
|
+
async function send(doFetch, req) {
|
|
87
|
+
let res;
|
|
88
|
+
let text;
|
|
89
|
+
try {
|
|
90
|
+
res = await doFetch(req.url, {
|
|
91
|
+
method: req.method,
|
|
92
|
+
headers: req.headers,
|
|
93
|
+
body: req.body === undefined ? undefined : JSON.stringify(req.body),
|
|
94
|
+
redirect: 'error',
|
|
95
|
+
signal: AbortSignal.timeout(30000),
|
|
96
|
+
});
|
|
97
|
+
text = await res.text();
|
|
98
|
+
} catch (err) {
|
|
99
|
+
throw new CliError({ exit: 1, code: 'network_error', title: 'Request failed', detail: describe(err) });
|
|
100
|
+
}
|
|
101
|
+
if (!res.ok) throw errorFromResponse(res, text);
|
|
102
|
+
if (res.status === 204 || text === '') return null;
|
|
103
|
+
try {
|
|
104
|
+
return JSON.parse(text);
|
|
105
|
+
} catch {
|
|
106
|
+
return text;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
module.exports = { ENVS, redactKey, resolveOrigin, buildUrl, send };
|
package/src/input.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const fs = require('node:fs');
|
|
2
|
+
const { usage } = require('./errors');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Parses inline JSON or `@file` JSON.
|
|
6
|
+
* @param {string} text
|
|
7
|
+
* @param {string} label
|
|
8
|
+
* @returns {unknown}
|
|
9
|
+
*/
|
|
10
|
+
function parseJsonArg(text, label) {
|
|
11
|
+
let raw = text;
|
|
12
|
+
if (text.startsWith('@')) {
|
|
13
|
+
try {
|
|
14
|
+
raw = fs.readFileSync(text.slice(1), 'utf8');
|
|
15
|
+
} catch {
|
|
16
|
+
throw usage(`cannot read ${label} file: ${text.slice(1)}`);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(raw);
|
|
21
|
+
} catch {
|
|
22
|
+
throw usage(`${label} is not valid JSON`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Resolves a --body value: inline JSON, `@file`, or `-` for stdin.
|
|
28
|
+
* @param {string} text
|
|
29
|
+
* @param {AsyncIterable<string | Buffer>} stdin
|
|
30
|
+
* @returns {Promise<unknown>}
|
|
31
|
+
*/
|
|
32
|
+
async function resolveBody(text, stdin) {
|
|
33
|
+
if (text !== '-') return parseJsonArg(text, '--body');
|
|
34
|
+
const chunks = [];
|
|
35
|
+
for await (const chunk of stdin) chunks.push(Buffer.from(chunk));
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
38
|
+
} catch {
|
|
39
|
+
throw usage('--body (stdin) is not valid JSON');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = { parseJsonArg, resolveBody };
|