chiakeo 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.
Files changed (3) hide show
  1. package/README.md +11 -2
  2. package/chiakeo.mjs +300 -0
  3. package/package.json +23 -4
package/README.md CHANGED
@@ -1,3 +1,12 @@
1
- # Temporary Holding Version
1
+ # chiakeo
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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,300 @@
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: dòng lệnh cho Chia Kèo
20
+
21
+ up [--url URL] [--name TÊN] đăng nhập bằng mã (như tailscale up)
22
+ down xóa token trên máy này
23
+ whoami xem đang đăng nhập là ai
24
+ games danh sách kèo đang chơi
25
+ game <kèo> chi tiết, số dư và ai chuyển cho ai
26
+ new <tên> [--people N] tạo kèo mới
27
+ add-person <kèo> <tên...> thêm người
28
+ add-expense <kèo> <nội dung> <số tiền> --payer TÊN [--split A,B] [--note GHI CHÚ]
29
+ pay <kèo> <người trả> <người nhận> <số tiền>
30
+ api <METHOD> <đường dẫn> [json] gọi thẳng REST API
31
+
32
+ <kèo> là mã, id hoặc tên kèo. Số tiền: 50000, 50k, 1.5m.
33
+ Biến môi trường: CHIAKEO_CONFIG (đường dẫn file cấu hình).`;
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(`Thiếu giá trị cho ${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(`Số tiền không hợp lệ: ${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(`Số tiền phải lớn hơn 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("Chưa đăng nhập. Chạy: 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 || "lỗi không rõ"}`);
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(`Mở link này trong trình duyệt (đăng nhập nếu được hỏi):
106
+ ${start.verificationUrl}?code=${start.userCode}
107
+ Hoặc mở ${start.verificationUrl} và nhập mã: ${start.userCode}
108
+ Đang chờ duyệt...`);
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("Đã đăng nhập.");
123
+ return;
124
+ }
125
+ if (status === "expired") break;
126
+ }
127
+ throw new CliError("Mã hết hạn. Chạy lại: chiakeo up");
128
+ }
129
+
130
+ async function down() {
131
+ await rm(CONFIG_PATH, { force: true });
132
+ console.log(
133
+ "Đã xóa token trên máy này. Muốn thu hồi hẳn thì vào Cài đặt > Token trên web.",
134
+ );
135
+ }
136
+
137
+ async function whoami() {
138
+ const { user } = await authed("GET", "/api/session");
139
+ if (!user) throw new CliError("Token không còn hiệu lực. Chạy: chiakeo up");
140
+ console.log(user.name);
141
+ }
142
+
143
+ async function findGame(ref) {
144
+ // Kèo tất toán xong tự đóng và rời danh sách đang chơi, nên tìm cả kèo đã đóng.
145
+ const [active, closed] = await Promise.all([
146
+ authed("GET", "/api/games"),
147
+ authed("GET", "/api/games/closed"),
148
+ ]);
149
+ const key = ref.toLowerCase();
150
+ const matches = [...active, ...closed].filter(
151
+ (game) =>
152
+ game.id === ref ||
153
+ game.code.toLowerCase() === key ||
154
+ game.name.toLowerCase() === key,
155
+ );
156
+ if (matches.length !== 1) {
157
+ throw new CliError(
158
+ matches.length === 0
159
+ ? `Không thấy kèo "${ref}" `
160
+ : `Có ${matches.length} kèo khớp "${ref}", dùng mã kèo`,
161
+ );
162
+ }
163
+ return matches[0];
164
+ }
165
+
166
+ async function loadGame(ref) {
167
+ const { id } = await findGame(ref);
168
+ return authed("GET", `/api/games/${id}`);
169
+ }
170
+
171
+ function findPerson(game, name) {
172
+ const person = game.participants.find(
173
+ (item) => item.name.toLowerCase() === name.toLowerCase(),
174
+ );
175
+ if (!person) {
176
+ const names = game.participants.map((item) => item.name).join(", ");
177
+ throw new CliError(`Không thấy "${name}" trong kèo. Có: ${names}`);
178
+ }
179
+ return person;
180
+ }
181
+
182
+ async function games() {
183
+ const list = await authed("GET", "/api/games");
184
+ for (const game of list) {
185
+ console.log(
186
+ `${game.code} ${game.name} (${game.participantCount} người, ${game.expenseCount} khoản)`,
187
+ );
188
+ }
189
+ if (list.length === 0) console.log("Chưa có kèo nào đang chơi.");
190
+ }
191
+
192
+ async function game({ positional }) {
193
+ const detail = await loadGame(requireArg(positional[1], "<kèo>"));
194
+ const nameOf = (id) =>
195
+ detail.participants.find((item) => item.id === id)?.name ?? id;
196
+ console.log(`${detail.name} (${detail.code})`);
197
+ console.log(`Tổng chi: ${money(detail.summary.totalExpense)}`);
198
+ for (const row of detail.summary.balances) {
199
+ console.log(
200
+ ` ${nameOf(row.participantId)}: trả ${money(row.paid)}, phải chịu ${money(row.owed)}, số dư ${money(row.balance)}`,
201
+ );
202
+ }
203
+ for (const row of detail.summary.settlements) {
204
+ console.log(
205
+ `${nameOf(row.fromParticipantId)} chuyển ${money(row.amount)} cho ${nameOf(row.toParticipantId)}`,
206
+ );
207
+ }
208
+ }
209
+
210
+ async function newGame({ positional, flags }) {
211
+ const created = await authed("POST", "/api/games", {
212
+ name: requireArg(positional[1], "<tên>"),
213
+ participantCount: Number(flags.people || 0),
214
+ });
215
+ console.log(`Đã tạo kèo ${created.name} (${created.code})`);
216
+ }
217
+
218
+ async function addPerson({ positional }) {
219
+ const target = await findGame(requireArg(positional[1], "<kèo>"));
220
+ const names = positional.slice(2);
221
+ if (names.length === 0) throw new CliError("Thiếu <tên...>");
222
+ for (const name of names) {
223
+ await authed("POST", `/api/games/${target.id}/participants`, { name });
224
+ }
225
+ console.log(`Đã thêm ${names.join(", ")} vào ${target.name}`);
226
+ }
227
+
228
+ async function addExpense({ positional, flags }) {
229
+ const detail = await loadGame(requireArg(positional[1], "<kèo>"));
230
+ const payer = findPerson(detail, requireArg(flags.payer, "--payer"));
231
+ const split = flags.split
232
+ ? flags.split.split(",").map((name) => findPerson(detail, name.trim()))
233
+ : detail.participants;
234
+ await authed("POST", `/api/games/${detail.id}/expenses`, {
235
+ title: requireArg(positional[2], "<nội dung>"),
236
+ amount: parseAmount(positional[3]),
237
+ note: flags.note || "",
238
+ payerParticipantId: payer.id,
239
+ splitMode: "equal",
240
+ splitParticipantIds: split.map((person) => person.id),
241
+ });
242
+ console.log(`Đã thêm khoản chi ${positional[2]} vào ${detail.name}`);
243
+ }
244
+
245
+ async function pay({ positional }) {
246
+ const detail = await loadGame(requireArg(positional[1], "<kèo>"));
247
+ const from = findPerson(detail, requireArg(positional[2], "<người trả>"));
248
+ const to = findPerson(detail, requireArg(positional[3], "<người nhận>"));
249
+ await authed("POST", `/api/games/${detail.id}/transfers`, {
250
+ fromParticipantId: from.id,
251
+ toParticipantId: to.id,
252
+ amount: parseAmount(positional[4]),
253
+ });
254
+ console.log(`Đã ghi nhận ${from.name} trả ${to.name}`);
255
+ }
256
+
257
+ async function api({ positional }) {
258
+ const [, method, path, json] = positional;
259
+ const body = json === undefined ? undefined : JSON.parse(json);
260
+ const data = await authed(
261
+ requireArg(method, "<METHOD>").toUpperCase(),
262
+ requireArg(path, "<đường dẫn>"),
263
+ body,
264
+ );
265
+ console.log(JSON.stringify(data, null, 2));
266
+ }
267
+
268
+ function requireArg(value, label) {
269
+ if (value === undefined) throw new CliError(`Thiếu ${label}`);
270
+ return value;
271
+ }
272
+
273
+ const COMMANDS = {
274
+ up,
275
+ login: up,
276
+ down,
277
+ whoami,
278
+ games,
279
+ game,
280
+ new: newGame,
281
+ "add-person": addPerson,
282
+ "add-expense": addExpense,
283
+ pay,
284
+ api,
285
+ };
286
+
287
+ async function main() {
288
+ const args = parseArgs(process.argv.slice(2));
289
+ const command = COMMANDS[args.positional[0]];
290
+ if (!command) {
291
+ console.log(HELP);
292
+ return;
293
+ }
294
+ await command(args);
295
+ }
296
+
297
+ main().catch((error) => {
298
+ console.error(error instanceof CliError ? error.message : error);
299
+ process.exit(1);
300
+ });
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "chiakeo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
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
+ }