@hackersbaby/plugin 0.5.0 → 0.5.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.
@@ -6,9 +6,16 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
9
12
  var __commonJS = (cb, mod) => function __require() {
10
13
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
14
  };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
12
19
  var __copyProps = (to, from, except, desc) => {
13
20
  if (from && typeof from === "object" || typeof from === "function") {
14
21
  for (let key of __getOwnPropNames(from))
@@ -25,6 +32,42 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
32
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
33
  mod
27
34
  ));
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+
37
+ // src/config.ts
38
+ function sessionStateFile(source) {
39
+ return import_path.default.join(CONFIG_DIR, `active-session-${source}.json`);
40
+ }
41
+ function ensureConfigDir() {
42
+ if (!import_fs.default.existsSync(CONFIG_DIR)) {
43
+ import_fs.default.mkdirSync(CONFIG_DIR, { recursive: true });
44
+ }
45
+ }
46
+ function loadConfig() {
47
+ try {
48
+ if (!import_fs.default.existsSync(CONFIG_FILE)) return null;
49
+ const raw = import_fs.default.readFileSync(CONFIG_FILE, "utf-8");
50
+ return JSON.parse(raw);
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ function saveConfig(config) {
56
+ ensureConfigDir();
57
+ import_fs.default.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
58
+ }
59
+ var import_fs, import_path, import_os, CONFIG_DIR, CONFIG_FILE, QUEUE_FILE;
60
+ var init_config = __esm({
61
+ "src/config.ts"() {
62
+ "use strict";
63
+ import_fs = __toESM(require("fs"));
64
+ import_path = __toESM(require("path"));
65
+ import_os = __toESM(require("os"));
66
+ CONFIG_DIR = import_path.default.join(import_os.default.homedir(), ".hackersbaby");
67
+ CONFIG_FILE = import_path.default.join(CONFIG_DIR, "config.json");
68
+ QUEUE_FILE = import_path.default.join(CONFIG_DIR, "queue.jsonl");
69
+ }
70
+ });
28
71
 
29
72
  // ../shared/dist/types.js
30
73
  var require_types = __commonJS({
@@ -164,185 +207,175 @@ var require_dist = __commonJS({
164
207
  }
165
208
  });
166
209
 
167
- // src/collector.ts
168
- var import_uuid = require("uuid");
169
-
170
- // src/config.ts
171
- var import_fs = __toESM(require("fs"));
172
- var import_path = __toESM(require("path"));
173
- var import_os = __toESM(require("os"));
174
- var CONFIG_DIR = import_path.default.join(import_os.default.homedir(), ".hackersbaby");
175
- var CONFIG_FILE = import_path.default.join(CONFIG_DIR, "config.json");
176
- var QUEUE_FILE = import_path.default.join(CONFIG_DIR, "queue.jsonl");
177
- function sessionStateFile(source) {
178
- return import_path.default.join(CONFIG_DIR, `active-session-${source}.json`);
179
- }
180
- function ensureConfigDir() {
181
- if (!import_fs.default.existsSync(CONFIG_DIR)) {
182
- import_fs.default.mkdirSync(CONFIG_DIR, { recursive: true });
183
- }
184
- }
185
- function loadConfig() {
186
- try {
187
- if (!import_fs.default.existsSync(CONFIG_FILE)) return null;
188
- const raw = import_fs.default.readFileSync(CONFIG_FILE, "utf-8");
189
- return JSON.parse(raw);
190
- } catch {
191
- return null;
192
- }
193
- }
194
- function saveConfig(config) {
195
- ensureConfigDir();
196
- import_fs.default.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
197
- }
198
-
199
210
  // src/api-client.ts
200
- var import_shared = __toESM(require_dist());
201
- var APIClient = class {
202
- config = loadConfig();
203
- sessionSecret = null;
204
- chainHash = "0000000000000000";
205
- get headers() {
206
- return {
207
- "Content-Type": "application/json",
208
- Authorization: `Bearer ${this.config?.token || ""}`
209
- };
210
- }
211
- /** Register session with server and get cryptographic secret */
212
- async startSession(sessionId) {
213
- try {
214
- const server = this.config?.server || "https://hackers.baby";
215
- const res = await fetch(`${server}/api/sessions/start`, {
216
- method: "POST",
217
- headers: this.headers,
218
- body: JSON.stringify({ session_id: sessionId })
219
- });
220
- if (res.ok) {
221
- const data = await res.json();
222
- this.sessionSecret = data.session_secret;
223
- this.chainHash = data.initial_chain_hash;
224
- return true;
211
+ var import_shared, APIClient;
212
+ var init_api_client = __esm({
213
+ "src/api-client.ts"() {
214
+ "use strict";
215
+ init_config();
216
+ import_shared = __toESM(require_dist());
217
+ APIClient = class {
218
+ config = loadConfig();
219
+ sessionSecret = null;
220
+ chainHash = "0000000000000000";
221
+ onChainUpdate = null;
222
+ /** Set callback to persist chain state between hook processes */
223
+ setChainUpdateCallback(cb) {
224
+ this.onChainUpdate = cb;
225
225
  }
226
- return false;
227
- } catch {
228
- return false;
229
- }
230
- }
231
- async sendBatch(batch) {
232
- try {
233
- const server = this.config?.server || "https://hackers.baby";
234
- if (this.sessionSecret) {
235
- const prevChainHash = this.chainHash;
236
- const newChainHash = (0, import_shared.computeChainHash)(batch.events, prevChainHash);
237
- const signature = (0, import_shared.signBatch)(batch.session_id, batch.events, newChainHash, this.sessionSecret);
238
- batch.signature = signature;
239
- batch.chain_hash = newChainHash;
240
- batch.prev_chain_hash = prevChainHash;
241
- this.chainHash = newChainHash;
226
+ /** Restore crypto state from a previous session */
227
+ restoreCryptoState(secret, chainHash) {
228
+ this.sessionSecret = secret;
229
+ this.chainHash = chainHash;
242
230
  }
243
- const res = await fetch(`${server}/api/scores/batch`, {
244
- method: "POST",
245
- headers: this.headers,
246
- body: JSON.stringify(batch)
247
- });
248
- return res.ok;
249
- } catch {
250
- return false;
251
- }
252
- }
253
- async refreshTokenIfNeeded() {
254
- if (!this.config) return;
255
- try {
256
- const parts = this.config.token.split(".");
257
- if (parts.length !== 3) return;
258
- const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
259
- const expMs = payload.exp * 1e3;
260
- const oneDayMs = 24 * 60 * 60 * 1e3;
261
- if (Date.now() + oneDayMs < expMs) return;
262
- const res = await fetch(`${this.config.server}/api/auth/cli-token/refresh`, {
263
- method: "POST",
264
- headers: this.headers,
265
- body: JSON.stringify({ refresh_token: this.config.refresh_token })
266
- });
267
- if (res.ok) {
268
- const data = await res.json();
269
- if (data.token) {
270
- this.config.token = data.token;
271
- if (data.refresh_token) this.config.refresh_token = data.refresh_token;
272
- saveConfig(this.config);
231
+ get headers() {
232
+ return {
233
+ "Content-Type": "application/json",
234
+ Authorization: `Bearer ${this.config?.token || ""}`
235
+ };
236
+ }
237
+ /** Get current crypto state for persistence */
238
+ getCryptoState() {
239
+ if (!this.sessionSecret) return null;
240
+ return { secret: this.sessionSecret, chainHash: this.chainHash };
241
+ }
242
+ /** Register session with server and get cryptographic secret */
243
+ async startSession(sessionId) {
244
+ try {
245
+ const server = this.config?.server || "https://hackers.baby";
246
+ const res = await fetch(`${server}/api/sessions/start`, {
247
+ method: "POST",
248
+ headers: this.headers,
249
+ body: JSON.stringify({ session_id: sessionId })
250
+ });
251
+ if (res.ok) {
252
+ const data = await res.json();
253
+ this.sessionSecret = data.session_secret;
254
+ this.chainHash = data.initial_chain_hash;
255
+ return true;
256
+ }
257
+ return false;
258
+ } catch {
259
+ return false;
273
260
  }
274
261
  }
275
- } catch {
276
- }
277
- }
278
- async getStatus() {
279
- const server = this.config?.server || "https://hackers.baby";
280
- const res = await fetch(`${server}/api/users/me`, { headers: this.headers });
281
- if (!res.ok) throw new Error(`getStatus failed: ${res.status}`);
282
- return res.json();
283
- }
284
- async getRank() {
285
- const server = this.config?.server || "https://hackers.baby";
286
- const res = await fetch(`${server}/api/users/me/rank`, { headers: this.headers });
287
- if (!res.ok) throw new Error(`getRank failed: ${res.status}`);
288
- return res.json();
289
- }
290
- async getLeaderboard() {
291
- const server = this.config?.server || "https://hackers.baby";
292
- const res = await fetch(`${server}/api/leaderboard/global?limit=10`, { headers: this.headers });
293
- if (!res.ok) throw new Error(`getLeaderboard failed: ${res.status}`);
294
- return res.json();
295
- }
296
- async getPublicStats() {
297
- try {
298
- const server = this.config?.server || "https://hackers.baby";
299
- const res = await fetch(`${server}/api/stats/public`);
300
- if (!res.ok) return null;
301
- return res.json();
302
- } catch {
303
- return null;
304
- }
305
- }
306
- async getNotifications() {
307
- try {
308
- const server = this.config?.server || "https://hackers.baby";
309
- const res = await fetch(`${server}/api/users/me/notifications`, { headers: this.headers });
310
- if (!res.ok) return null;
311
- return res.json();
312
- } catch {
313
- return null;
314
- }
315
- }
316
- async claimReferral(code) {
317
- try {
318
- const server = this.config?.server || "https://hackers.baby";
319
- const res = await fetch(`${server}/api/referral/claim`, {
320
- method: "POST",
321
- headers: this.headers,
322
- body: JSON.stringify({ referral_code: code })
323
- });
324
- if (!res.ok) return null;
325
- return res.json();
326
- } catch {
327
- return null;
328
- }
329
- }
330
- async getReferralStats() {
331
- try {
332
- const server = this.config?.server || "https://hackers.baby";
333
- const res = await fetch(`${server}/api/referral/stats`, { headers: this.headers });
334
- if (!res.ok) return null;
335
- return res.json();
336
- } catch {
337
- return null;
338
- }
262
+ async sendBatch(batch) {
263
+ try {
264
+ const server = this.config?.server || "https://hackers.baby";
265
+ if (this.sessionSecret) {
266
+ const prevChainHash = this.chainHash;
267
+ const newChainHash = (0, import_shared.computeChainHash)(batch.events, prevChainHash);
268
+ const signature = (0, import_shared.signBatch)(batch.session_id, batch.events, newChainHash, this.sessionSecret);
269
+ batch.signature = signature;
270
+ batch.chain_hash = newChainHash;
271
+ batch.prev_chain_hash = prevChainHash;
272
+ this.chainHash = newChainHash;
273
+ if (this.onChainUpdate) {
274
+ this.onChainUpdate(this.chainHash, this.sessionSecret);
275
+ }
276
+ }
277
+ const res = await fetch(`${server}/api/scores/batch`, {
278
+ method: "POST",
279
+ headers: this.headers,
280
+ body: JSON.stringify(batch)
281
+ });
282
+ return res.ok;
283
+ } catch {
284
+ return false;
285
+ }
286
+ }
287
+ async refreshTokenIfNeeded() {
288
+ if (!this.config) return;
289
+ try {
290
+ const parts = this.config.token.split(".");
291
+ if (parts.length !== 3) return;
292
+ const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
293
+ const expMs = payload.exp * 1e3;
294
+ const oneDayMs = 24 * 60 * 60 * 1e3;
295
+ if (Date.now() + oneDayMs < expMs) return;
296
+ const res = await fetch(`${this.config.server}/api/auth/cli-token/refresh`, {
297
+ method: "POST",
298
+ headers: this.headers,
299
+ body: JSON.stringify({ refresh_token: this.config.refresh_token })
300
+ });
301
+ if (res.ok) {
302
+ const data = await res.json();
303
+ if (data.token) {
304
+ this.config.token = data.token;
305
+ if (data.refresh_token) this.config.refresh_token = data.refresh_token;
306
+ saveConfig(this.config);
307
+ }
308
+ }
309
+ } catch {
310
+ }
311
+ }
312
+ async getStatus() {
313
+ const server = this.config?.server || "https://hackers.baby";
314
+ const res = await fetch(`${server}/api/users/me`, { headers: this.headers });
315
+ if (!res.ok) throw new Error(`getStatus failed: ${res.status}`);
316
+ return res.json();
317
+ }
318
+ async getRank() {
319
+ const server = this.config?.server || "https://hackers.baby";
320
+ const res = await fetch(`${server}/api/users/me/rank`, { headers: this.headers });
321
+ if (!res.ok) throw new Error(`getRank failed: ${res.status}`);
322
+ return res.json();
323
+ }
324
+ async getLeaderboard() {
325
+ const server = this.config?.server || "https://hackers.baby";
326
+ const res = await fetch(`${server}/api/leaderboard/global?limit=10`, { headers: this.headers });
327
+ if (!res.ok) throw new Error(`getLeaderboard failed: ${res.status}`);
328
+ return res.json();
329
+ }
330
+ async getPublicStats() {
331
+ try {
332
+ const server = this.config?.server || "https://hackers.baby";
333
+ const res = await fetch(`${server}/api/stats/public`);
334
+ if (!res.ok) return null;
335
+ return res.json();
336
+ } catch {
337
+ return null;
338
+ }
339
+ }
340
+ async getNotifications() {
341
+ try {
342
+ const server = this.config?.server || "https://hackers.baby";
343
+ const res = await fetch(`${server}/api/users/me/notifications`, { headers: this.headers });
344
+ if (!res.ok) return null;
345
+ return res.json();
346
+ } catch {
347
+ return null;
348
+ }
349
+ }
350
+ async claimReferral(code) {
351
+ try {
352
+ const server = this.config?.server || "https://hackers.baby";
353
+ const res = await fetch(`${server}/api/referral/claim`, {
354
+ method: "POST",
355
+ headers: this.headers,
356
+ body: JSON.stringify({ referral_code: code })
357
+ });
358
+ if (!res.ok) return null;
359
+ return res.json();
360
+ } catch {
361
+ return null;
362
+ }
363
+ }
364
+ async getReferralStats() {
365
+ try {
366
+ const server = this.config?.server || "https://hackers.baby";
367
+ const res = await fetch(`${server}/api/referral/stats`, { headers: this.headers });
368
+ if (!res.ok) return null;
369
+ return res.json();
370
+ } catch {
371
+ return null;
372
+ }
373
+ }
374
+ };
339
375
  }
340
- };
376
+ });
341
377
 
342
378
  // src/queue.ts
343
- var import_fs2 = __toESM(require("fs"));
344
- var MAX_QUEUE_SIZE = 1e4;
345
- var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
346
379
  function enqueueEvents(events) {
347
380
  ensureConfigDir();
348
381
  const lines = events.map((e) => JSON.stringify(e)).join("\n");
@@ -380,76 +413,129 @@ function drainQueue() {
380
413
  return [];
381
414
  }
382
415
  }
416
+ var import_fs2, MAX_QUEUE_SIZE, MAX_AGE_MS;
417
+ var init_queue = __esm({
418
+ "src/queue.ts"() {
419
+ "use strict";
420
+ import_fs2 = __toESM(require("fs"));
421
+ init_config();
422
+ MAX_QUEUE_SIZE = 1e4;
423
+ MAX_AGE_MS = 24 * 60 * 60 * 1e3;
424
+ }
425
+ });
383
426
 
384
427
  // src/collector.ts
385
- var EventCollector = class {
386
- sessionId;
387
- buffer = [];
388
- flushInterval = null;
389
- client;
390
- source;
391
- constructor(sessionId, source) {
392
- this.sessionId = sessionId ?? (0, import_uuid.v4)();
393
- this.client = new APIClient();
394
- this.source = source;
395
- }
396
- addEvent(event) {
397
- const metadata = this.source ? { ...event.metadata, source: this.source } : event.metadata;
398
- this.buffer.push({
399
- ...event,
400
- metadata,
401
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
402
- });
403
- }
404
- async start() {
405
- await this.client.refreshTokenIfNeeded();
406
- await this.client.startSession(this.sessionId);
407
- const queued = drainQueue();
408
- if (queued.length > 0) {
409
- const batch = { session_id: this.sessionId, events: queued };
410
- const ok = await this.client.sendBatch(batch);
411
- if (!ok) {
412
- enqueueEvents(queued);
428
+ var collector_exports = {};
429
+ __export(collector_exports, {
430
+ EventCollector: () => EventCollector
431
+ });
432
+ var import_uuid, EventCollector;
433
+ var init_collector = __esm({
434
+ "src/collector.ts"() {
435
+ "use strict";
436
+ import_uuid = require("uuid");
437
+ init_api_client();
438
+ init_queue();
439
+ init_config();
440
+ EventCollector = class {
441
+ sessionId;
442
+ buffer = [];
443
+ flushInterval = null;
444
+ client;
445
+ source;
446
+ constructor(sessionId, source) {
447
+ this.sessionId = sessionId ?? (0, import_uuid.v4)();
448
+ this.client = new APIClient();
449
+ this.source = source;
413
450
  }
414
- }
415
- const config = loadConfig();
416
- const intervalMs = config?.preferences?.batch_interval_ms ?? 1e4;
417
- this.flushInterval = setInterval(() => {
418
- this.flush().catch(() => {
419
- });
420
- }, intervalMs);
421
- }
422
- async flush() {
423
- if (this.buffer.length === 0) return;
424
- const events = this.buffer.splice(0);
425
- const batch = { session_id: this.sessionId, events };
426
- const ok = await this.client.sendBatch(batch);
427
- if (!ok) {
428
- enqueueEvents(events);
429
- }
430
- }
431
- async stop() {
432
- if (this.flushInterval !== null) {
433
- clearInterval(this.flushInterval);
434
- this.flushInterval = null;
435
- }
436
- this.addEvent({ action_type: "session_completed", value: 1, metadata: {} });
437
- await this.flush();
451
+ /** Restore crypto state from persisted session data */
452
+ restoreCrypto(secret, chainHash) {
453
+ this.client.restoreCryptoState(secret, chainHash);
454
+ }
455
+ /** Set callback to persist crypto state after each batch */
456
+ setCryptoUpdateCallback(cb) {
457
+ this.client.setChainUpdateCallback(cb);
458
+ }
459
+ addEvent(event) {
460
+ const metadata = this.source ? { ...event.metadata, source: this.source } : event.metadata;
461
+ this.buffer.push({
462
+ ...event,
463
+ metadata,
464
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
465
+ });
466
+ }
467
+ async start() {
468
+ await this.client.refreshTokenIfNeeded();
469
+ await this.client.startSession(this.sessionId);
470
+ const queued = drainQueue();
471
+ if (queued.length > 0) {
472
+ const batch = { session_id: this.sessionId, events: queued };
473
+ const ok = await this.client.sendBatch(batch);
474
+ if (!ok) {
475
+ enqueueEvents(queued);
476
+ }
477
+ }
478
+ const config = loadConfig();
479
+ const intervalMs = config?.preferences?.batch_interval_ms ?? 1e4;
480
+ this.flushInterval = setInterval(() => {
481
+ this.flush().catch(() => {
482
+ });
483
+ }, intervalMs);
484
+ }
485
+ async flush() {
486
+ if (this.buffer.length === 0) return;
487
+ const events = this.buffer.splice(0);
488
+ const batch = { session_id: this.sessionId, events };
489
+ const ok = await this.client.sendBatch(batch);
490
+ if (!ok) {
491
+ enqueueEvents(events);
492
+ }
493
+ }
494
+ async stop() {
495
+ if (this.flushInterval !== null) {
496
+ clearInterval(this.flushInterval);
497
+ this.flushInterval = null;
498
+ }
499
+ this.addEvent({ action_type: "session_completed", value: 1, metadata: {} });
500
+ await this.flush();
501
+ }
502
+ };
438
503
  }
439
- };
504
+ });
440
505
 
441
506
  // src/hooks/shared/utils.ts
442
507
  var import_fs3 = __toESM(require("fs"));
443
- function loadSessionId(source) {
508
+ init_config();
509
+ function loadSessionState(source) {
444
510
  try {
445
511
  const file = sessionStateFile(source);
446
512
  if (!import_fs3.default.existsSync(file)) return void 0;
447
- const data = JSON.parse(import_fs3.default.readFileSync(file, "utf-8"));
448
- return data.sessionId;
513
+ return JSON.parse(import_fs3.default.readFileSync(file, "utf-8"));
449
514
  } catch {
450
515
  return void 0;
451
516
  }
452
517
  }
518
+ function loadSessionId(source) {
519
+ return loadSessionState(source)?.sessionId;
520
+ }
521
+ function updateSessionState(source, updates) {
522
+ const state = loadSessionState(source);
523
+ if (!state) return;
524
+ const file = sessionStateFile(source);
525
+ import_fs3.default.writeFileSync(file, JSON.stringify({ ...state, ...updates }));
526
+ }
527
+ function createCollector(sessionId, source) {
528
+ const { EventCollector: EventCollector2 } = (init_collector(), __toCommonJS(collector_exports));
529
+ const collector = new EventCollector2(sessionId, source);
530
+ const state = loadSessionState(source);
531
+ if (state?.sessionSecret && state?.chainHash && state.sessionId === sessionId) {
532
+ collector.restoreCrypto(state.sessionSecret, state.chainHash);
533
+ collector.setCryptoUpdateCallback((chainHash, secret) => {
534
+ updateSessionState(source, { chainHash, sessionSecret: secret });
535
+ });
536
+ }
537
+ return collector;
538
+ }
453
539
  function removeSessionState(source) {
454
540
  const file = sessionStateFile(source);
455
541
  if (import_fs3.default.existsSync(file)) import_fs3.default.unlinkSync(file);
@@ -463,7 +549,7 @@ function detectSource(payload) {
463
549
  // src/hooks/shared/session-end.ts
464
550
  async function handleSessionEnd(source) {
465
551
  const detected = detectSource();
466
- const collector = new EventCollector(loadSessionId(detected), detected);
552
+ const collector = createCollector(loadSessionId(detected), detected);
467
553
  await collector.stop();
468
554
  removeSessionState(detected);
469
555
  }