@the-seeker/madefeed 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 +35 -2
  2. package/dist/cli.mjs +630 -0
  3. package/package.json +28 -4
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @the-seeker/madefeed
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
+ [MadeFeed](https://madefeed.dev) 토큰 미터예요. 이 컴퓨터에서 AI 코딩 도구로 쓴 토큰 합계를 읽어 MadeFeed 계정에 올려요. 올린 토큰만큼 제품에 투표할 표가 생겨요.
4
+
5
+ ## 쓰는 법
6
+
7
+ ```sh
8
+ npx @the-seeker/madefeed@latest
9
+ ```
10
+
11
+ 처음 실행하면 브라우저에서 기기를 연결하고, 이어서 사용량을 올려요. Node.js 22.13 이상이 필요해요.
12
+
13
+ | 명령 | 하는 일 |
14
+ | --- | --- |
15
+ | `madefeed` 또는 `madefeed upload` | 연결이 없으면 연결하고, 사용량을 올려요. |
16
+ | `madefeed login` | 기기만 연결해요. |
17
+ | `madefeed status` | 연결 상태를 보여줘요. |
18
+ | `madefeed logout` | 이 기기의 연결을 지워요. |
19
+
20
+ | 옵션 | 뜻 |
21
+ | --- | --- |
22
+ | `--dry-run` | 아무것도 보내지 않고, 보낼 내용을 그대로 보여줘요. |
23
+ | `--days N` | 오늘을 포함해 며칠 치를 셀지 정해요. 기본 14, 최대 35예요. |
24
+ | `--json` | 결과를 JSON으로만 출력해요. |
25
+ | `--url URL` | 서버 주소예요. 기본은 `https://madefeed.dev`예요. |
26
+
27
+ ## 보내는 것과 보내지 않는 것
28
+
29
+ - 보내는 것: 기기 이름, 날짜, 도구 이름, 모델 이름, 토큰 수
30
+ - 보내지 않는 것: 프롬프트, 대화 내용, 코드, 파일 이름과 경로
31
+
32
+ `--dry-run`으로 실제로 보낼 내용을 먼저 확인할 수 있어요.
33
+
34
+ ## 읽는 곳
35
+
36
+ Claude Code, Codex, OpenCode의 로컬 사용 기록을 읽기 전용으로 읽어요. Cursor는 아직 지원하지 않아요.
package/dist/cli.mjs ADDED
@@ -0,0 +1,630 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { realpathSync } from "node:fs";
5
+ import { homedir, hostname } from "node:os";
6
+ import { pathToFileURL } from "node:url";
7
+ import { parseArgs } from "node:util";
8
+
9
+ // src/aggregate.ts
10
+ import { createReadStream } from "node:fs";
11
+ import { readdir, stat } from "node:fs/promises";
12
+ import { join } from "node:path";
13
+ import { createInterface } from "node:readline";
14
+ var MeterError = class extends Error {
15
+ };
16
+ function isRecord(value) {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+ function record(value) {
20
+ return isRecord(value) ? value : {};
21
+ }
22
+ function parseJson(text) {
23
+ try {
24
+ const value = JSON.parse(text);
25
+ return value;
26
+ } catch (error) {
27
+ if (error instanceof SyntaxError) return void 0;
28
+ throw error;
29
+ }
30
+ }
31
+ function count(value) {
32
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
33
+ }
34
+ function timestamp(value) {
35
+ return typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : NaN;
36
+ }
37
+ function modelName(value) {
38
+ return typeof value === "string" && /^[A-Za-z0-9._:/-]{1,80}$/.test(value) ? value : "unknown";
39
+ }
40
+ function aggregate(rows) {
41
+ const totals = /* @__PURE__ */ new Map();
42
+ for (const row of rows) {
43
+ const model = modelName(row.model);
44
+ const key = JSON.stringify([row.date, row.tool, model]);
45
+ const tokens = (totals.get(key)?.tokens ?? 0) + row.tokens;
46
+ if (!Number.isSafeInteger(tokens) || tokens < 0 || tokens > 2e9)
47
+ throw new MeterError("\uD1A0\uD070 \uD569\uACC4\uAC00 \uC11C\uBC84 \uD5C8\uC6A9 \uBC94\uC704(0~2e9)\uB97C \uBC97\uC5B4\uB098\uC694.");
48
+ totals.set(key, { date: row.date, tool: row.tool, model, tokens });
49
+ }
50
+ return [...totals.values()].sort(
51
+ (a, b) => a.date.localeCompare(b.date) || a.tool.localeCompare(b.tool) || a.model.localeCompare(b.model)
52
+ );
53
+ }
54
+ function payload(deviceName, rows) {
55
+ return { deviceName, rows: aggregate(rows) };
56
+ }
57
+ async function* files(root) {
58
+ for (const entry of await readdir(root, { withFileTypes: true })) {
59
+ const path = join(root, entry.name);
60
+ if (entry.isDirectory()) yield* files(path);
61
+ else if (entry.isFile()) yield path;
62
+ }
63
+ }
64
+ async function* jsonLines(path) {
65
+ const stream = createReadStream(path, { encoding: "utf8" });
66
+ const reader = createInterface({ input: stream, crlfDelay: Infinity });
67
+ try {
68
+ for await (const line of reader) yield parseJson(line);
69
+ } finally {
70
+ reader.close();
71
+ stream.destroy();
72
+ }
73
+ }
74
+ async function recentFile(path, sinceMs) {
75
+ return (await stat(path)).mtimeMs >= sinceMs;
76
+ }
77
+ function unsupported(error, reason) {
78
+ if (error instanceof Error) return { supported: false, reason, rows: [] };
79
+ throw error;
80
+ }
81
+
82
+ // src/api.ts
83
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
84
+ var ApiError = class extends MeterError {
85
+ constructor(status) {
86
+ super(
87
+ status === 401 ? "HTTP 401: \uAE30\uAE30 \uC778\uC99D\uC774 \uC720\uD6A8\uD558\uC9C0 \uC54A\uC544\uC694. login\uC73C\uB85C \uB2E4\uC2DC \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694." : status === 422 ? "HTTP 422: \uC0AC\uC6A9\uB7C9 \uD615\uC2DD\uC774 \uC11C\uBC84 \uADDC\uCE59\uACFC \uB9DE\uC9C0 \uC54A\uC544\uC694." : `HTTP ${status}: \uC11C\uBC84 \uC694\uCCAD\uC5D0 \uC2E4\uD328\uD588\uC5B4\uC694.`
88
+ );
89
+ this.status = status;
90
+ }
91
+ status;
92
+ };
93
+ async function post(api, request) {
94
+ try {
95
+ const response = await api.fetch(`${api.url}${request.path}`, {
96
+ method: "POST",
97
+ redirect: "error",
98
+ signal: AbortSignal.timeout(15e3),
99
+ headers: {
100
+ "content-type": "application/json",
101
+ ...request.token ? { authorization: `Bearer ${request.token}` } : {}
102
+ },
103
+ body: JSON.stringify(request.body)
104
+ });
105
+ const data = await response.json();
106
+ return { status: response.status, data: record(data) };
107
+ } catch (error) {
108
+ if (error instanceof Error)
109
+ throw new MeterError(
110
+ "\uB124\uD2B8\uC6CC\uD06C \uC5F0\uACB0 \uB610\uB294 \uC11C\uBC84 \uC751\uB2F5\uC744 \uD655\uC778\uD574 \uC8FC\uC138\uC694. \uC790\uB3D9 \uC7AC\uC804\uC1A1\uD558\uC9C0 \uC54A\uC544\uC694."
111
+ );
112
+ throw error;
113
+ }
114
+ }
115
+ async function requestDevice(api, deviceName) {
116
+ const { status, data } = await post(api, {
117
+ path: "/api/meter/device",
118
+ body: { deviceName }
119
+ });
120
+ if (status !== 200) throw new ApiError(status);
121
+ const code = data["device_code"];
122
+ const user = data["user_code"];
123
+ const uri = data["verification_uri"];
124
+ const expires = data["expires_in"];
125
+ const interval = data["interval"];
126
+ if (typeof code !== "string" || typeof user !== "string" || typeof uri !== "string" || typeof expires !== "number" || !Number.isFinite(expires) || expires <= 0 || typeof interval !== "number" || !Number.isFinite(interval) || interval <= 0)
127
+ throw new MeterError("\uAE30\uAE30 \uC778\uC99D \uC751\uB2F5\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
128
+ let verification;
129
+ try {
130
+ verification = new URL(uri);
131
+ } catch (error) {
132
+ if (error instanceof TypeError)
133
+ throw new MeterError("\uC778\uC99D \uC8FC\uC18C\uAC00 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
134
+ throw error;
135
+ }
136
+ if (verification.protocol !== "https:" && verification.origin !== api.url)
137
+ throw new MeterError("\uC548\uC804\uD558\uC9C0 \uC54A\uC740 \uC778\uC99D \uC8FC\uC18C\uC608\uC694.");
138
+ return {
139
+ device_code: code,
140
+ user_code: user,
141
+ verification_uri: uri,
142
+ expires_in: expires,
143
+ interval
144
+ };
145
+ }
146
+ async function pollToken(api, device) {
147
+ const deadline = Date.now() + device.expires_in * 1e3;
148
+ const sleep = api.sleep ?? (async (ms) => {
149
+ await setTimeout2(ms);
150
+ });
151
+ for (let attempt = 0; attempt < Math.ceil(device.expires_in / device.interval); attempt++) {
152
+ await sleep(device.interval * 1e3);
153
+ if (Date.now() >= deadline) break;
154
+ const { status, data } = await post(api, {
155
+ path: "/api/meter/token",
156
+ body: { device_code: device.device_code }
157
+ });
158
+ if (status === 200) {
159
+ const token = data["token"];
160
+ if (typeof token !== "string" || !/^mfd_[A-Za-z0-9_-]+$/.test(token))
161
+ throw new MeterError("\uAE30\uAE30 \uD1A0\uD070 \uC751\uB2F5\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
162
+ return token;
163
+ }
164
+ const code = typeof data["error"] === "string" ? data["error"] : record(data["error"])["code"];
165
+ if (status !== 400) throw new ApiError(status);
166
+ switch (code) {
167
+ case "authorization_pending":
168
+ continue;
169
+ case "expired_token":
170
+ throw new MeterError(
171
+ "\uAE30\uAE30 \uC778\uC99D \uCF54\uB4DC\uAC00 \uB9CC\uB8CC\uB410\uC5B4\uC694. login\uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
172
+ );
173
+ case "invalid_grant":
174
+ throw new MeterError(
175
+ "\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 \uC778\uC99D \uCF54\uB4DC\uC608\uC694. login\uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
176
+ );
177
+ default:
178
+ throw new ApiError(status);
179
+ }
180
+ }
181
+ throw new MeterError(
182
+ "\uAE30\uAE30 \uC778\uC99D \uCF54\uB4DC\uAC00 \uB9CC\uB8CC\uB410\uC5B4\uC694. login\uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
183
+ );
184
+ }
185
+ async function uploadUsage(api, token, body) {
186
+ let accepted = 0;
187
+ let weekTokens = 0;
188
+ let votesGranted = 0;
189
+ const safe = payload(body.deviceName, body.rows);
190
+ for (let offset = 0; offset < safe.rows.length; offset += 200) {
191
+ const { status, data } = await post(api, {
192
+ path: "/api/meter/usage",
193
+ token,
194
+ body: {
195
+ deviceName: safe.deviceName,
196
+ rows: safe.rows.slice(offset, offset + 200)
197
+ }
198
+ });
199
+ if (status !== 200) throw new ApiError(status);
200
+ const values = [data["accepted"], data["weekTokens"], data["votesGranted"]];
201
+ if (!values.every(
202
+ (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0
203
+ ))
204
+ throw new MeterError("\uC0AC\uC6A9\uB7C9 \uC800\uC7A5 \uC751\uB2F5\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
205
+ const a = data["accepted"];
206
+ const w = data["weekTokens"];
207
+ const v = data["votesGranted"];
208
+ if (typeof a === "number" && typeof w === "number" && typeof v === "number") {
209
+ accepted += a;
210
+ weekTokens = w;
211
+ votesGranted += v;
212
+ }
213
+ }
214
+ return { accepted, weekTokens, votesGranted };
215
+ }
216
+
217
+ // src/config.ts
218
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
219
+ import { randomUUID } from "node:crypto";
220
+ import { join as join2 } from "node:path";
221
+ function serviceUrl(value) {
222
+ let url;
223
+ try {
224
+ url = new URL(value);
225
+ } catch (error) {
226
+ if (error instanceof TypeError)
227
+ throw new MeterError("\uC11C\uBC84 URL\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
228
+ throw error;
229
+ }
230
+ const local = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
231
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local) || url.username || url.password || url.search || url.hash || url.pathname !== "/")
232
+ throw new MeterError("\uC11C\uBC84 URL\uC740 \uC778\uC99D \uC815\uBCF4 \uC5C6\uB294 HTTPS origin\uC774\uC5B4\uC57C \uD574\uC694.");
233
+ return url.origin;
234
+ }
235
+ async function readConfig(home) {
236
+ try {
237
+ const data = record(
238
+ parseJson(
239
+ await readFile(join2(home, ".config/madefeed/cli.json"), "utf8")
240
+ )
241
+ );
242
+ if (typeof data["url"] !== "string" || typeof data["deviceToken"] !== "string" || !/^mfd_[A-Za-z0-9_-]+$/.test(data["deviceToken"]) || typeof data["deviceName"] !== "string")
243
+ throw new MeterError(
244
+ "\uC124\uC815 \uD30C\uC77C\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694. login\uC73C\uB85C \uB2E4\uC2DC \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694."
245
+ );
246
+ return {
247
+ url: serviceUrl(data["url"]),
248
+ deviceToken: data["deviceToken"],
249
+ deviceName: data["deviceName"]
250
+ };
251
+ } catch (error) {
252
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
253
+ return void 0;
254
+ throw error;
255
+ }
256
+ }
257
+ async function saveConfig(home, config) {
258
+ const directory = join2(home, ".config/madefeed");
259
+ await mkdir(directory, { recursive: true, mode: 448 });
260
+ const temporary = join2(directory, `cli-${randomUUID()}.tmp`);
261
+ try {
262
+ await writeFile(temporary, JSON.stringify(config), {
263
+ mode: 384,
264
+ flag: "wx"
265
+ });
266
+ await chmod(temporary, 384);
267
+ await rename(temporary, join2(directory, "cli.json"));
268
+ } finally {
269
+ await rm(temporary, { force: true });
270
+ }
271
+ }
272
+ async function logout(home) {
273
+ await rm(join2(home, ".config/madefeed/cli.json"), { force: true });
274
+ }
275
+
276
+ // src/kst.ts
277
+ var offsetMs = 9 * 60 * 60 * 1e3;
278
+ function kstDateOf(value) {
279
+ const ms = typeof value === "number" ? value : Date.parse(value);
280
+ return new Date(ms + offsetMs).toISOString().slice(0, 10);
281
+ }
282
+ function windowStart(now, days) {
283
+ return Date.parse(`${kstDateOf(now)}T00:00:00+09:00`) - (days - 1) * 864e5;
284
+ }
285
+
286
+ // src/sources/claude.ts
287
+ import { join as join3 } from "node:path";
288
+ async function readClaude(options) {
289
+ const messages = /* @__PURE__ */ new Map();
290
+ try {
291
+ for await (const path of files(join3(options.home, ".claude/projects"))) {
292
+ if (!path.endsWith(".jsonl") || !await recentFile(path, options.sinceMs))
293
+ continue;
294
+ for await (const value of jsonLines(path)) {
295
+ const event = record(value);
296
+ if (event["type"] !== "assistant") continue;
297
+ const message = record(event["message"]);
298
+ const ms = timestamp(event["timestamp"]);
299
+ if (!Number.isFinite(ms) || ms < options.sinceMs || message["model"] === "<synthetic>")
300
+ continue;
301
+ if (typeof message["id"] !== "string" || typeof event["requestId"] !== "string")
302
+ continue;
303
+ const usage2 = record(message["usage"]);
304
+ const tokens = count(usage2["input_tokens"]) + count(usage2["output_tokens"]) + count(usage2["cache_creation_input_tokens"]) + count(usage2["cache_read_input_tokens"]);
305
+ const key = JSON.stringify([message["id"], event["requestId"]]);
306
+ if (tokens > (messages.get(key)?.tokens ?? -1))
307
+ messages.set(key, {
308
+ date: kstDateOf(ms),
309
+ tool: "claude-code",
310
+ model: modelName(message["model"]),
311
+ tokens
312
+ });
313
+ }
314
+ }
315
+ return { supported: true, rows: [...messages.values()] };
316
+ } catch (error) {
317
+ return unsupported(
318
+ error,
319
+ "Claude Code \uB85C\uADF8\uB97C \uC77D\uC744 \uC218 \uC5C6\uC5B4 unsupported\uB85C \uCC98\uB9AC\uD574\uC694."
320
+ );
321
+ }
322
+ }
323
+
324
+ // src/sources/codex.ts
325
+ import { join as join4, basename } from "node:path";
326
+ async function readCodex(options) {
327
+ const rows = [];
328
+ try {
329
+ for await (const path of files(join4(options.home, ".codex/sessions"))) {
330
+ if (!basename(path).startsWith("rollout-") || !path.endsWith(".jsonl") || !await recentFile(path, options.sinceMs))
331
+ continue;
332
+ let model = "unknown";
333
+ let previous = 0;
334
+ for await (const value of jsonLines(path)) {
335
+ const event = record(value);
336
+ const data = record(event["payload"]);
337
+ if (event["type"] === "turn_context") {
338
+ model = modelName(data["model"]);
339
+ continue;
340
+ }
341
+ if (event["type"] !== "event_msg" || data["type"] !== "token_count")
342
+ continue;
343
+ const info = record(data["info"]);
344
+ const total = record(info["total_token_usage"])["total_tokens"];
345
+ if (typeof total !== "number" || !Number.isSafeInteger(total) || total < 0)
346
+ continue;
347
+ const delta = total >= previous ? total - previous : count(record(info["last_token_usage"])["total_tokens"]);
348
+ previous = total;
349
+ const ms = timestamp(event["timestamp"]);
350
+ if (Number.isFinite(ms) && ms >= options.sinceMs && delta > 0)
351
+ rows.push({
352
+ date: kstDateOf(ms),
353
+ tool: "codex",
354
+ model,
355
+ tokens: delta
356
+ });
357
+ }
358
+ }
359
+ return { supported: true, rows };
360
+ } catch (error) {
361
+ return unsupported(
362
+ error,
363
+ "Codex \uB85C\uADF8\uB97C \uC77D\uC744 \uC218 \uC5C6\uC5B4 unsupported\uB85C \uCC98\uB9AC\uD574\uC694."
364
+ );
365
+ }
366
+ }
367
+
368
+ // src/sources/opencode.ts
369
+ import { readFile as readFile2 } from "node:fs/promises";
370
+ import { join as join5 } from "node:path";
371
+ import { Worker } from "node:worker_threads";
372
+ function databaseWorker() {
373
+ const { parentPort, workerData } = process.getBuiltinModule(
374
+ "node:worker_threads"
375
+ );
376
+ try {
377
+ const sqlite = process.getBuiltinModule?.("node:sqlite");
378
+ if (!sqlite) throw new TypeError("sqlite unavailable");
379
+ const db = new sqlite.DatabaseSync(workerData.path, { readOnly: true });
380
+ try {
381
+ db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=200");
382
+ const sql = "SELECT time_created, data FROM message WHERE time_created >= ?";
383
+ const plan = db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all(workerData.sinceMs);
384
+ if (plan.some(
385
+ (row) => typeof row["detail"] !== "string" || !/SEARCH message .*INDEX .*\(time_created>\?\)/.test(row["detail"])
386
+ ))
387
+ throw new TypeError("no time index");
388
+ const rows = [];
389
+ for (const row of db.prepare(sql).iterate(workerData.sinceMs)) {
390
+ if (rows.length >= 2e5) throw new RangeError("row budget");
391
+ rows.push(row);
392
+ }
393
+ parentPort?.postMessage({ rows });
394
+ } finally {
395
+ db.close();
396
+ }
397
+ } catch (error) {
398
+ if (error instanceof Error) parentPort?.postMessage({ error: true });
399
+ else throw error;
400
+ }
401
+ }
402
+ async function databaseRows(options) {
403
+ const worker = new Worker(`(${databaseWorker.toString()})()`, {
404
+ eval: true,
405
+ workerData: {
406
+ path: join5(options.home, ".local/share/opencode/opencode.db"),
407
+ sinceMs: options.sinceMs
408
+ }
409
+ });
410
+ try {
411
+ return await new Promise((resolve, reject) => {
412
+ const timer = setTimeout(
413
+ () => reject(new MeterError("OpenCode DB \uC2DC\uAC04 \uC608\uC0B0\uC744 \uCD08\uACFC\uD574\uC694.")),
414
+ 2500
415
+ );
416
+ const fail = () => {
417
+ clearTimeout(timer);
418
+ reject(new MeterError("OpenCode DB\uB97C \uC548\uC804\uD558\uAC8C \uC870\uD68C\uD560 \uC218 \uC5C6\uC5B4\uC694."));
419
+ };
420
+ worker.once("error", fail);
421
+ worker.once("exit", fail);
422
+ worker.once("message", (value) => {
423
+ clearTimeout(timer);
424
+ const rows = record(value)["rows"];
425
+ if (Array.isArray(rows)) resolve(rows);
426
+ else fail();
427
+ });
428
+ });
429
+ } finally {
430
+ await worker.terminate();
431
+ }
432
+ }
433
+ function usage(value, ms) {
434
+ const data = record(value);
435
+ if (data["role"] !== "assistant") return void 0;
436
+ const tokens = record(data["tokens"]);
437
+ const cache = record(tokens["cache"]);
438
+ const total = tokens["total"];
439
+ const sum = typeof total === "number" ? count(total) : count(tokens["input"]) + count(tokens["output"]) + count(tokens["reasoning"]) + count(cache["read"]) + count(cache["write"]);
440
+ return {
441
+ date: kstDateOf(ms),
442
+ tool: "opencode",
443
+ model: modelName(data["modelID"]),
444
+ tokens: sum
445
+ };
446
+ }
447
+ async function readOpenCode(options) {
448
+ try {
449
+ const rows = [];
450
+ for (const value of await databaseRows(options)) {
451
+ const row = record(value);
452
+ const ms = timestamp(row["time_created"]);
453
+ if (typeof row["data"] !== "string" || !Number.isFinite(ms)) continue;
454
+ const parsed = usage(parseJson(row["data"]), ms);
455
+ if (parsed) rows.push(parsed);
456
+ }
457
+ return { supported: true, rows };
458
+ } catch (error) {
459
+ if (!(error instanceof Error)) throw error;
460
+ }
461
+ try {
462
+ const rows = [];
463
+ for await (const path of files(
464
+ join5(options.home, ".local/share/opencode/storage/message")
465
+ )) {
466
+ if (!path.endsWith(".json")) continue;
467
+ const data = parseJson(await readFile2(path, "utf8"));
468
+ const ms = timestamp(record(record(data)["time"])["created"]);
469
+ if (!Number.isFinite(ms) || ms < options.sinceMs) continue;
470
+ const parsed = usage(data, ms);
471
+ if (parsed) rows.push(parsed);
472
+ }
473
+ return { supported: true, reason: "OpenCode legacy JSON\uC744 \uC0AC\uC6A9\uD574\uC694.", rows };
474
+ } catch (error) {
475
+ if (!(error instanceof Error)) throw error;
476
+ return {
477
+ supported: false,
478
+ reason: "OpenCode\uB294 \uC2DC\uAC04 \uC778\uB371\uC2A4\xB7\uC870\uD68C \uC2DC\uAC04 \uC608\uC0B0 \uB610\uB294 legacy JSON\uC744 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC5B4 unsupported\uB85C \uCC98\uB9AC\uD574\uC694.",
479
+ rows: []
480
+ };
481
+ }
482
+ }
483
+
484
+ // src/cli.ts
485
+ var help = `madefeed 0.1.0 \u2014 \uD1A0\uD070 \uBBF8\uD130\uC608\uC694.
486
+ \uC0AC\uC6A9\uBC95: madefeed [login|upload|logout|status] [\uC635\uC158]
487
+ --dry-run \uC804\uC1A1 \uC5C6\uC774 \uD569\uACC4\uC640 \uC815\uD655\uD55C \uC694\uCCAD JSON\uC744 \uCD9C\uB825\uD574\uC694.
488
+ --days N \uC624\uB298\uC744 \uD3EC\uD568\uD55C KST \uC77C\uC218\uC608\uC694. \uAE30\uBCF8 14, \uCD5C\uB300 35\uC608\uC694.
489
+ --url URL \uC11C\uBC84 \uC8FC\uC18C\uC608\uC694. MADEFEED_URL \uB610\uB294 https://madefeed.dev\uB97C \uC0AC\uC6A9\uD574\uC694.
490
+ --json \uAE30\uACC4\uAC00 \uC77D\uC744 JSON\uB9CC \uD45C\uC900 \uCD9C\uB825\uC73C\uB85C \uB0B4\uBCF4\uB0B4\uC694.
491
+ --help \uB3C4\uC6C0\uB9D0\uC744 \uBCF4\uC5EC\uC918\uC694.
492
+ --version \uBC84\uC804\uC744 \uBCF4\uC5EC\uC918\uC694.
493
+ \uAE30\uBCF8 \uC2E4\uD589\uC740 \uB85C\uADF8\uC778 \uD6C4 \uC0AC\uC6A9\uB7C9\uC744 \uC804\uC1A1\uD574\uC694. Cursor\uB294 unsupported\uC608\uC694.`;
494
+ async function runCli(args, runtime = {}) {
495
+ let parsed;
496
+ try {
497
+ parsed = parseArgs({
498
+ args: [...args],
499
+ allowPositionals: true,
500
+ options: {
501
+ "dry-run": { type: "boolean" },
502
+ days: { type: "string" },
503
+ url: { type: "string" },
504
+ json: { type: "boolean" },
505
+ help: { type: "boolean" },
506
+ version: { type: "boolean" }
507
+ }
508
+ });
509
+ } catch (error) {
510
+ if (error instanceof Error)
511
+ throw new MeterError(
512
+ "\uBA85\uB839 \uC635\uC158\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694. --help\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694."
513
+ );
514
+ throw error;
515
+ }
516
+ const { values, positionals } = parsed;
517
+ const output = runtime.output ?? console.log;
518
+ const diagnostic = runtime.diagnostic ?? console.error;
519
+ if (values["help"]) {
520
+ output(help);
521
+ return;
522
+ }
523
+ if (values["version"]) {
524
+ output("0.1.0");
525
+ return;
526
+ }
527
+ const days = Number(values["days"] ?? 14);
528
+ if (!Number.isInteger(days) || days < 1 || days > 35)
529
+ throw new MeterError("--days\uB294 1~35 \uC0AC\uC774\uC758 \uC815\uC218\uC5EC\uC57C \uD574\uC694.");
530
+ const command = positionals[0] ?? "upload";
531
+ if (positionals.length > 1 || !["login", "upload", "logout", "status"].includes(command))
532
+ throw new MeterError("\uC54C \uC218 \uC5C6\uB294 \uBA85\uB839\uC774\uC5D0\uC694. --help\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694.");
533
+ if (values["dry-run"] && command !== "upload")
534
+ throw new MeterError(
535
+ "--dry-run\uC740 \uAE30\uBCF8 \uC2E4\uD589 \uB610\uB294 upload\uC5D0\uC11C\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC5B4\uC694."
536
+ );
537
+ const home = runtime.home ?? homedir();
538
+ if (command === "logout") {
539
+ await logout(home);
540
+ output(
541
+ values["json"] ? JSON.stringify({ loggedIn: false }) : "\uB85C\uCEEC \uAE30\uAE30 \uD1A0\uD070\uC744 \uC9C0\uC6E0\uC5B4\uC694. \uC11C\uBC84 \uAE30\uAE30 \uD574\uC81C\uB294 \uC6F9 \uC124\uC815\uC5D0\uC11C \uD560 \uC218 \uC788\uC5B4\uC694."
542
+ );
543
+ return;
544
+ }
545
+ const config = await readConfig(home);
546
+ const chosen = values["url"] ?? process.env["MADEFEED_URL"] ?? config?.url ?? "https://madefeed.dev";
547
+ if (typeof chosen !== "string")
548
+ throw new MeterError("\uC11C\uBC84 URL\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
549
+ const url = serviceUrl(chosen);
550
+ const configured = config?.url === url ? config : void 0;
551
+ const deviceName = configured?.deviceName ?? hostname().replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 80);
552
+ if (command === "status") {
553
+ const status = { loggedIn: Boolean(configured), url, deviceName };
554
+ output(
555
+ values["json"] ? JSON.stringify(status) : configured ? "\uAE30\uAE30\uC5D0 \uB85C\uADF8\uC778 \uC815\uBCF4\uAC00 \uC788\uC5B4\uC694. \uC11C\uBC84 \uC5F0\uACB0\uC740 \uC804\uC1A1\uD560 \uB54C \uD655\uC778\uD574\uC694." : "\uC544\uC9C1 \uB85C\uADF8\uC778\uD558\uC9C0 \uC54A\uC558\uC5B4\uC694. login\uC73C\uB85C \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694."
556
+ );
557
+ return;
558
+ }
559
+ const now = runtime.now ?? Date.now();
560
+ const options = { home, sinceMs: windowStart(now, days) };
561
+ const api = {
562
+ url,
563
+ fetch: runtime.fetch ?? fetch,
564
+ ...runtime.sleep ? { sleep: runtime.sleep } : {}
565
+ };
566
+ const sources = command === "upload" ? await Promise.all([
567
+ readClaude(options),
568
+ readCodex(options),
569
+ readOpenCode(options)
570
+ ]) : [];
571
+ for (const source of sources) if (source.reason) diagnostic(source.reason);
572
+ const rows = aggregate(
573
+ sources.flatMap((source) => source.rows).filter((row) => row.date <= kstDateOf(now))
574
+ );
575
+ const body = payload(deviceName, rows);
576
+ if (values["dry-run"]) {
577
+ if (!values["json"]) {
578
+ output("\uC804\uC1A1\uD558\uC9C0 \uC54A\uC558\uC5B4\uC694. \uC544\uB798 \uD569\uACC4\uC640 JSON\uB9CC \uC804\uC1A1 \uB300\uC0C1\uC774\uC5D0\uC694.");
579
+ output("date tool model tokens");
580
+ for (const row of rows)
581
+ output(
582
+ `${row.date} ${row.tool.padEnd(11)} ${row.model.padEnd(28)} ${row.tokens}`
583
+ );
584
+ }
585
+ output(JSON.stringify(body, null, values["json"] ? void 0 : 2));
586
+ return;
587
+ }
588
+ let token = configured?.deviceToken;
589
+ if (command === "login" || !token) {
590
+ const device = await requestDevice(api, deviceName);
591
+ const instructions = values["json"] ? diagnostic : output;
592
+ instructions(
593
+ `\uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C ${device.verification_uri} \uC8FC\uC18C\uB97C \uC5F4\uACE0 ${device.user_code} \uCF54\uB4DC\uB97C \uC785\uB825\uD574 \uC8FC\uC138\uC694.`
594
+ );
595
+ token = await pollToken(api, device);
596
+ await saveConfig(home, { url, deviceName, deviceToken: token });
597
+ }
598
+ if (command === "login") {
599
+ output(
600
+ values["json"] ? JSON.stringify({ loggedIn: true }) : "\uAE30\uAE30\uB97C \uC5F0\uACB0\uD588\uC5B4\uC694."
601
+ );
602
+ return;
603
+ }
604
+ const result = await uploadUsage(api, token, body);
605
+ output(
606
+ values["json"] ? JSON.stringify(result) : `${result.accepted}\uAC1C \uC0AC\uC6A9\uB7C9 \uD569\uACC4\uB97C \uC804\uC1A1\uD588\uC5B4\uC694.`
607
+ );
608
+ }
609
+ function invokedDirectly() {
610
+ const entry = process.argv[1];
611
+ if (!entry) return false;
612
+ try {
613
+ return import.meta.url === pathToFileURL(realpathSync(entry)).href;
614
+ } catch (error) {
615
+ if (error instanceof Error) return false;
616
+ throw error;
617
+ }
618
+ }
619
+ if (invokedDirectly()) {
620
+ runCli(process.argv.slice(2)).catch((error) => {
621
+ const message = error instanceof MeterError ? error.message : "\uB85C\uCEEC \uC0AC\uC6A9\uB7C9 \uB610\uB294 \uC124\uC815\uC744 \uCC98\uB9AC\uD560 \uC218 \uC5C6\uC5B4\uC694. \uC811\uADFC \uAD8C\uD55C\uACFC Node.js \uBC84\uC804\uC744 \uD655\uC778\uD574 \uC8FC\uC138\uC694.";
622
+ if (process.argv.includes("--json"))
623
+ console.error(JSON.stringify({ error: message }));
624
+ else console.error(message);
625
+ process.exitCode = 1;
626
+ });
627
+ }
628
+ export {
629
+ runCli
630
+ };
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@the-seeker/madefeed",
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": "MadeFeed 토큰 미터: AI 코딩 도구의 토큰 사용량 합계를 madefeed.dev 에 올려요.",
5
+ "homepage": "https://madefeed.dev/meter",
6
+ "license": "UNLICENSED",
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=22.13"
10
+ },
11
+ "bin": {
12
+ "madefeed": "./dist/cli.mjs"
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "scripts": {
22
+ "build": "esbuild src/cli.ts --bundle --platform=node --format=esm --target=node22 --outfile=dist/cli.mjs --banner:js=\"#!/usr/bin/env node\"",
23
+ "typecheck": "tsrs --noEmit",
24
+ "test": "vitest run --passWithNoTests"
25
+ },
26
+ "devDependencies": {
27
+ "esbuild": "0.28.2",
28
+ "@types/node": "^22.18.0"
29
+ }
30
+ }