@zilfu/cli 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/LICENSE +21 -0
- package/README.md +61 -0
- package/dist/cli.js +510 -0
- package/dist/cli.js.map +1 -0
- package/package.json +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Zilfu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# @zilfu/cli
|
|
2
|
+
|
|
3
|
+
Official command-line interface for the [Zilfu](https://zilfu.app) API. A thin
|
|
4
|
+
wrapper around [`@zilfu/sdk`](https://www.npmjs.com/package/@zilfu/sdk).
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install -g @zilfu/cli
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Requires Node.js >= 18.17.
|
|
13
|
+
|
|
14
|
+
## Authenticate
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
zilfu login --web # authorize in the browser (recommended)
|
|
18
|
+
zilfu login # prompts for a token (hidden input)
|
|
19
|
+
zilfu login --token <token> # non-interactive
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`--web` opens a Zilfu consent screen in your browser, mints a token for the
|
|
23
|
+
already-signed-in account, and hands it back to the CLI over a local loopback
|
|
24
|
+
callback (PKCE-protected). If a browser can't be opened, the authorize URL is
|
|
25
|
+
printed — open it on any machine that can reach the printed `127.0.0.1` port.
|
|
26
|
+
|
|
27
|
+
Otherwise, create a token manually at **Settings → API tokens** and paste it.
|
|
28
|
+
Credentials are stored at `~/.config/zilfu/config.json` (mode `600`).
|
|
29
|
+
|
|
30
|
+
You can also authenticate per-invocation without `login`:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
export ZILFU_TOKEN=<token>
|
|
34
|
+
zilfu spaces list
|
|
35
|
+
# or
|
|
36
|
+
zilfu spaces list --token <token> --base-url https://zilfu.app/api
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Token resolution precedence: `--token` flag → `ZILFU_TOKEN` → stored config.
|
|
40
|
+
|
|
41
|
+
## Commands
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
zilfu whoami # current user
|
|
45
|
+
zilfu health # API health (no auth required)
|
|
46
|
+
zilfu spaces list # spaces you can access
|
|
47
|
+
zilfu accounts list --space <id> # connected accounts in a space
|
|
48
|
+
zilfu posts list --space <id> # posts in a space
|
|
49
|
+
zilfu logout # remove stored credentials
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Global flags: `--token`, `--base-url`, `--json`. Pass `--json` to any command
|
|
53
|
+
for raw, pipeable JSON output.
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
zilfu spaces list --json | jq '.[].name'
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
MIT
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { defineCommand, runMain } from 'citty';
|
|
3
|
+
import { createZilfuClient, ZilfuApiError } from '@zilfu/sdk';
|
|
4
|
+
import { hostname, homedir } from 'os';
|
|
5
|
+
import { join } from 'path';
|
|
6
|
+
import { existsSync, rmSync, mkdirSync, writeFileSync, chmodSync, readFileSync } from 'fs';
|
|
7
|
+
import 'buffer';
|
|
8
|
+
import { createServer } from 'http';
|
|
9
|
+
import { randomBytes, createHash } from 'crypto';
|
|
10
|
+
import { spawn } from 'child_process';
|
|
11
|
+
|
|
12
|
+
function configDir() {
|
|
13
|
+
if (process.platform === "win32") {
|
|
14
|
+
const appData = process.env.APPDATA ?? join(homedir(), "AppData", "Roaming");
|
|
15
|
+
return join(appData, "zilfu");
|
|
16
|
+
}
|
|
17
|
+
const base = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
|
|
18
|
+
return join(base, "zilfu");
|
|
19
|
+
}
|
|
20
|
+
function configPath() {
|
|
21
|
+
return join(configDir(), "config.json");
|
|
22
|
+
}
|
|
23
|
+
function readConfig() {
|
|
24
|
+
try {
|
|
25
|
+
const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
|
|
26
|
+
if (parsed && typeof parsed === "object") {
|
|
27
|
+
return parsed;
|
|
28
|
+
}
|
|
29
|
+
} catch {
|
|
30
|
+
}
|
|
31
|
+
return {};
|
|
32
|
+
}
|
|
33
|
+
function writeConfig(config) {
|
|
34
|
+
mkdirSync(configDir(), { recursive: true });
|
|
35
|
+
const path = configPath();
|
|
36
|
+
writeFileSync(path, `${JSON.stringify(config, null, 2)}
|
|
37
|
+
`, { mode: 384 });
|
|
38
|
+
chmodSync(path, 384);
|
|
39
|
+
return path;
|
|
40
|
+
}
|
|
41
|
+
function clearConfig() {
|
|
42
|
+
const path = configPath();
|
|
43
|
+
if (existsSync(path)) {
|
|
44
|
+
rmSync(path);
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
var CTRL_C = String.fromCharCode(3);
|
|
50
|
+
var CTRL_D = String.fromCharCode(4);
|
|
51
|
+
var DEL = String.fromCharCode(127);
|
|
52
|
+
var BACKSPACE = String.fromCharCode(8);
|
|
53
|
+
var SUBMIT = /* @__PURE__ */ new Set(["\r", "\n", CTRL_D]);
|
|
54
|
+
var DELETE = /* @__PURE__ */ new Set([DEL, BACKSPACE]);
|
|
55
|
+
function promptSecret(label) {
|
|
56
|
+
return new Promise((resolve) => {
|
|
57
|
+
const { stdin, stdout } = process;
|
|
58
|
+
stdout.write(label);
|
|
59
|
+
stdin.setRawMode(true);
|
|
60
|
+
stdin.resume();
|
|
61
|
+
let input = "";
|
|
62
|
+
const finish = () => {
|
|
63
|
+
stdin.setRawMode(false);
|
|
64
|
+
stdin.pause();
|
|
65
|
+
stdin.removeListener("data", onData);
|
|
66
|
+
stdout.write("\n");
|
|
67
|
+
};
|
|
68
|
+
const onData = (chunk) => {
|
|
69
|
+
for (const char of chunk.toString("utf8")) {
|
|
70
|
+
if (char === CTRL_C) {
|
|
71
|
+
finish();
|
|
72
|
+
process.exit(130);
|
|
73
|
+
}
|
|
74
|
+
if (SUBMIT.has(char)) {
|
|
75
|
+
finish();
|
|
76
|
+
resolve(input);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (DELETE.has(char)) {
|
|
80
|
+
input = input.slice(0, -1);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (char >= " ") {
|
|
84
|
+
input += char;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
stdin.on("data", onData);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
var TIMEOUT_MS = 5 * 60 * 1e3;
|
|
92
|
+
function base64url(buffer) {
|
|
93
|
+
return buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
94
|
+
}
|
|
95
|
+
function createPkce() {
|
|
96
|
+
const verifier = base64url(randomBytes(32));
|
|
97
|
+
const challenge = base64url(createHash("sha256").update(verifier).digest());
|
|
98
|
+
return { verifier, challenge };
|
|
99
|
+
}
|
|
100
|
+
function webOrigin(baseUrl) {
|
|
101
|
+
const url = new URL(baseUrl);
|
|
102
|
+
url.pathname = url.pathname.replace(/\/api\/?$/, "/");
|
|
103
|
+
return url.toString().replace(/\/$/, "");
|
|
104
|
+
}
|
|
105
|
+
function openBrowser(url) {
|
|
106
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
107
|
+
try {
|
|
108
|
+
const child = spawn(command, args, { stdio: "ignore", detached: true });
|
|
109
|
+
child.on("error", () => {
|
|
110
|
+
});
|
|
111
|
+
child.unref();
|
|
112
|
+
} catch {
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
var DONE_PAGE = '<!doctype html><meta charset=utf-8><title>Zilfu CLI</title><body style="font-family:system-ui;display:grid;place-items:center;height:100vh;margin:0"><p>Authorization complete. You can close this tab and return to your terminal.</p>';
|
|
116
|
+
function loginViaBrowser(baseUrl) {
|
|
117
|
+
const origin = webOrigin(baseUrl);
|
|
118
|
+
const { verifier, challenge } = createPkce();
|
|
119
|
+
const state = randomBytes(16).toString("hex");
|
|
120
|
+
return new Promise((resolve, reject) => {
|
|
121
|
+
const server = createServer((req, res) => {
|
|
122
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
123
|
+
if (url.pathname !== "/callback") {
|
|
124
|
+
res.writeHead(204).end();
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
res.writeHead(200, { "content-type": "text/html" }).end(DONE_PAGE);
|
|
128
|
+
const error = url.searchParams.get("error");
|
|
129
|
+
if (error) {
|
|
130
|
+
settle(reject, new Error(`Authorization was denied (${error}).`));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (url.searchParams.get("state") !== state) {
|
|
134
|
+
settle(reject, new Error("State mismatch \u2014 aborting for safety."));
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const code = url.searchParams.get("code");
|
|
138
|
+
if (!code) {
|
|
139
|
+
settle(reject, new Error("No authorization code received."));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
exchange(origin, code, verifier).then(
|
|
143
|
+
(token) => settle(resolve, token),
|
|
144
|
+
(err) => settle(reject, err)
|
|
145
|
+
);
|
|
146
|
+
});
|
|
147
|
+
const timer = setTimeout(() => {
|
|
148
|
+
settle(reject, new Error("Timed out waiting for browser authorization."));
|
|
149
|
+
}, TIMEOUT_MS);
|
|
150
|
+
function settle(fn, value) {
|
|
151
|
+
clearTimeout(timer);
|
|
152
|
+
server.close();
|
|
153
|
+
fn(value);
|
|
154
|
+
}
|
|
155
|
+
server.on("error", (err) => settle(reject, err));
|
|
156
|
+
server.listen(0, "127.0.0.1", () => {
|
|
157
|
+
const { port } = server.address();
|
|
158
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
159
|
+
const authorizeUrl = `${origin}/cli/authorize?${new URLSearchParams({
|
|
160
|
+
redirect_uri: redirectUri,
|
|
161
|
+
state,
|
|
162
|
+
code_challenge: challenge,
|
|
163
|
+
name: `zilfu-cli (${hostname()})`
|
|
164
|
+
}).toString()}`;
|
|
165
|
+
process.stdout.write(
|
|
166
|
+
`Opening your browser to authorize access:
|
|
167
|
+
${authorizeUrl}
|
|
168
|
+
|
|
169
|
+
Waiting for authorization\u2026
|
|
170
|
+
`
|
|
171
|
+
);
|
|
172
|
+
openBrowser(authorizeUrl);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
async function exchange(origin, code, verifier) {
|
|
177
|
+
const res = await fetch(`${origin}/cli/token`, {
|
|
178
|
+
method: "POST",
|
|
179
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
180
|
+
body: JSON.stringify({ code, code_verifier: verifier })
|
|
181
|
+
});
|
|
182
|
+
if (!res.ok) {
|
|
183
|
+
throw new Error(`Token exchange failed (HTTP ${res.status}).`);
|
|
184
|
+
}
|
|
185
|
+
const body = await res.json();
|
|
186
|
+
if (!body.token) {
|
|
187
|
+
throw new Error("Token exchange returned no token.");
|
|
188
|
+
}
|
|
189
|
+
return body.token;
|
|
190
|
+
}
|
|
191
|
+
var MissingTokenError = class extends Error {
|
|
192
|
+
constructor() {
|
|
193
|
+
super(
|
|
194
|
+
"No API token found.\nRun `zilfu login`, set ZILFU_TOKEN, or pass --token <token>.\nCreate a token at Settings \u2192 API tokens."
|
|
195
|
+
);
|
|
196
|
+
this.name = "MissingTokenError";
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
function resolveToken(flags) {
|
|
200
|
+
return flags.token ?? process.env.ZILFU_TOKEN ?? readConfig().token;
|
|
201
|
+
}
|
|
202
|
+
function resolveBaseUrl(flags) {
|
|
203
|
+
return flags.baseUrl ?? process.env.ZILFU_BASE_URL ?? readConfig().baseUrl;
|
|
204
|
+
}
|
|
205
|
+
function resolveClient(flags, opts = {}) {
|
|
206
|
+
const token = resolveToken(flags);
|
|
207
|
+
if (!token && opts.requireToken !== false) {
|
|
208
|
+
throw new MissingTokenError();
|
|
209
|
+
}
|
|
210
|
+
return createZilfuClient({
|
|
211
|
+
token: token ?? "",
|
|
212
|
+
baseUrl: resolveBaseUrl(flags)
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
function formatCell(value) {
|
|
216
|
+
if (value === null || value === void 0) {
|
|
217
|
+
return "";
|
|
218
|
+
}
|
|
219
|
+
if (typeof value === "object") {
|
|
220
|
+
return JSON.stringify(value);
|
|
221
|
+
}
|
|
222
|
+
return String(value);
|
|
223
|
+
}
|
|
224
|
+
function inferColumns(rows) {
|
|
225
|
+
const first = rows[0] ?? {};
|
|
226
|
+
return Object.keys(first).filter((key) => {
|
|
227
|
+
const value = first[key];
|
|
228
|
+
return value === null || typeof value !== "object";
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
function printTable(rows, columns) {
|
|
232
|
+
if (rows.length === 0) {
|
|
233
|
+
process.stdout.write("No results.\n");
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const cols = columns ?? inferColumns(rows);
|
|
237
|
+
const widths = cols.map(
|
|
238
|
+
(col) => Math.max(col.length, ...rows.map((row) => formatCell(row[col]).length))
|
|
239
|
+
);
|
|
240
|
+
const line = (cells) => `${cells.map((cell, i) => cell.padEnd(widths[i])).join(" ").replace(/\s+$/, "")}
|
|
241
|
+
`;
|
|
242
|
+
process.stdout.write(line(cols));
|
|
243
|
+
process.stdout.write(line(cols.map((_, i) => "-".repeat(widths[i]))));
|
|
244
|
+
for (const row of rows) {
|
|
245
|
+
process.stdout.write(line(cols.map((col) => formatCell(row[col]))));
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function printRecord(record) {
|
|
249
|
+
const keys = Object.keys(record);
|
|
250
|
+
if (keys.length === 0) {
|
|
251
|
+
process.stdout.write("(empty)\n");
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const width = Math.max(...keys.map((key) => key.length));
|
|
255
|
+
for (const key of keys) {
|
|
256
|
+
process.stdout.write(`${key.padEnd(width)} ${formatCell(record[key])}
|
|
257
|
+
`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function print(data, opts = {}) {
|
|
261
|
+
if (opts.json) {
|
|
262
|
+
process.stdout.write(`${JSON.stringify(data, null, 2)}
|
|
263
|
+
`);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (Array.isArray(data)) {
|
|
267
|
+
printTable(data, opts.columns);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (data && typeof data === "object") {
|
|
271
|
+
printRecord(data);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
process.stdout.write(`${formatCell(data)}
|
|
275
|
+
`);
|
|
276
|
+
}
|
|
277
|
+
function printError(error) {
|
|
278
|
+
if (error instanceof ZilfuApiError) {
|
|
279
|
+
process.stderr.write(`Error ${error.status}: ${error.message}
|
|
280
|
+
`);
|
|
281
|
+
if (error.errors) {
|
|
282
|
+
for (const [field, messages] of Object.entries(error.errors)) {
|
|
283
|
+
for (const message of messages) {
|
|
284
|
+
process.stderr.write(` - ${field}: ${message}
|
|
285
|
+
`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
} else if (error instanceof Error) {
|
|
290
|
+
process.stderr.write(`${error.message}
|
|
291
|
+
`);
|
|
292
|
+
} else {
|
|
293
|
+
process.stderr.write(`${String(error)}
|
|
294
|
+
`);
|
|
295
|
+
}
|
|
296
|
+
return process.exit(1);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// src/commands/_shared.ts
|
|
300
|
+
var globalArgs = {
|
|
301
|
+
token: {
|
|
302
|
+
type: "string",
|
|
303
|
+
description: "API token (overrides ZILFU_TOKEN and stored config)"
|
|
304
|
+
},
|
|
305
|
+
"base-url": {
|
|
306
|
+
type: "string",
|
|
307
|
+
description: "API base URL (overrides ZILFU_BASE_URL and stored config)"
|
|
308
|
+
},
|
|
309
|
+
json: {
|
|
310
|
+
type: "boolean",
|
|
311
|
+
description: "Output raw JSON instead of a table"
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
function readString(value) {
|
|
315
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
316
|
+
}
|
|
317
|
+
function clientFor(args, opts) {
|
|
318
|
+
return resolveClient(
|
|
319
|
+
{ token: readString(args["token"]), baseUrl: readString(args["base-url"]) },
|
|
320
|
+
opts
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
function wantsJson(args) {
|
|
324
|
+
return args["json"] === true;
|
|
325
|
+
}
|
|
326
|
+
function toSpaceId(value) {
|
|
327
|
+
const id = Number(value);
|
|
328
|
+
if (!Number.isInteger(id) || id <= 0) {
|
|
329
|
+
throw new Error(`Invalid space id: ${String(value)}`);
|
|
330
|
+
}
|
|
331
|
+
return id;
|
|
332
|
+
}
|
|
333
|
+
async function guard(fn) {
|
|
334
|
+
try {
|
|
335
|
+
await fn();
|
|
336
|
+
} catch (error) {
|
|
337
|
+
printError(error);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// src/commands/login.ts
|
|
342
|
+
var login = defineCommand({
|
|
343
|
+
meta: { name: "login", description: "Authenticate and store your API token" },
|
|
344
|
+
args: {
|
|
345
|
+
web: {
|
|
346
|
+
type: "boolean",
|
|
347
|
+
description: "Authorize in the browser instead of pasting a token"
|
|
348
|
+
},
|
|
349
|
+
token: {
|
|
350
|
+
type: "string",
|
|
351
|
+
description: "API token (skips the interactive prompt)"
|
|
352
|
+
},
|
|
353
|
+
"base-url": {
|
|
354
|
+
type: "string",
|
|
355
|
+
description: "API base URL to store (defaults to the production API)"
|
|
356
|
+
}
|
|
357
|
+
},
|
|
358
|
+
run: ({ args }) => guard(async () => {
|
|
359
|
+
const baseUrl = typeof args["base-url"] === "string" && args["base-url"] ? args["base-url"] : process.env.ZILFU_BASE_URL;
|
|
360
|
+
const token = args["web"] === true ? await loginViaBrowser(baseUrl ?? "https://zilfu.app/api") : await promptToken(typeof args["token"] === "string" ? args["token"] : "");
|
|
361
|
+
const api = createZilfuClient({ token, baseUrl });
|
|
362
|
+
const res = await api.session.get();
|
|
363
|
+
const user = res.data?.data;
|
|
364
|
+
const path = writeConfig({ token, ...baseUrl ? { baseUrl } : {} });
|
|
365
|
+
process.stdout.write(
|
|
366
|
+
`Logged in as ${user?.name ?? "?"} <${user?.email ?? "?"}>.
|
|
367
|
+
Credentials stored at ${path}
|
|
368
|
+
`
|
|
369
|
+
);
|
|
370
|
+
})
|
|
371
|
+
});
|
|
372
|
+
async function promptToken(flagToken) {
|
|
373
|
+
let token = flagToken;
|
|
374
|
+
if (!token) {
|
|
375
|
+
if (!process.stdin.isTTY) {
|
|
376
|
+
throw new Error(
|
|
377
|
+
"No token provided. Pass --token <token>, use --web, or run in an interactive terminal."
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
process.stdout.write("Create a token at Settings -> API tokens.\n");
|
|
381
|
+
token = await promptSecret("Zilfu API token: ");
|
|
382
|
+
}
|
|
383
|
+
token = token.trim();
|
|
384
|
+
if (!token) {
|
|
385
|
+
throw new Error("A token is required.");
|
|
386
|
+
}
|
|
387
|
+
return token;
|
|
388
|
+
}
|
|
389
|
+
var logout = defineCommand({
|
|
390
|
+
meta: { name: "logout", description: "Remove stored credentials" },
|
|
391
|
+
run: () => guard(() => {
|
|
392
|
+
const removed = clearConfig();
|
|
393
|
+
process.stdout.write(
|
|
394
|
+
removed ? "Logged out.\n" : "No stored credentials found.\n"
|
|
395
|
+
);
|
|
396
|
+
})
|
|
397
|
+
});
|
|
398
|
+
var whoami = defineCommand({
|
|
399
|
+
meta: { name: "whoami", description: "Show the authenticated user" },
|
|
400
|
+
args: { ...globalArgs },
|
|
401
|
+
run: ({ args }) => guard(async () => {
|
|
402
|
+
const api = clientFor(args);
|
|
403
|
+
const res = await api.session.get();
|
|
404
|
+
print(res.data?.data ?? {}, { json: wantsJson(args) });
|
|
405
|
+
})
|
|
406
|
+
});
|
|
407
|
+
var health = defineCommand({
|
|
408
|
+
meta: { name: "health", description: "Check the Zilfu API health" },
|
|
409
|
+
args: { ...globalArgs },
|
|
410
|
+
run: ({ args }) => guard(async () => {
|
|
411
|
+
const api = clientFor(args, { requireToken: false });
|
|
412
|
+
const res = await api.health.check();
|
|
413
|
+
print(res.data ?? {}, { json: wantsJson(args) });
|
|
414
|
+
})
|
|
415
|
+
});
|
|
416
|
+
var list = defineCommand({
|
|
417
|
+
meta: { name: "list", description: "List spaces you can access" },
|
|
418
|
+
args: { ...globalArgs },
|
|
419
|
+
run: ({ args }) => guard(async () => {
|
|
420
|
+
const api = clientFor(args);
|
|
421
|
+
const res = await api.spaces.list();
|
|
422
|
+
print(res.data?.data ?? [], {
|
|
423
|
+
json: wantsJson(args),
|
|
424
|
+
columns: ["id", "name", "timezone"]
|
|
425
|
+
});
|
|
426
|
+
})
|
|
427
|
+
});
|
|
428
|
+
var spaces = defineCommand({
|
|
429
|
+
meta: { name: "spaces", description: "Manage spaces" },
|
|
430
|
+
subCommands: { list }
|
|
431
|
+
});
|
|
432
|
+
var list2 = defineCommand({
|
|
433
|
+
meta: { name: "list", description: "List connected accounts in a space" },
|
|
434
|
+
args: {
|
|
435
|
+
...globalArgs,
|
|
436
|
+
space: { type: "string", required: true, description: "The space id" }
|
|
437
|
+
},
|
|
438
|
+
run: ({ args }) => guard(async () => {
|
|
439
|
+
const space = toSpaceId(args["space"]);
|
|
440
|
+
const api = clientFor(args);
|
|
441
|
+
const res = await api.accounts.list({ path: { space } });
|
|
442
|
+
print(res.data?.data ?? [], {
|
|
443
|
+
json: wantsJson(args),
|
|
444
|
+
columns: ["id", "social", "display_name", "handler", "is_active"]
|
|
445
|
+
});
|
|
446
|
+
})
|
|
447
|
+
});
|
|
448
|
+
var accounts = defineCommand({
|
|
449
|
+
meta: { name: "accounts", description: "Manage connected accounts" },
|
|
450
|
+
subCommands: { list: list2 }
|
|
451
|
+
});
|
|
452
|
+
var STATUS_LABELS = {
|
|
453
|
+
0: "scheduled",
|
|
454
|
+
1: "published",
|
|
455
|
+
2: "error",
|
|
456
|
+
3: "draft",
|
|
457
|
+
4: "processing"
|
|
458
|
+
};
|
|
459
|
+
function statusLabel(status) {
|
|
460
|
+
return STATUS_LABELS[status] ?? String(status);
|
|
461
|
+
}
|
|
462
|
+
var list3 = defineCommand({
|
|
463
|
+
meta: { name: "list", description: "List posts in a space" },
|
|
464
|
+
args: {
|
|
465
|
+
...globalArgs,
|
|
466
|
+
space: { type: "string", required: true, description: "The space id" }
|
|
467
|
+
},
|
|
468
|
+
run: ({ args }) => guard(async () => {
|
|
469
|
+
const space = toSpaceId(args["space"]);
|
|
470
|
+
const api = clientFor(args);
|
|
471
|
+
const res = await api.posts.list({ path: { space } });
|
|
472
|
+
const posts2 = res.data?.data ?? [];
|
|
473
|
+
if (wantsJson(args)) {
|
|
474
|
+
print(posts2, { json: true });
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
const rows = posts2.map((post) => ({
|
|
478
|
+
id: post.id,
|
|
479
|
+
status: statusLabel(post.status),
|
|
480
|
+
scheduled_at: post.scheduled_at,
|
|
481
|
+
published_at: post.published_at
|
|
482
|
+
}));
|
|
483
|
+
print(rows, { columns: ["id", "status", "scheduled_at", "published_at"] });
|
|
484
|
+
})
|
|
485
|
+
});
|
|
486
|
+
var posts = defineCommand({
|
|
487
|
+
meta: { name: "posts", description: "Manage posts" },
|
|
488
|
+
subCommands: { list: list3 }
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
// src/cli.ts
|
|
492
|
+
var main = defineCommand({
|
|
493
|
+
meta: {
|
|
494
|
+
name: "zilfu",
|
|
495
|
+
version: "0.1.0",
|
|
496
|
+
description: "Zilfu command-line interface"
|
|
497
|
+
},
|
|
498
|
+
subCommands: {
|
|
499
|
+
login,
|
|
500
|
+
logout,
|
|
501
|
+
whoami,
|
|
502
|
+
health,
|
|
503
|
+
spaces,
|
|
504
|
+
accounts,
|
|
505
|
+
posts
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
runMain(main);
|
|
509
|
+
//# sourceMappingURL=cli.js.map
|
|
510
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/prompt.ts","../src/web-auth.ts","../src/client.ts","../src/output.ts","../src/commands/_shared.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/whoami.ts","../src/commands/health.ts","../src/commands/spaces.ts","../src/commands/accounts.ts","../src/commands/posts.ts","../src/cli.ts"],"names":["createZilfuClient","defineCommand","list","posts"],"mappings":";;;;;;;;;;;AAkBA,SAAS,SAAA,GAAoB;AAC3B,EAAA,IAAI,OAAA,CAAQ,aAAa,OAAA,EAAS;AAChC,IAAA,MAAM,OAAA,GAAU,QAAQ,GAAA,CAAI,OAAA,IAAW,KAAK,OAAA,EAAQ,EAAG,WAAW,SAAS,CAAA;AAC3E,IAAA,OAAO,IAAA,CAAK,SAAS,OAAO,CAAA;AAAA,EAC9B;AACA,EAAA,MAAM,OAAO,OAAA,CAAQ,GAAA,CAAI,mBAAmB,IAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AACrE,EAAA,OAAO,IAAA,CAAK,MAAM,OAAO,CAAA;AAC3B;AAEO,SAAS,UAAA,GAAqB;AACnC,EAAA,OAAO,IAAA,CAAK,SAAA,EAAU,EAAG,aAAa,CAAA;AACxC;AAEO,SAAS,UAAA,GAAwB;AACtC,EAAA,IAAI;AACF,IAAA,MAAM,SAAkB,IAAA,CAAK,KAAA,CAAM,aAAa,UAAA,EAAW,EAAG,MAAM,CAAC,CAAA;AACrE,IAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACxC,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,OAAO,EAAC;AACV;AAGO,SAAS,YAAY,MAAA,EAA2B;AACrD,EAAA,SAAA,CAAU,SAAA,EAAU,EAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC1C,EAAA,MAAM,OAAO,UAAA,EAAW;AACxB,EAAA,aAAA,CAAc,MAAM,CAAA,EAAG,IAAA,CAAK,UAAU,MAAA,EAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,CAAA,EAAM,EAAE,IAAA,EAAM,GAA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ACnB,MAAA,KAAA,CAAMA,MAAAA,EAAO,EAAE,IAAA,EAAM,IAAA,EAAM,CAAA;AAC3B,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,IAAA,GAAOA,MAAAA,CAAM,GAAA,CAAI,CAAC,IAAA,MAAU;AAAA,MAChC,IAAI,IAAA,CAAK,EAAA;AAAA,MACT,MAAA,EAAQ,WAAA,CAAY,IAAA,CAAK,MAAM,CAAA;AAAA,MAC/B,cAAc,IAAA,CAAK,YAAA;AAAA,MACnB,cAAc,IAAA,CAAK;AAAA,KACrB,CAAE,CAAA;AACF,IAAA,KAAA,CAAM,IAAA,EAAM,EAAE,OAAA,EAAS,CAAC,MAAM,QAAA,EAAU,cAAA,EAAgB,cAAc,CAAA,EAAG,CAAA;AAAA,EAC3E,CAAC;AACL,CAAC,CAAA;AAEM,IAAM,QAAQF,aAAAA,CAAc;AAAA,EACjC,IAAA,EAAM,EAAE,IAAA,EAAM,OAAA,EAAS,aAAa,cAAA,EAAe;AAAA,EACnD,WAAA,EAAa,EAAE,IAAA,EAAAC,KAAAA;AACjB,CAAC,CAAA;;;ACvCD,IAAM,OAAOD,aAAAA,CAAc;AAAA,EACzB,IAAA,EAAM;AAAA,IACJ,IAAA,EAAM,OAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,WAAA,EAAa;AAAA,GACf;AAAA,EACA,WAAA,EAAa;AAAA,IACX,KAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,QAAA;AAAA,IACA;AAAA;AAEJ,CAAC,CAAA;AAED,OAAA,CAAQ,IAAI,CAAA","file":"cli.js","sourcesContent":["import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\n\n/** Persisted CLI credentials. Written by `zilfu login`, read on every command. */\nexport interface CliConfig {\n token?: string;\n baseUrl?: string;\n}\n\n/** XDG (or `%APPDATA%` on Windows) directory holding the config file. */\nfunction configDir(): string {\n if (process.platform === \"win32\") {\n const appData = process.env.APPDATA ?? join(homedir(), \"AppData\", \"Roaming\");\n return join(appData, \"zilfu\");\n }\n const base = process.env.XDG_CONFIG_HOME ?? join(homedir(), \".config\");\n return join(base, \"zilfu\");\n}\n\nexport function configPath(): string {\n return join(configDir(), \"config.json\");\n}\n\nexport function readConfig(): CliConfig {\n try {\n const parsed: unknown = JSON.parse(readFileSync(configPath(), \"utf8\"));\n if (parsed && typeof parsed === \"object\") {\n return parsed as CliConfig;\n }\n } catch {\n // Missing or unreadable config → fall back to defaults.\n }\n return {};\n}\n\n/** Writes the config file (creating its directory) with `0600` permissions. */\nexport function writeConfig(config: CliConfig): string {\n mkdirSync(configDir(), { recursive: true });\n const path = configPath();\n writeFileSync(path, `${JSON.stringify(config, null, 2)}\\n`, { mode: 0o600 });\n chmodSync(path, 0o600);\n return path;\n}\n\n/** Removes the config file. Returns `true` if a file was actually deleted. */\nexport function clearConfig(): boolean {\n const path = configPath();\n if (existsSync(path)) {\n rmSync(path);\n return true;\n }\n return false;\n}\n","import { Buffer } from \"node:buffer\";\n\nconst CTRL_C = String.fromCharCode(3); // ETX\nconst CTRL_D = String.fromCharCode(4); // EOT\nconst DEL = String.fromCharCode(127);\nconst BACKSPACE = String.fromCharCode(8);\n\nconst SUBMIT = new Set([\"\\r\", \"\\n\", CTRL_D]);\nconst DELETE = new Set([DEL, BACKSPACE]);\n\n/**\n * Reads a single line from a TTY without echoing it — for secrets like tokens.\n * Uses raw mode so keystrokes never reach the terminal. Callers should check\n * `process.stdin.isTTY` before using this for non-interactive input.\n */\nexport function promptSecret(label: string): Promise<string> {\n return new Promise((resolve) => {\n const { stdin, stdout } = process;\n stdout.write(label);\n stdin.setRawMode(true);\n stdin.resume();\n\n let input = \"\";\n const finish = (): void => {\n stdin.setRawMode(false);\n stdin.pause();\n stdin.removeListener(\"data\", onData);\n stdout.write(\"\\n\");\n };\n\n const onData = (chunk: Buffer): void => {\n for (const char of chunk.toString(\"utf8\")) {\n if (char === CTRL_C) {\n finish();\n process.exit(130);\n }\n if (SUBMIT.has(char)) {\n finish();\n resolve(input);\n return;\n }\n if (DELETE.has(char)) {\n input = input.slice(0, -1);\n continue;\n }\n if (char >= \" \") {\n input += char;\n }\n }\n };\n\n stdin.on(\"data\", onData);\n });\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { randomBytes, createHash } from \"node:crypto\";\nimport { spawn } from \"node:child_process\";\nimport { hostname } from \"node:os\";\nimport type { AddressInfo } from \"node:net\";\n\n/** How long to wait for the browser approval before giving up. */\nconst TIMEOUT_MS = 5 * 60 * 1000;\n\nfunction base64url(buffer: Buffer): string {\n return buffer\n .toString(\"base64\")\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\n}\n\n/** A PKCE (S256) verifier/challenge pair. */\nfunction createPkce(): { verifier: string; challenge: string } {\n const verifier = base64url(randomBytes(32));\n const challenge = base64url(createHash(\"sha256\").update(verifier).digest());\n return { verifier, challenge };\n}\n\n/**\n * The web origin that serves the consent screen, derived from the API base URL\n * by dropping a trailing `/api` segment (e.g. `https://zilfu.app/api` →\n * `https://zilfu.app`).\n */\nexport function webOrigin(baseUrl: string): string {\n const url = new URL(baseUrl);\n url.pathname = url.pathname.replace(/\\/api\\/?$/, \"/\");\n return url.toString().replace(/\\/$/, \"\");\n}\n\n/** Best-effort: open `url` in the default browser. Never throws. */\nfunction openBrowser(url: string): void {\n const [command, args] =\n process.platform === \"darwin\"\n ? ([\"open\", [url]] as const)\n : process.platform === \"win32\"\n ? ([\"cmd\", [\"/c\", \"start\", \"\", url]] as const)\n : ([\"xdg-open\", [url]] as const);\n try {\n const child = spawn(command, args, { stdio: \"ignore\", detached: true });\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // Headless or no opener — the URL is printed for manual use.\n }\n}\n\nconst DONE_PAGE =\n \"<!doctype html><meta charset=utf-8><title>Zilfu CLI</title>\" +\n \"<body style=\\\"font-family:system-ui;display:grid;place-items:center;height:100vh;margin:0\\\">\" +\n \"<p>Authorization complete. You can close this tab and return to your terminal.</p>\";\n\n/**\n * Runs the loopback browser login: opens a consent screen, waits for the\n * one-time code on a local callback, then exchanges it (with the PKCE verifier)\n * for an API token. Resolves with the plaintext token.\n */\nexport function loginViaBrowser(baseUrl: string): Promise<string> {\n const origin = webOrigin(baseUrl);\n const { verifier, challenge } = createPkce();\n const state = randomBytes(16).toString(\"hex\");\n\n return new Promise<string>((resolve, reject) => {\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n const url = new URL(req.url ?? \"/\", \"http://127.0.0.1\");\n if (url.pathname !== \"/callback\") {\n res.writeHead(204).end();\n return;\n }\n\n res.writeHead(200, { \"content-type\": \"text/html\" }).end(DONE_PAGE);\n\n const error = url.searchParams.get(\"error\");\n if (error) {\n settle(reject, new Error(`Authorization was denied (${error}).`));\n return;\n }\n if (url.searchParams.get(\"state\") !== state) {\n settle(reject, new Error(\"State mismatch — aborting for safety.\"));\n return;\n }\n const code = url.searchParams.get(\"code\");\n if (!code) {\n settle(reject, new Error(\"No authorization code received.\"));\n return;\n }\n exchange(origin, code, verifier).then(\n (token) => settle(resolve, token),\n (err) => settle(reject, err),\n );\n });\n\n const timer = setTimeout(() => {\n settle(reject, new Error(\"Timed out waiting for browser authorization.\"));\n }, TIMEOUT_MS);\n\n function settle<T>(fn: (value: T) => void, value: T): void {\n clearTimeout(timer);\n server.close();\n fn(value);\n }\n\n server.on(\"error\", (err) => settle(reject, err));\n\n server.listen(0, \"127.0.0.1\", () => {\n const { port } = server.address() as AddressInfo;\n const redirectUri = `http://127.0.0.1:${port}/callback`;\n const authorizeUrl = `${origin}/cli/authorize?${new URLSearchParams({\n redirect_uri: redirectUri,\n state,\n code_challenge: challenge,\n name: `zilfu-cli (${hostname()})`,\n }).toString()}`;\n\n process.stdout.write(\n `Opening your browser to authorize access:\\n ${authorizeUrl}\\n\\n` +\n \"Waiting for authorization…\\n\",\n );\n openBrowser(authorizeUrl);\n });\n });\n}\n\nasync function exchange(\n origin: string,\n code: string,\n verifier: string,\n): Promise<string> {\n const res = await fetch(`${origin}/cli/token`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json\" },\n body: JSON.stringify({ code, code_verifier: verifier }),\n });\n if (!res.ok) {\n throw new Error(`Token exchange failed (HTTP ${res.status}).`);\n }\n const body = (await res.json()) as { token?: string };\n if (!body.token) {\n throw new Error(\"Token exchange returned no token.\");\n }\n return body.token;\n}\n","import { createZilfuClient, type ZilfuClient } from \"@zilfu/sdk\";\nimport { readConfig } from \"./config\";\n\n/** Raised when a command needs auth but no token could be resolved. */\nexport class MissingTokenError extends Error {\n constructor() {\n super(\n \"No API token found.\\n\" +\n \"Run `zilfu login`, set ZILFU_TOKEN, or pass --token <token>.\\n\" +\n \"Create a token at Settings → API tokens.\",\n );\n this.name = \"MissingTokenError\";\n }\n}\n\nexport interface GlobalFlags {\n token?: string;\n baseUrl?: string;\n}\n\nexport interface ResolveOptions {\n /** When false, build a client even without a token (e.g. `health`). */\n requireToken?: boolean;\n}\n\n/** Token precedence: explicit flag → env → stored config. */\nexport function resolveToken(flags: GlobalFlags): string | undefined {\n return flags.token ?? process.env.ZILFU_TOKEN ?? readConfig().token;\n}\n\n/** Base-URL precedence: flag → env → config (SDK default if all unset). */\nexport function resolveBaseUrl(flags: GlobalFlags): string | undefined {\n return flags.baseUrl ?? process.env.ZILFU_BASE_URL ?? readConfig().baseUrl;\n}\n\nexport function resolveClient(\n flags: GlobalFlags,\n opts: ResolveOptions = {},\n): ZilfuClient {\n const token = resolveToken(flags);\n if (!token && opts.requireToken !== false) {\n throw new MissingTokenError();\n }\n return createZilfuClient({\n token: token ?? \"\",\n baseUrl: resolveBaseUrl(flags),\n });\n}\n","import { ZilfuApiError } from \"@zilfu/sdk\";\n\nexport interface PrintOptions {\n /** Print pretty JSON instead of a human-readable table/record. */\n json?: boolean;\n /** Column order for array output. Inferred from the first row when omitted. */\n columns?: string[];\n}\n\nfunction formatCell(value: unknown): string {\n if (value === null || value === undefined) {\n return \"\";\n }\n if (typeof value === \"object\") {\n return JSON.stringify(value);\n }\n return String(value);\n}\n\nfunction inferColumns(rows: Array<Record<string, unknown>>): string[] {\n const first = rows[0] ?? {};\n return Object.keys(first).filter((key) => {\n const value = first[key];\n return value === null || typeof value !== \"object\";\n });\n}\n\nfunction printTable(\n rows: Array<Record<string, unknown>>,\n columns?: string[],\n): void {\n if (rows.length === 0) {\n process.stdout.write(\"No results.\\n\");\n return;\n }\n const cols = columns ?? inferColumns(rows);\n const widths = cols.map((col) =>\n Math.max(col.length, ...rows.map((row) => formatCell(row[col]).length)),\n );\n const line = (cells: string[]): string =>\n `${cells.map((cell, i) => cell.padEnd(widths[i]!)).join(\" \").replace(/\\s+$/, \"\")}\\n`;\n\n process.stdout.write(line(cols));\n process.stdout.write(line(cols.map((_, i) => \"-\".repeat(widths[i]!))));\n for (const row of rows) {\n process.stdout.write(line(cols.map((col) => formatCell(row[col]))));\n }\n}\n\nfunction printRecord(record: Record<string, unknown>): void {\n const keys = Object.keys(record);\n if (keys.length === 0) {\n process.stdout.write(\"(empty)\\n\");\n return;\n }\n const width = Math.max(...keys.map((key) => key.length));\n for (const key of keys) {\n process.stdout.write(`${key.padEnd(width)} ${formatCell(record[key])}\\n`);\n }\n}\n\n/** Renders command output as JSON (`--json`) or a human-readable view. */\nexport function print(data: unknown, opts: PrintOptions = {}): void {\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(data, null, 2)}\\n`);\n return;\n }\n if (Array.isArray(data)) {\n printTable(data as Array<Record<string, unknown>>, opts.columns);\n return;\n }\n if (data && typeof data === \"object\") {\n printRecord(data as Record<string, unknown>);\n return;\n }\n process.stdout.write(`${formatCell(data)}\\n`);\n}\n\n/** Prints an error to stderr (with Laravel validation details) and exits 1. */\nexport function printError(error: unknown): never {\n if (error instanceof ZilfuApiError) {\n process.stderr.write(`Error ${error.status}: ${error.message}\\n`);\n if (error.errors) {\n for (const [field, messages] of Object.entries(error.errors)) {\n for (const message of messages) {\n process.stderr.write(` - ${field}: ${message}\\n`);\n }\n }\n }\n } else if (error instanceof Error) {\n process.stderr.write(`${error.message}\\n`);\n } else {\n process.stderr.write(`${String(error)}\\n`);\n }\n return process.exit(1);\n}\n","import { resolveClient, type ResolveOptions } from \"../client\";\nimport { printError } from \"../output\";\n\n/**\n * Global flags spread into every leaf command's `args`. Defined `as const` so\n * citty keeps the literal `type` values; values are read loosely via the\n * helpers below, so we don't depend on citty's arg-type inference.\n */\nexport const globalArgs = {\n token: {\n type: \"string\",\n description: \"API token (overrides ZILFU_TOKEN and stored config)\",\n },\n \"base-url\": {\n type: \"string\",\n description: \"API base URL (overrides ZILFU_BASE_URL and stored config)\",\n },\n json: {\n type: \"boolean\",\n description: \"Output raw JSON instead of a table\",\n },\n} as const;\n\ntype Args = Record<string, unknown>;\n\nfunction readString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/** Builds an authenticated SDK client from a command's parsed args. */\nexport function clientFor(args: Args, opts?: ResolveOptions) {\n return resolveClient(\n { token: readString(args[\"token\"]), baseUrl: readString(args[\"base-url\"]) },\n opts,\n );\n}\n\nexport function wantsJson(args: Args): boolean {\n return args[\"json\"] === true;\n}\n\n/** Coerces a `--space` argument to a positive integer space id. */\nexport function toSpaceId(value: unknown): number {\n const id = Number(value);\n if (!Number.isInteger(id) || id <= 0) {\n throw new Error(`Invalid space id: ${String(value)}`);\n }\n return id;\n}\n\n/** Runs a command body, routing any thrown error through `printError`. */\nexport async function guard(fn: () => Promise<void> | void): Promise<void> {\n try {\n await fn();\n } catch (error) {\n printError(error);\n }\n}\n","import { defineCommand } from \"citty\";\nimport { createZilfuClient } from \"@zilfu/sdk\";\nimport { writeConfig } from \"../config\";\nimport { promptSecret } from \"../prompt\";\nimport { loginViaBrowser } from \"../web-auth\";\nimport { guard } from \"./_shared\";\n\nexport const login = defineCommand({\n meta: { name: \"login\", description: \"Authenticate and store your API token\" },\n args: {\n web: {\n type: \"boolean\",\n description: \"Authorize in the browser instead of pasting a token\",\n },\n token: {\n type: \"string\",\n description: \"API token (skips the interactive prompt)\",\n },\n \"base-url\": {\n type: \"string\",\n description: \"API base URL to store (defaults to the production API)\",\n },\n },\n run: ({ args }) =>\n guard(async () => {\n const baseUrl =\n typeof args[\"base-url\"] === \"string\" && args[\"base-url\"]\n ? args[\"base-url\"]\n : process.env.ZILFU_BASE_URL;\n\n const token =\n args[\"web\"] === true\n ? await loginViaBrowser(baseUrl ?? \"https://zilfu.app/api\")\n : await promptToken(typeof args[\"token\"] === \"string\" ? args[\"token\"] : \"\");\n\n const api = createZilfuClient({ token, baseUrl });\n const res = await api.session.get();\n const user = res.data?.data;\n\n const path = writeConfig({ token, ...(baseUrl ? { baseUrl } : {}) });\n process.stdout.write(\n `Logged in as ${user?.name ?? \"?\"} <${user?.email ?? \"?\"}>.\\n` +\n `Credentials stored at ${path}\\n`,\n );\n }),\n});\n\n/** Resolve a token from the flag or an interactive hidden prompt. */\nasync function promptToken(flagToken: string): Promise<string> {\n let token = flagToken;\n if (!token) {\n if (!process.stdin.isTTY) {\n throw new Error(\n \"No token provided. Pass --token <token>, use --web, or run in an interactive terminal.\",\n );\n }\n process.stdout.write(\"Create a token at Settings -> API tokens.\\n\");\n token = await promptSecret(\"Zilfu API token: \");\n }\n token = token.trim();\n if (!token) {\n throw new Error(\"A token is required.\");\n }\n return token;\n}\n","import { defineCommand } from \"citty\";\nimport { clearConfig } from \"../config\";\nimport { guard } from \"./_shared\";\n\nexport const logout = defineCommand({\n meta: { name: \"logout\", description: \"Remove stored credentials\" },\n run: () =>\n guard(() => {\n const removed = clearConfig();\n process.stdout.write(\n removed ? \"Logged out.\\n\" : \"No stored credentials found.\\n\",\n );\n }),\n});\n","import { defineCommand } from \"citty\";\nimport { print } from \"../output\";\nimport { clientFor, globalArgs, guard, wantsJson } from \"./_shared\";\n\nexport const whoami = defineCommand({\n meta: { name: \"whoami\", description: \"Show the authenticated user\" },\n args: { ...globalArgs },\n run: ({ args }) =>\n guard(async () => {\n const api = clientFor(args);\n const res = await api.session.get();\n print(res.data?.data ?? {}, { json: wantsJson(args) });\n }),\n});\n","import { defineCommand } from \"citty\";\nimport { print } from \"../output\";\nimport { clientFor, globalArgs, guard, wantsJson } from \"./_shared\";\n\nexport const health = defineCommand({\n meta: { name: \"health\", description: \"Check the Zilfu API health\" },\n args: { ...globalArgs },\n run: ({ args }) =>\n guard(async () => {\n const api = clientFor(args, { requireToken: false });\n const res = await api.health.check();\n print(res.data ?? {}, { json: wantsJson(args) });\n }),\n});\n","import { defineCommand } from \"citty\";\nimport { print } from \"../output\";\nimport { clientFor, globalArgs, guard, wantsJson } from \"./_shared\";\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List spaces you can access\" },\n args: { ...globalArgs },\n run: ({ args }) =>\n guard(async () => {\n const api = clientFor(args);\n const res = await api.spaces.list();\n print(res.data?.data ?? [], {\n json: wantsJson(args),\n columns: [\"id\", \"name\", \"timezone\"],\n });\n }),\n});\n\nexport const spaces = defineCommand({\n meta: { name: \"spaces\", description: \"Manage spaces\" },\n subCommands: { list },\n});\n","import { defineCommand } from \"citty\";\nimport { print } from \"../output\";\nimport { clientFor, globalArgs, guard, toSpaceId, wantsJson } from \"./_shared\";\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List connected accounts in a space\" },\n args: {\n ...globalArgs,\n space: { type: \"string\", required: true, description: \"The space id\" },\n },\n run: ({ args }) =>\n guard(async () => {\n const space = toSpaceId(args[\"space\"]);\n const api = clientFor(args);\n const res = await api.accounts.list({ path: { space } });\n print(res.data?.data ?? [], {\n json: wantsJson(args),\n columns: [\"id\", \"social\", \"display_name\", \"handler\", \"is_active\"],\n });\n }),\n});\n\nexport const accounts = defineCommand({\n meta: { name: \"accounts\", description: \"Manage connected accounts\" },\n subCommands: { list },\n});\n","import { defineCommand } from \"citty\";\nimport type { PostResource } from \"@zilfu/sdk\";\nimport { print } from \"../output\";\nimport { clientFor, globalArgs, guard, toSpaceId, wantsJson } from \"./_shared\";\n\nconst STATUS_LABELS: Record<number, string> = {\n 0: \"scheduled\",\n 1: \"published\",\n 2: \"error\",\n 3: \"draft\",\n 4: \"processing\",\n};\n\nfunction statusLabel(status: number): string {\n return STATUS_LABELS[status] ?? String(status);\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List posts in a space\" },\n args: {\n ...globalArgs,\n space: { type: \"string\", required: true, description: \"The space id\" },\n },\n run: ({ args }) =>\n guard(async () => {\n const space = toSpaceId(args[\"space\"]);\n const api = clientFor(args);\n const res = await api.posts.list({ path: { space } });\n const posts: PostResource[] = res.data?.data ?? [];\n\n if (wantsJson(args)) {\n print(posts, { json: true });\n return;\n }\n\n const rows = posts.map((post) => ({\n id: post.id,\n status: statusLabel(post.status),\n scheduled_at: post.scheduled_at,\n published_at: post.published_at,\n }));\n print(rows, { columns: [\"id\", \"status\", \"scheduled_at\", \"published_at\"] });\n }),\n});\n\nexport const posts = defineCommand({\n meta: { name: \"posts\", description: \"Manage posts\" },\n subCommands: { list },\n});\n","import { defineCommand, runMain } from \"citty\";\nimport { login } from \"./commands/login\";\nimport { logout } from \"./commands/logout\";\nimport { whoami } from \"./commands/whoami\";\nimport { health } from \"./commands/health\";\nimport { spaces } from \"./commands/spaces\";\nimport { accounts } from \"./commands/accounts\";\nimport { posts } from \"./commands/posts\";\n\nconst main = defineCommand({\n meta: {\n name: \"zilfu\",\n version: \"0.1.0\",\n description: \"Zilfu command-line interface\",\n },\n subCommands: {\n login,\n logout,\n whoami,\n health,\n spaces,\n accounts,\n posts,\n },\n});\n\nrunMain(main);\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zilfu/cli",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Official command-line interface for the Zilfu API",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"zilfu": "./dist/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18.17"
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@zilfu/sdk": "^0.1.10",
|
|
23
|
+
"citty": "^0.2.2"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^22.10.0",
|
|
27
|
+
"oxlint": "^1.61.0",
|
|
28
|
+
"tsup": "^8.5.0",
|
|
29
|
+
"tsx": "^4.22.3",
|
|
30
|
+
"typescript": "^5.9.3"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "tsup",
|
|
34
|
+
"dev": "node --import tsx src/cli.ts",
|
|
35
|
+
"typecheck": "tsc --noEmit",
|
|
36
|
+
"lint": "oxlint"
|
|
37
|
+
}
|
|
38
|
+
}
|