chiakeo 0.0.0-stage → 0.1.1
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 +11 -2
- package/chiakeo.mjs +305 -0
- package/package.json +23 -4
package/README.md
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
-
#
|
|
1
|
+
# chiakeo
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Command line for [Chia Kèo](https://chiakeo.huyab.cfd).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add -g chiakeo
|
|
7
|
+
chiakeo up
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
`chiakeo up` prints a link and a code. Open the link, sign in, and approve. The token is saved in `~/.config/chiakeo/config.json` (mode 600). Run `chiakeo down` to delete it.
|
|
11
|
+
|
|
12
|
+
Run `chiakeo` with no arguments to see all commands. Needs Node 22 or newer.
|
package/chiakeo.mjs
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir, hostname } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
7
|
+
|
|
8
|
+
const DEFAULT_URL = "https://chiakeo.huyab.cfd";
|
|
9
|
+
const CONFIG_PATH =
|
|
10
|
+
process.env.CHIAKEO_CONFIG ||
|
|
11
|
+
join(homedir(), ".config", "chiakeo", "config.json");
|
|
12
|
+
const TOKEN_BYTES = 32;
|
|
13
|
+
const TOKEN_PREFIX_LENGTH = 9;
|
|
14
|
+
const DEVICE_NAME_MAX_LENGTH = 60;
|
|
15
|
+
const CONFIG_FILE_MODE = 0o600;
|
|
16
|
+
const AMOUNT_UNITS = { k: 1_000, m: 1_000_000 };
|
|
17
|
+
const AMOUNT_PATTERN = /^(\d+(?:[.,]\d+)?)([km])?$/i;
|
|
18
|
+
|
|
19
|
+
const HELP = `chiakeo: command line for Chia Kèo
|
|
20
|
+
|
|
21
|
+
up [--url URL] [--name NAME] sign in with a code (like tailscale up)
|
|
22
|
+
down delete the token on this computer
|
|
23
|
+
whoami show who is signed in
|
|
24
|
+
games list the open games
|
|
25
|
+
game <game> details, balances and who pays whom
|
|
26
|
+
new <name> [--people N] create a game
|
|
27
|
+
add-person <game> <name...> add people
|
|
28
|
+
add-expense <game> <title> <amount> --payer NAME [--split A,B] [--note NOTE]
|
|
29
|
+
pay <game> <from> <to> <amount>
|
|
30
|
+
api <METHOD> <path> [json] call the REST API directly
|
|
31
|
+
|
|
32
|
+
<game> is the game code, id or name. Amount: 50000, 50k, 1.5m.
|
|
33
|
+
Environment: CHIAKEO_CONFIG (path of the config file).`;
|
|
34
|
+
|
|
35
|
+
class CliError extends Error {}
|
|
36
|
+
|
|
37
|
+
function parseArgs(argv) {
|
|
38
|
+
const positional = [];
|
|
39
|
+
const flags = {};
|
|
40
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
41
|
+
const arg = argv[index];
|
|
42
|
+
if (!arg.startsWith("--")) {
|
|
43
|
+
positional.push(arg);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const value = argv[index + 1];
|
|
47
|
+
if (value === undefined || value.startsWith("--")) {
|
|
48
|
+
throw new CliError(`Missing value for ${arg}`);
|
|
49
|
+
}
|
|
50
|
+
flags[arg.slice(2)] = value;
|
|
51
|
+
index += 1;
|
|
52
|
+
}
|
|
53
|
+
return { positional, flags };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function parseAmount(raw) {
|
|
57
|
+
const match = AMOUNT_PATTERN.exec(String(raw ?? "").trim());
|
|
58
|
+
if (!match) throw new CliError(`Bad amount: ${raw}`);
|
|
59
|
+
const unit = AMOUNT_UNITS[(match[2] || "").toLowerCase()] ?? 1;
|
|
60
|
+
const amount = Math.round(Number(match[1].replace(",", ".")) * unit);
|
|
61
|
+
if (amount <= 0) throw new CliError(`Amount must be more than 0: ${raw}`);
|
|
62
|
+
return amount;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const money = (value) => `${value.toLocaleString("vi-VN")} ₫`;
|
|
66
|
+
|
|
67
|
+
async function readConfig() {
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(await readFile(CONFIG_PATH, "utf8"));
|
|
70
|
+
} catch {
|
|
71
|
+
throw new CliError("You are not signed in. Run: chiakeo up");
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function request(baseUrl, method, path, body, token) {
|
|
76
|
+
const response = await fetch(`${baseUrl}${path}`, {
|
|
77
|
+
method,
|
|
78
|
+
headers: {
|
|
79
|
+
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
80
|
+
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
81
|
+
},
|
|
82
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
83
|
+
});
|
|
84
|
+
const data = await response.json().catch(() => ({}));
|
|
85
|
+
if (!response.ok) {
|
|
86
|
+
throw new CliError(`${response.status} ${data.error || "unknown error"}`);
|
|
87
|
+
}
|
|
88
|
+
return data;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function authed(method, path, body) {
|
|
92
|
+
const { url, token } = await readConfig();
|
|
93
|
+
return request(url, method, path, body, token);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function up({ flags }) {
|
|
97
|
+
const url = (flags.url || DEFAULT_URL).replace(/\/$/, "");
|
|
98
|
+
const secret = `ck_${randomBytes(TOKEN_BYTES).toString("hex")}`;
|
|
99
|
+
const start = await request(url, "POST", "/api/cli-auth/start", {
|
|
100
|
+
tokenHash: createHash("sha256").update(secret).digest("hex"),
|
|
101
|
+
tokenPrefix: secret.slice(0, TOKEN_PREFIX_LENGTH),
|
|
102
|
+
name: (flags.name || hostname()).slice(0, DEVICE_NAME_MAX_LENGTH),
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
console.log(`Open this link in your browser (sign in if asked):
|
|
106
|
+
${start.verificationUrl}?code=${start.userCode}
|
|
107
|
+
Or open ${start.verificationUrl} and type this code: ${start.userCode}
|
|
108
|
+
Waiting for approval...`);
|
|
109
|
+
|
|
110
|
+
const deadline = Date.now() + start.expiresInSeconds * 1000;
|
|
111
|
+
while (Date.now() < deadline) {
|
|
112
|
+
await sleep(start.intervalSeconds * 1000);
|
|
113
|
+
const { status } = await request(url, "POST", "/api/cli-auth/poll", {
|
|
114
|
+
deviceCode: start.deviceCode,
|
|
115
|
+
});
|
|
116
|
+
if (status === "approved") {
|
|
117
|
+
await mkdir(dirname(CONFIG_PATH), { recursive: true });
|
|
118
|
+
await writeFile(CONFIG_PATH, JSON.stringify({ url, token: secret }), {
|
|
119
|
+
mode: CONFIG_FILE_MODE,
|
|
120
|
+
});
|
|
121
|
+
await chmod(CONFIG_PATH, CONFIG_FILE_MODE);
|
|
122
|
+
console.log("Signed in.");
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (status === "expired") break;
|
|
126
|
+
}
|
|
127
|
+
throw new CliError("The code has expired. Run again: chiakeo up");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function down() {
|
|
131
|
+
await rm(CONFIG_PATH, { force: true });
|
|
132
|
+
console.log(
|
|
133
|
+
"Deleted the token on this computer. To revoke it fully, open Settings > Tokens on the website.",
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function whoami() {
|
|
138
|
+
const { user } = await authed("GET", "/api/session");
|
|
139
|
+
if (!user)
|
|
140
|
+
throw new CliError("The token is no longer valid. Run: chiakeo up");
|
|
141
|
+
console.log(user.name);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function findGame(ref) {
|
|
145
|
+
// A settled game closes by itself and leaves the open list, so search closed games too.
|
|
146
|
+
const [active, closed] = await Promise.all([
|
|
147
|
+
authed("GET", "/api/games"),
|
|
148
|
+
authed("GET", "/api/games/closed"),
|
|
149
|
+
]);
|
|
150
|
+
const key = ref.toLowerCase();
|
|
151
|
+
const matches = [...active, ...closed].filter(
|
|
152
|
+
(game) =>
|
|
153
|
+
game.id === ref ||
|
|
154
|
+
game.code.toLowerCase() === key ||
|
|
155
|
+
game.name.toLowerCase() === key,
|
|
156
|
+
);
|
|
157
|
+
if (matches.length !== 1) {
|
|
158
|
+
throw new CliError(
|
|
159
|
+
matches.length === 0
|
|
160
|
+
? `No game found for "${ref}"`
|
|
161
|
+
: `${matches.length} games match "${ref}", use the game code`,
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
return matches[0];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function loadGame(ref) {
|
|
168
|
+
const { id } = await findGame(ref);
|
|
169
|
+
return authed("GET", `/api/games/${id}`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function findPerson(game, name) {
|
|
173
|
+
const person = game.participants.find(
|
|
174
|
+
(item) => item.name.toLowerCase() === name.toLowerCase(),
|
|
175
|
+
);
|
|
176
|
+
if (!person) {
|
|
177
|
+
const names = game.participants.map((item) => item.name).join(", ");
|
|
178
|
+
throw new CliError(`No person "${name}" in this game. People: ${names}`);
|
|
179
|
+
}
|
|
180
|
+
return person;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function games() {
|
|
184
|
+
const list = await authed("GET", "/api/games");
|
|
185
|
+
for (const game of list) {
|
|
186
|
+
console.log(
|
|
187
|
+
`${game.code} ${game.name} (${game.participantCount} people, ${game.expenseCount} expenses)`,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
if (list.length === 0) console.log("No open games.");
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function game({ positional }) {
|
|
194
|
+
const detail = await loadGame(requireArg(positional[1], "<game>"));
|
|
195
|
+
const nameOf = (id) =>
|
|
196
|
+
detail.participants.find((item) => item.id === id)?.name ?? id;
|
|
197
|
+
console.log(`${detail.name} (${detail.code})`);
|
|
198
|
+
console.log(`Total spent: ${money(detail.summary.totalExpense)}`);
|
|
199
|
+
for (const row of detail.summary.balances) {
|
|
200
|
+
console.log(
|
|
201
|
+
` ${nameOf(row.participantId)}: paid ${money(row.paid)}, owes ${money(row.owed)}, balance ${money(row.balance)}`,
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
for (const row of detail.summary.settlements) {
|
|
205
|
+
console.log(
|
|
206
|
+
`${nameOf(row.fromParticipantId)} sends ${money(row.amount)} to ${nameOf(row.toParticipantId)}`,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function newGame({ positional, flags }) {
|
|
212
|
+
const created = await authed("POST", "/api/games", {
|
|
213
|
+
name: requireArg(positional[1], "<name>"),
|
|
214
|
+
participantCount: Number(flags.people || 0),
|
|
215
|
+
});
|
|
216
|
+
console.log(`Created game ${created.name} (${created.code})`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function addPerson({ positional }) {
|
|
220
|
+
const target = await findGame(requireArg(positional[1], "<game>"));
|
|
221
|
+
const names = positional.slice(2);
|
|
222
|
+
if (names.length === 0) throw new CliError("Missing <name...>");
|
|
223
|
+
for (const name of names) {
|
|
224
|
+
await authed("POST", `/api/games/${target.id}/participants`, { name });
|
|
225
|
+
}
|
|
226
|
+
console.log(`Added ${names.join(", ")} to ${target.name}`);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function addExpense({ positional, flags }) {
|
|
230
|
+
const detail = await loadGame(requireArg(positional[1], "<game>"));
|
|
231
|
+
const payer = findPerson(detail, requireArg(flags.payer, "--payer"));
|
|
232
|
+
const split = flags.split
|
|
233
|
+
? flags.split.split(",").map((name) => findPerson(detail, name.trim()))
|
|
234
|
+
: detail.participants;
|
|
235
|
+
await authed("POST", `/api/games/${detail.id}/expenses`, {
|
|
236
|
+
title: requireArg(positional[2], "<title>"),
|
|
237
|
+
amount: parseAmount(positional[3]),
|
|
238
|
+
note: flags.note || "",
|
|
239
|
+
payerParticipantId: payer.id,
|
|
240
|
+
splitMode: "equal",
|
|
241
|
+
splitParticipantIds: split.map((person) => person.id),
|
|
242
|
+
});
|
|
243
|
+
console.log(`Added expense ${positional[2]} to ${detail.name}`);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function pay({ positional }) {
|
|
247
|
+
const detail = await loadGame(requireArg(positional[1], "<game>"));
|
|
248
|
+
const from = findPerson(detail, requireArg(positional[2], "<from>"));
|
|
249
|
+
const to = findPerson(detail, requireArg(positional[3], "<to>"));
|
|
250
|
+
await authed("POST", `/api/games/${detail.id}/transfers`, {
|
|
251
|
+
fromParticipantId: from.id,
|
|
252
|
+
toParticipantId: to.id,
|
|
253
|
+
amount: parseAmount(positional[4]),
|
|
254
|
+
});
|
|
255
|
+
console.log(`Recorded: ${from.name} paid ${to.name}`);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function api({ positional }) {
|
|
259
|
+
const [, method, path, json] = positional;
|
|
260
|
+
const body = json === undefined ? undefined : JSON.parse(json);
|
|
261
|
+
const data = await authed(
|
|
262
|
+
requireArg(method, "<METHOD>").toUpperCase(),
|
|
263
|
+
requireArg(path, "<path>"),
|
|
264
|
+
body,
|
|
265
|
+
);
|
|
266
|
+
console.log(JSON.stringify(data, null, 2));
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function requireArg(value, label) {
|
|
270
|
+
if (value === undefined) throw new CliError(`Missing ${label}`);
|
|
271
|
+
return value;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const COMMANDS = {
|
|
275
|
+
up,
|
|
276
|
+
login: up,
|
|
277
|
+
down,
|
|
278
|
+
whoami,
|
|
279
|
+
games,
|
|
280
|
+
game,
|
|
281
|
+
new: newGame,
|
|
282
|
+
"add-person": addPerson,
|
|
283
|
+
"add-expense": addExpense,
|
|
284
|
+
pay,
|
|
285
|
+
api,
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
async function main() {
|
|
289
|
+
const args = parseArgs(process.argv.slice(2));
|
|
290
|
+
const [name] = args.positional;
|
|
291
|
+
if (name === undefined) {
|
|
292
|
+
console.log(HELP);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
const command = COMMANDS[name];
|
|
296
|
+
if (!command) {
|
|
297
|
+
throw new CliError(`Unknown command: ${name}. Run chiakeo for help.`);
|
|
298
|
+
}
|
|
299
|
+
await command(args);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
main().catch((error) => {
|
|
303
|
+
console.error(error instanceof CliError ? error.message : error);
|
|
304
|
+
process.exit(1);
|
|
305
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "chiakeo",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Command line for Chia Kèo: log in with a device code, read and write games",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"chiakeo": "chiakeo.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"chiakeo.mjs",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=22"
|
|
15
|
+
},
|
|
16
|
+
"license": "UNLICENSED",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/nguyenhuy158/chiakeo.git",
|
|
20
|
+
"directory": "cli"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
}
|
|
25
|
+
}
|