linkedin-relay-mcp 1.0.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/dist/cli.js ADDED
@@ -0,0 +1,2748 @@
1
+ #!/usr/bin/env bun
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // src/cache/store.ts
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
14
+ import { homedir } from "os";
15
+ import { dirname, join } from "path";
16
+ function cacheDir() {
17
+ return process.env.LNRELAY_CACHE_DIR ?? join(homedir(), ".lnrelay");
18
+ }
19
+ function cachePath(...parts) {
20
+ return join(cacheDir(), ...parts);
21
+ }
22
+ function loadJson(path) {
23
+ if (!existsSync(path)) return { state: "missing" };
24
+ let raw;
25
+ try {
26
+ raw = readFileSync(path, "utf-8");
27
+ } catch (e) {
28
+ return quarantine(path, `unreadable: ${e.message}`);
29
+ }
30
+ try {
31
+ return { state: "ok", value: JSON.parse(raw) };
32
+ } catch (e) {
33
+ return quarantine(path, `unparseable JSON: ${e.message}`);
34
+ }
35
+ }
36
+ function quarantine(path, reason) {
37
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
38
+ const target = cachePath("quarantine", stamp, path.split("/").pop() ?? "file");
39
+ try {
40
+ mkdirSync(dirname(target), { recursive: true });
41
+ renameSync(path, target);
42
+ } catch {
43
+ }
44
+ return { state: "corrupt", quarantinedTo: target, reason };
45
+ }
46
+ function saveJson(path, value) {
47
+ mkdirSync(dirname(path), { recursive: true });
48
+ const tmp = `${path}.tmp`;
49
+ writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: "utf-8", mode: 384 });
50
+ renameSync(tmp, path);
51
+ }
52
+ var init_store = __esm({
53
+ "src/cache/store.ts"() {
54
+ "use strict";
55
+ }
56
+ });
57
+
58
+ // src/cache/db.ts
59
+ var db_exports = {};
60
+ __export(db_exports, {
61
+ CacheCorrupt: () => CacheCorrupt,
62
+ THIRD_PARTY_TTL_MS: () => THIRD_PARTY_TTL_MS,
63
+ count: () => count,
64
+ fold: () => fold,
65
+ getCheckpoint: () => getCheckpoint,
66
+ openDb: () => openDb,
67
+ purge: () => purge,
68
+ removeUrns: () => removeUrns,
69
+ search: () => search,
70
+ setCheckpoint: () => setCheckpoint,
71
+ sweepExpired: () => sweepExpired,
72
+ upsert: () => upsert,
73
+ urnsFor: () => urnsFor
74
+ });
75
+ import { Database } from "bun:sqlite";
76
+ import { mkdirSync as mkdirSync2, renameSync as renameSync2 } from "fs";
77
+ function fold(value) {
78
+ return value.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
79
+ }
80
+ function openDb(now = Date.now()) {
81
+ mkdirSync2(cacheDir(), { recursive: true });
82
+ const path = cachePath(DB_FILE);
83
+ let db;
84
+ try {
85
+ db = new Database(path, { create: true });
86
+ const check = db.query("PRAGMA integrity_check").get();
87
+ if (check?.integrity_check !== void 0 && check.integrity_check !== "ok") {
88
+ throw new Error(`integrity_check: ${check.integrity_check}`);
89
+ }
90
+ } catch (e) {
91
+ throw quarantine2(path, e.message, now);
92
+ }
93
+ db.run("PRAGMA journal_mode = WAL");
94
+ for (const stmt of TABLES) db.run(stmt);
95
+ migrate(db);
96
+ for (const stmt of INDEXES) db.run(stmt);
97
+ sweepExpired(db, now);
98
+ return db;
99
+ }
100
+ function migrate(db) {
101
+ const columns = db.query("PRAGMA table_info(records)").all();
102
+ if (!columns.some((c) => c.name === "textFold")) {
103
+ db.run("ALTER TABLE records ADD COLUMN textFold TEXT NOT NULL DEFAULT ''");
104
+ }
105
+ const stale = db.query("SELECT urn, source, text FROM records WHERE textFold = '' AND text != ''").all();
106
+ if (stale.length > 0) {
107
+ const update = db.query("UPDATE records SET textFold = ? WHERE urn = ? AND source = ?");
108
+ db.transaction(() => {
109
+ for (const r of stale) update.run(fold(r.text), r.urn, r.source);
110
+ })();
111
+ }
112
+ }
113
+ function quarantine2(path, reason, now) {
114
+ const stamp = new Date(now).toISOString().replace(/[:.]/g, "-");
115
+ const target = cachePath("quarantine", stamp, DB_FILE);
116
+ try {
117
+ mkdirSync2(cachePath("quarantine", stamp), { recursive: true });
118
+ renameSync2(path, target);
119
+ } catch {
120
+ }
121
+ return new CacheCorrupt(
122
+ `the local cache was unreadable and has been quarantined: ${reason}`,
123
+ target
124
+ );
125
+ }
126
+ function sweepExpired(db, now = Date.now()) {
127
+ const result = db.run(
128
+ "UPDATE records SET body = NULL, text = '', textFold = '' WHERE expiresAt IS NOT NULL AND expiresAt <= ? AND body IS NOT NULL",
129
+ [now]
130
+ );
131
+ return result.changes;
132
+ }
133
+ function upsert(db, source, rows, now = Date.now()) {
134
+ const expiresAt = source === "third-party" ? now + THIRD_PARTY_TTL_MS : null;
135
+ let added = 0;
136
+ let updated = 0;
137
+ const exists = db.query("SELECT 1 FROM records WHERE urn = ? AND source = ?");
138
+ const write = db.query(
139
+ `INSERT INTO records (urn, source, body, text, textFold, firstSeenAt, updatedAt, expiresAt)
140
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
141
+ ON CONFLICT(urn, source) DO UPDATE SET
142
+ body = excluded.body, text = excluded.text, textFold = excluded.textFold,
143
+ updatedAt = excluded.updatedAt, expiresAt = excluded.expiresAt`
144
+ );
145
+ db.transaction(() => {
146
+ for (const row of rows) {
147
+ if (exists.get(row.urn, source) === null) added++;
148
+ else updated++;
149
+ write.run(
150
+ row.urn,
151
+ source,
152
+ JSON.stringify(row.body),
153
+ row.text,
154
+ fold(row.text),
155
+ now,
156
+ now,
157
+ expiresAt
158
+ );
159
+ }
160
+ })();
161
+ return { added, updated };
162
+ }
163
+ function count(db, source) {
164
+ const row = source === void 0 ? db.query("SELECT COUNT(*) AS n FROM records").get() : db.query("SELECT COUNT(*) AS n FROM records WHERE source = ?").get(source);
165
+ return row.n;
166
+ }
167
+ function search(db, query, opts = {}) {
168
+ const sources = opts.sources ?? ["connections", "my-posts", "third-party"];
169
+ const placeholders = sources.map(() => "?").join(",");
170
+ const params = [...sources];
171
+ let sql = `SELECT * FROM records WHERE source IN (${placeholders}) AND body IS NOT NULL`;
172
+ if (query !== "") {
173
+ sql += " AND textFold LIKE ?";
174
+ params.push(`%${fold(query)}%`);
175
+ }
176
+ if (opts.since !== void 0) {
177
+ sql += " AND updatedAt >= ?";
178
+ params.push(opts.since);
179
+ }
180
+ sql += " ORDER BY updatedAt DESC LIMIT ?";
181
+ params.push(opts.limit ?? 25);
182
+ return db.query(sql).all(...params);
183
+ }
184
+ function urnsFor(db, source) {
185
+ const rows = db.query("SELECT urn FROM records WHERE source = ?").all(source);
186
+ return new Set(rows.map((r) => r.urn));
187
+ }
188
+ function removeUrns(db, source, urns) {
189
+ if (urns.length === 0) return 0;
190
+ const stmt = db.query("DELETE FROM records WHERE source = ? AND urn = ?");
191
+ let removed = 0;
192
+ db.transaction(() => {
193
+ for (const urn of urns) removed += stmt.run(source, urn).changes;
194
+ })();
195
+ return removed;
196
+ }
197
+ function getCheckpoint(db, source) {
198
+ const row = db.query("SELECT * FROM checkpoints WHERE source = ?").get(source);
199
+ if (row === null) return void 0;
200
+ return { ...row, headIds: JSON.parse(row.headIds) };
201
+ }
202
+ function setCheckpoint(db, cp) {
203
+ db.run(
204
+ `INSERT INTO checkpoints (source, lastSuccessfulAt, newestCreatedAt, headIds, state)
205
+ VALUES (?, ?, ?, ?, ?)
206
+ ON CONFLICT(source) DO UPDATE SET
207
+ lastSuccessfulAt = excluded.lastSuccessfulAt,
208
+ newestCreatedAt = excluded.newestCreatedAt,
209
+ headIds = excluded.headIds,
210
+ state = excluded.state`,
211
+ [cp.source, cp.lastSuccessfulAt, cp.newestCreatedAt, JSON.stringify(cp.headIds), cp.state]
212
+ );
213
+ }
214
+ function purge(db, scope) {
215
+ const result = scope === "all" ? db.run("DELETE FROM records") : db.run("DELETE FROM records WHERE source = 'third-party'");
216
+ if (scope === "all") db.run("DELETE FROM checkpoints");
217
+ return result.changes;
218
+ }
219
+ var DB_FILE, THIRD_PARTY_TTL_MS, TABLES, INDEXES, CacheCorrupt;
220
+ var init_db = __esm({
221
+ "src/cache/db.ts"() {
222
+ "use strict";
223
+ init_store();
224
+ DB_FILE = "cache.db";
225
+ THIRD_PARTY_TTL_MS = 30 * 864e5;
226
+ TABLES = [
227
+ `CREATE TABLE IF NOT EXISTS records (
228
+ urn TEXT NOT NULL,
229
+ source TEXT NOT NULL,
230
+ body TEXT,
231
+ text TEXT NOT NULL DEFAULT '',
232
+ textFold TEXT NOT NULL DEFAULT '',
233
+ firstSeenAt INTEGER NOT NULL,
234
+ updatedAt INTEGER NOT NULL,
235
+ expiresAt INTEGER,
236
+ PRIMARY KEY (urn, source)
237
+ )`,
238
+ `CREATE TABLE IF NOT EXISTS checkpoints (
239
+ source TEXT PRIMARY KEY,
240
+ lastSuccessfulAt INTEGER NOT NULL,
241
+ newestCreatedAt INTEGER,
242
+ headIds TEXT NOT NULL DEFAULT '[]',
243
+ state TEXT NOT NULL DEFAULT 'ok'
244
+ )`
245
+ ];
246
+ INDEXES = [
247
+ "CREATE INDEX IF NOT EXISTS records_source ON records(source)",
248
+ "CREATE INDEX IF NOT EXISTS records_fold ON records(textFold)",
249
+ "CREATE INDEX IF NOT EXISTS records_expires ON records(expiresAt)"
250
+ ];
251
+ CacheCorrupt = class extends Error {
252
+ constructor(message, quarantinedTo) {
253
+ super(message);
254
+ this.quarantinedTo = quarantinedTo;
255
+ this.name = "CacheCorrupt";
256
+ }
257
+ quarantinedTo;
258
+ };
259
+ }
260
+ });
261
+
262
+ // src/args.ts
263
+ function parseArgs(argv) {
264
+ const [command, ...rest] = argv;
265
+ const positionals = [];
266
+ const flags = {};
267
+ for (let i = 0; i < rest.length; i++) {
268
+ const token = rest[i];
269
+ if (token === void 0) continue;
270
+ if (token.startsWith("--")) {
271
+ const key = token.slice(2);
272
+ const next = rest[i + 1];
273
+ if (next !== void 0 && !next.startsWith("--")) {
274
+ flags[key] = next;
275
+ i++;
276
+ } else {
277
+ flags[key] = true;
278
+ }
279
+ } else if (token.startsWith("-") && token.length > 1) {
280
+ const key = token.slice(1);
281
+ const next = rest[i + 1];
282
+ if (next !== void 0 && !next.startsWith("-")) {
283
+ flags[key] = next;
284
+ i++;
285
+ } else {
286
+ flags[key] = true;
287
+ }
288
+ } else {
289
+ positionals.push(token);
290
+ }
291
+ }
292
+ return { command, positionals, flags };
293
+ }
294
+ function bool(args, name) {
295
+ return args.flags[name] === true || args.flags[name] === "true";
296
+ }
297
+ function str(args, name) {
298
+ const v = args.flags[name];
299
+ return typeof v === "string" ? v : void 0;
300
+ }
301
+ function num(args, name) {
302
+ const v = str(args, name);
303
+ if (v === void 0) return void 0;
304
+ const n = Number(v);
305
+ return Number.isFinite(n) ? n : void 0;
306
+ }
307
+
308
+ // src/commands/cache.ts
309
+ init_db();
310
+
311
+ // src/engine/restli.ts
312
+ var ENCODED = {
313
+ "%": "%25",
314
+ // MUST be first — see below
315
+ "(": "%28",
316
+ ")": "%29",
317
+ ",": "%2C",
318
+ ":": "%3A",
319
+ "|": "%7C",
320
+ "&": "%26",
321
+ "#": "%23",
322
+ "+": "%2B",
323
+ " ": "%20"
324
+ };
325
+ var RESERVED = /[%(),:|&#+ ]/g;
326
+ function encodeScalar(value) {
327
+ if (typeof value !== "string") return String(value);
328
+ return value.replace(RESERVED, (c) => ENCODED[c] ?? c);
329
+ }
330
+ function encodeValue(value) {
331
+ if (value === void 0) return void 0;
332
+ if (Array.isArray(value)) {
333
+ const members = value.map(encodeValue).filter((m) => m !== void 0);
334
+ return `List(${members.join(",")})`;
335
+ }
336
+ if (typeof value === "object") return encodeObject(value);
337
+ return encodeScalar(value);
338
+ }
339
+ function encodeObject(obj) {
340
+ const parts = [];
341
+ for (const [key, value] of Object.entries(obj)) {
342
+ const encoded = encodeValue(value);
343
+ if (encoded !== void 0) parts.push(`${key}:${encoded}`);
344
+ }
345
+ return `(${parts.join(",")})`;
346
+ }
347
+ function encodeVariables(vars) {
348
+ return encodeObject(vars);
349
+ }
350
+ function parseTupleUrn(urn) {
351
+ const open = urn.indexOf(":(");
352
+ if (open === -1 || !urn.endsWith(")")) return null;
353
+ const namespace = urn.slice(0, open).split(":").pop();
354
+ if (namespace === void 0 || namespace === "") return null;
355
+ const body = urn.slice(open + 2, -1);
356
+ const members = [];
357
+ let depth = 0;
358
+ let current = "";
359
+ for (const char of body) {
360
+ if (char === "(") depth++;
361
+ else if (char === ")") depth--;
362
+ if (depth < 0) return null;
363
+ if (char === "," && depth === 0) {
364
+ members.push(current);
365
+ current = "";
366
+ } else {
367
+ current += char;
368
+ }
369
+ }
370
+ if (depth !== 0) return null;
371
+ members.push(current);
372
+ return { namespace, members };
373
+ }
374
+ function innerUrn(urn) {
375
+ const parsed = parseTupleUrn(urn);
376
+ const first = parsed?.members[0];
377
+ return first ?? urn;
378
+ }
379
+ var NAMESPACE_ALIASES = {
380
+ fs_miniProfile: "fsd_profile",
381
+ fs_profile: "fsd_profile"
382
+ };
383
+ function canonicalUrn(urn) {
384
+ const inner = innerUrn(urn);
385
+ const parts = inner.split(":");
386
+ const namespace = parts[2];
387
+ if (namespace === void 0) return inner;
388
+ const alias = NAMESPACE_ALIASES[namespace];
389
+ if (alias === void 0) return inner;
390
+ parts[2] = alias;
391
+ return parts.join(":");
392
+ }
393
+
394
+ // src/format.ts
395
+ function text(value) {
396
+ if (typeof value === "string") return value.trim() || void 0;
397
+ if (value === null || typeof value !== "object") return void 0;
398
+ const node = value;
399
+ if (typeof node.text === "string") return node.text.trim() || void 0;
400
+ if (node.text !== null && typeof node.text === "object") return text(node.text);
401
+ return void 0;
402
+ }
403
+ function typeOf(node) {
404
+ const t = node.$type ?? node._type;
405
+ return typeof t === "string" ? t : void 0;
406
+ }
407
+ function cleanUrl(url) {
408
+ if (typeof url !== "string" || url === "") return void 0;
409
+ const cut = url.indexOf("?");
410
+ return cut === -1 ? url : url.slice(0, cut);
411
+ }
412
+ function defined(obj) {
413
+ for (const key of Object.keys(obj)) {
414
+ if (obj[key] === void 0) delete obj[key];
415
+ }
416
+ return obj;
417
+ }
418
+ function shapeSearchRow(node) {
419
+ const entityUrn = typeof node.entityUrn === "string" ? node.entityUrn : void 0;
420
+ return defined({
421
+ type: typeOf(node),
422
+ // The entity urn is composite — (profileUrn, SEARCH_SRP, DEFAULT) — and the
423
+ // member identity is its first member.
424
+ urn: entityUrn === void 0 ? void 0 : innerUrn(entityUrn),
425
+ name: text(node.title),
426
+ headline: text(node.primarySubtitle),
427
+ location: text(node.secondarySubtitle),
428
+ url: cleanUrl(node.navigationUrl)
429
+ });
430
+ }
431
+ function shapePost(node, index) {
432
+ const meta = node.updateMetadata;
433
+ const actor = node.actor;
434
+ const urn = typeof meta?.urn === "string" ? meta.urn : void 0;
435
+ const social = deref(node, "*socialDetail", index);
436
+ const counts = social === void 0 ? void 0 : deref(social, "*totalSocialActivityCounts", index);
437
+ return defined({
438
+ type: typeOf(node),
439
+ urn,
440
+ threadUrn: typeof social?.urn === "string" ? social.urn : void 0,
441
+ author: text(actor?.name),
442
+ // `text()` already trims; LinkedIn pads these with trailing spaces.
443
+ posted: text(actor?.subDescription),
444
+ text: text(node.commentary),
445
+ likes: numberOf(counts?.numLikes),
446
+ comments: numberOf(counts?.numComments),
447
+ shares: numberOf(counts?.numShares ?? social?.totalShares),
448
+ url: urn === void 0 ? void 0 : `https://www.linkedin.com/feed/update/${urn}/`
449
+ });
450
+ }
451
+ function numberOf(value) {
452
+ return typeof value === "number" ? value : void 0;
453
+ }
454
+ function deref(node, key, index) {
455
+ if (index === void 0) return void 0;
456
+ const ref = node[key];
457
+ if (typeof ref === "string") return index.get(ref);
458
+ if (ref === void 0) return void 0;
459
+ if (ref !== null && typeof ref === "object") {
460
+ for (const [k, v] of Object.entries(ref)) {
461
+ if (k.startsWith("*") && typeof v === "string") return index.get(v);
462
+ }
463
+ }
464
+ return void 0;
465
+ }
466
+ function shapeProfile(node, index) {
467
+ const base = shapeMember(node);
468
+ const geo = deref(node, "geoLocation", index);
469
+ const position = deref(node, "profileTopPosition", index) ?? firstOfType(index, "profile.Position");
470
+ const education = deref(node, "profileTopEducation", index) ?? firstOfType(index, "profile.Education");
471
+ return defined({
472
+ ...base,
473
+ location: text(geo?.defaultLocalizedName) ?? text(geo?.localizedName),
474
+ title: text(position?.title),
475
+ company: text(position?.companyName),
476
+ school: text(education?.schoolName)
477
+ });
478
+ }
479
+ function firstOfType(index, suffix) {
480
+ if (index === void 0) return void 0;
481
+ for (const node of new Set(index.values())) {
482
+ if (String(node.$type ?? "").endsWith(suffix)) return node;
483
+ }
484
+ return void 0;
485
+ }
486
+ function shapeMember(node) {
487
+ const first = text(node.firstName);
488
+ const last = text(node.lastName);
489
+ const publicId = text(node.publicIdentifier) ?? text(node.publicId);
490
+ const name = [first, last].filter(Boolean).join(" ");
491
+ return defined({
492
+ type: typeOf(node),
493
+ urn: typeof node.entityUrn === "string" ? node.entityUrn : void 0,
494
+ publicId,
495
+ name: name === "" ? void 0 : name,
496
+ headline: text(node.headline) ?? text(node.occupation),
497
+ url: publicId === void 0 ? void 0 : `https://www.linkedin.com/in/${publicId}/`
498
+ });
499
+ }
500
+ function shapeComment(node, index) {
501
+ const commenter = node.commenter;
502
+ const social = deref(node, "*socialDetail", index);
503
+ const counts = social === void 0 ? void 0 : deref(social, "*totalSocialActivityCounts", index);
504
+ return defined({
505
+ type: typeOf(node),
506
+ urn: typeof node.urn === "string" ? node.urn : void 0,
507
+ author: text(commenter?.title),
508
+ headline: text(commenter?.subtitle),
509
+ authorUrl: cleanUrl(commenter?.navigationUrl),
510
+ text: text(node.comment) ?? text(node.commentary),
511
+ likes: numberOf(counts?.numLikes),
512
+ postedAt: typeof node.createdAt === "number" ? new Date(node.createdAt).toISOString() : void 0,
513
+ edited: node.edited === true ? true : void 0,
514
+ url: cleanUrl(node.permalink)
515
+ });
516
+ }
517
+ function shapeReaction(node, index) {
518
+ const lockup = node.reactorLockup;
519
+ const actorUrn = typeof node.actorUrn === "string" ? node.actorUrn : void 0;
520
+ const profile = actorUrn === void 0 ? void 0 : index?.get(actorUrn);
521
+ return defined({
522
+ type: typeOf(node),
523
+ urn: actorUrn,
524
+ name: text(lockup?.title),
525
+ headline: text(lockup?.subtitle) ?? text(profile?.headline),
526
+ reaction: typeof node.reactionType === "string" ? node.reactionType : void 0,
527
+ url: cleanUrl(lockup?.navigationUrl)
528
+ });
529
+ }
530
+ function shapeEntity(node, index) {
531
+ try {
532
+ const t = (typeOf(node) ?? "").toLowerCase();
533
+ if (t.includes("entityresultviewmodel")) return shapeSearchRow(node);
534
+ if (t.endsWith("social.comment")) return shapeComment(node, index);
535
+ if (t.endsWith("social.reaction")) return shapeReaction(node, index);
536
+ if (t.includes("update")) return shapePost(node, index);
537
+ if (t.includes("profile")) return shapeMember(node);
538
+ return defined({
539
+ type: typeOf(node),
540
+ urn: typeof node.entityUrn === "string" ? node.entityUrn : void 0,
541
+ name: text(node.title) ?? text(node.name),
542
+ text: text(node.commentary) ?? text(node.text)
543
+ });
544
+ } catch {
545
+ return defined({ type: typeOf(node) });
546
+ }
547
+ }
548
+ function shapeAll(items, index) {
549
+ return items.map((node) => shapeEntity(node, index));
550
+ }
551
+ function project(rows, spec) {
552
+ const keys = spec.split(",").map((k) => k.trim()).filter((k) => k !== "");
553
+ if (keys.length === 0) return rows;
554
+ return rows.map((row) => {
555
+ const out = {};
556
+ for (const key of keys) {
557
+ if (row[key] !== void 0) out[key] = row[key];
558
+ }
559
+ return out;
560
+ });
561
+ }
562
+ var LEAD = ["name", "author", "title"];
563
+ var DETAIL = ["headline", "text", "location", "company", "posted", "reaction"];
564
+ function compactRows(rows) {
565
+ return rows.map((row) => {
566
+ const parts = [];
567
+ for (const key of LEAD) {
568
+ const v = row[key];
569
+ if (typeof v === "string" && v !== "") {
570
+ parts.push(v);
571
+ break;
572
+ }
573
+ }
574
+ for (const key of DETAIL) {
575
+ const v = row[key];
576
+ if (typeof v === "string" && v !== "") parts.push(v);
577
+ }
578
+ const counts = ["likes", "comments"].map((k) => typeof row[k] === "number" ? `${row[k]} ${k}` : void 0).filter((v) => v !== void 0);
579
+ parts.push(...counts);
580
+ if (parts.length === 0) {
581
+ const urn = row.urn ?? row.type;
582
+ if (typeof urn === "string") parts.push(urn);
583
+ }
584
+ return parts.join(" \xB7 ").replace(/\s*\n\s*/g, " ");
585
+ });
586
+ }
587
+
588
+ // src/output.ts
589
+ function ok(command, data) {
590
+ return { ok: true, command, data };
591
+ }
592
+ function err(command, code, message, hint, status, retryAfterMs) {
593
+ const error = { code, message };
594
+ if (hint !== void 0) error.hint = hint;
595
+ if (status !== void 0) error.status = status;
596
+ if (retryAfterMs !== void 0) error.retryAfterMs = retryAfterMs;
597
+ return { ok: false, command, error };
598
+ }
599
+ function toJson(envelope) {
600
+ return JSON.stringify(envelope, null, 2);
601
+ }
602
+ function exitCodeFor(envelope) {
603
+ if (envelope.ok) return 0;
604
+ return envelope.error.code === "UNKNOWN_COMMAND" ? 2 : 1;
605
+ }
606
+
607
+ // src/commands/cache.ts
608
+ var SOURCES = ["connections", "my-posts", "third-party"];
609
+ function corruptEnvelope(command, e) {
610
+ if (e instanceof CacheCorrupt) {
611
+ return err(
612
+ command,
613
+ "CACHE_CORRUPT",
614
+ e.message,
615
+ `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as an empty one \u2014 that would trigger a full re-sync against LinkedIn. Inspect it, then re-run.`
616
+ );
617
+ }
618
+ throw e;
619
+ }
620
+ function render(rows, opts) {
621
+ if (opts.compact === true) return compactRows(rows);
622
+ if (opts.fields !== void 0 && opts.fields !== "") return project(rows, opts.fields);
623
+ return rows;
624
+ }
625
+ function runLocal(query, sources, since, limit, opts = {}) {
626
+ const requested = sources?.split(",").map((s) => s.trim()) ?? SOURCES;
627
+ const invalid = requested.filter((s) => !SOURCES.includes(s));
628
+ if (invalid.length > 0) {
629
+ return err(
630
+ "local",
631
+ "INVALID_INPUT",
632
+ `unknown source(s): ${invalid.join(", ")}`,
633
+ `valid sources: ${SOURCES.join(", ")}`
634
+ );
635
+ }
636
+ let sinceMs;
637
+ if (since !== void 0) {
638
+ const parsed = Date.parse(since);
639
+ if (Number.isNaN(parsed)) {
640
+ return err("local", "INVALID_INPUT", `could not parse --since '${since}'`, "use YYYY-MM-DD");
641
+ }
642
+ sinceMs = parsed;
643
+ }
644
+ try {
645
+ const db = openDb();
646
+ const rows = search(db, query ?? "", {
647
+ sources: requested,
648
+ ...sinceMs === void 0 ? {} : { since: sinceMs },
649
+ limit
650
+ });
651
+ const total = count(db);
652
+ const shaped = rows.map((r) => ({
653
+ ...JSON.parse(r.body ?? "{}"),
654
+ source: r.source,
655
+ cachedAt: new Date(r.updatedAt).toISOString()
656
+ }));
657
+ return ok("local", {
658
+ items: render(shaped, opts),
659
+ meta: {
660
+ returnedCount: rows.length,
661
+ cachedTotal: total,
662
+ sources: requested,
663
+ // An empty cache is not an empty LinkedIn — say which one this is.
664
+ note: total === 0 ? "The local cache is empty. Run a read command with --retain, or sync a source, before searching offline." : void 0
665
+ }
666
+ });
667
+ } catch (e) {
668
+ return corruptEnvelope("local", e);
669
+ }
670
+ }
671
+ function runSourceRead(command, query, limit, opts = {}) {
672
+ const result = runLocal(query, command, void 0, limit, opts);
673
+ if (!result.ok) return result;
674
+ const data = result.data;
675
+ const meta = data.meta;
676
+ if (meta.cachedTotal === 0 || meta.returnedCount === 0) {
677
+ meta.note = `Nothing cached for '${command}'. Run \`lnrelay sync ${command}\` first \u2014 this command reads the local cache and makes no network call.`;
678
+ }
679
+ return ok(command, data);
680
+ }
681
+ function runPurge(scope, confirmed) {
682
+ const target = scope === "all" ? "all" : "third-party";
683
+ if (!confirmed) {
684
+ try {
685
+ const db = openDb();
686
+ return err(
687
+ "purge",
688
+ "CONFIRMATION_REQUIRED",
689
+ `would delete ${target === "all" ? count(db) : count(db, "third-party")} records (${target})`,
690
+ "Re-run with --confirm. This only touches local files; it never contacts LinkedIn."
691
+ );
692
+ } catch (e) {
693
+ return corruptEnvelope("purge", e);
694
+ }
695
+ }
696
+ try {
697
+ const db = openDb();
698
+ const removed = purge(db, target);
699
+ return ok("purge", { scope: target, removed, remaining: count(db) });
700
+ } catch (e) {
701
+ return corruptEnvelope("purge", e);
702
+ }
703
+ }
704
+ function runCacheStatus() {
705
+ try {
706
+ const db = openDb();
707
+ return ok("cache-status", {
708
+ total: count(db),
709
+ bySource: Object.fromEntries(SOURCES.map((s) => [s, count(db, s)])),
710
+ checkpoints: Object.fromEntries(SOURCES.map((s) => [s, getCheckpoint(db, s) ?? null])),
711
+ retention: "Third-party records expire 30 days after capture; the body is deleted and an identity stub remains so a re-fetch is a visible choice. Owner data never expires."
712
+ });
713
+ } catch (e) {
714
+ return corruptEnvelope("cache-status", e);
715
+ }
716
+ }
717
+ function retain(source, items) {
718
+ const rows = items.filter((i) => typeof i.urn === "string" && i.urn !== "").map((i) => ({
719
+ urn: i.urn,
720
+ body: i,
721
+ text: [i.name, i.headline, i.location, i.text, i.author, i.company, i.title].filter((v) => typeof v === "string").join(" ")
722
+ }));
723
+ if (rows.length === 0) return { skipped: "no items carried a urn to key on" };
724
+ try {
725
+ return upsert(openDb(), source, rows);
726
+ } catch (e) {
727
+ return { skipped: e.message };
728
+ }
729
+ }
730
+
731
+ // src/engine/index.ts
732
+ init_store();
733
+
734
+ // src/progress.ts
735
+ function progressReporter(quiet, write = (s) => {
736
+ process.stderr.write(s);
737
+ }) {
738
+ return (msg) => {
739
+ if (!quiet) write(`${msg}
740
+ `);
741
+ };
742
+ }
743
+
744
+ // src/engine/budget.ts
745
+ var HOUR = 36e5;
746
+ var DAY = 864e5;
747
+ var CAPS = {
748
+ profile: {
749
+ perDay: 30,
750
+ provenance: "vendor-lore",
751
+ note: "transplanted from jjuanrivvera/linkedin-cli's job-detail cap"
752
+ },
753
+ search: { perDay: 25, provenance: "guessed", note: "no corroborated figure exists" },
754
+ page: { perDay: 60, provenance: "guessed", note: "thread/feed pagination" },
755
+ write: {
756
+ perDay: 10,
757
+ provenance: "guessed",
758
+ note: "deliberately below the weakly-reported ~20/day connection lore"
759
+ },
760
+ global: { perDay: 250, provenance: "guessed", note: "all classes combined" }
761
+ };
762
+ var MIN_GAP_MS = 3e3;
763
+ function emptyLedger() {
764
+ return { spends: {} };
765
+ }
766
+ function within(times, now, window) {
767
+ if (times === void 0) return [];
768
+ return times.filter((t) => now - t < window);
769
+ }
770
+ function allSpends(ledger2, now) {
771
+ return Object.values(ledger2.spends).flatMap((times) => within(times, now, DAY));
772
+ }
773
+ function spend(ledger2, cls, now) {
774
+ const recent = allSpends(ledger2, now);
775
+ const last = recent.length > 0 ? Math.max(...recent) : void 0;
776
+ if (last !== void 0 && now - last < MIN_GAP_MS) {
777
+ return {
778
+ error: {
779
+ code: "BUDGET_EXHAUSTED",
780
+ message: `minimum gap of ${MIN_GAP_MS}ms between calls not met`,
781
+ hint: "requests are paced deliberately; wait and retry"
782
+ }
783
+ };
784
+ }
785
+ if (recent.length >= CAPS.global.perDay) {
786
+ return {
787
+ error: {
788
+ code: "BUDGET_EXHAUSTED",
789
+ message: `global daily cap of ${CAPS.global.perDay} calls reached`,
790
+ hint: "resets on a rolling 24h window; see `lnrelay budget`"
791
+ }
792
+ };
793
+ }
794
+ const cap = CAPS[cls];
795
+ const forClass = within(ledger2.spends[cls], now, DAY);
796
+ if (forClass.length >= cap.perDay) {
797
+ return {
798
+ error: {
799
+ code: "BUDGET_EXHAUSTED",
800
+ message: `daily cap of ${cap.perDay} reached for '${cls}'`,
801
+ hint: `cap provenance: ${cap.provenance} (${cap.note}). See \`lnrelay budget\`.`
802
+ }
803
+ };
804
+ }
805
+ return {
806
+ permit: { class: cls, issuedAt: now },
807
+ ledger: { spends: { ...ledger2.spends, [cls]: [...forClass, now] } }
808
+ };
809
+ }
810
+ function summarise(ledger2, cls, now) {
811
+ const cap = CAPS[cls];
812
+ const spent = cls === "global" ? allSpends(ledger2, now).length : within(ledger2.spends[cls], now, DAY).length;
813
+ const remaining = Math.max(0, cap.perDay - spent);
814
+ const summary = {
815
+ class: cls,
816
+ spentInWindow: spent,
817
+ cap: cap.perDay,
818
+ remaining,
819
+ capProvenance: cap.provenance
820
+ };
821
+ if (remaining / cap.perDay < 0.25) {
822
+ summary.warning = `only ${remaining} of ${cap.perDay} '${cls}' calls left in this 24h window \u2014 consider stopping`;
823
+ }
824
+ return summary;
825
+ }
826
+ function openCooldown(reason, now) {
827
+ if (reason === "CHALLENGE_DETECTED") {
828
+ return { reason, since: now, until: null, clearRequires: "human" };
829
+ }
830
+ const duration = reason === "REQUEST_DENIED" ? 6 * HOUR : HOUR;
831
+ return { reason, since: now, until: now + duration, clearRequires: "time" };
832
+ }
833
+ function activeCooldown(cooldown, now) {
834
+ if (cooldown === null) return false;
835
+ if (cooldown.until === null) return true;
836
+ return now < cooldown.until;
837
+ }
838
+
839
+ // src/engine/auth.ts
840
+ function csrfToken(jsessionId) {
841
+ return jsessionId.replace(/"/g, "");
842
+ }
843
+ function buildHeaders(session) {
844
+ return {
845
+ cookie: `li_at=${session.liAt}; JSESSIONID=${session.jsessionId}`,
846
+ "csrf-token": csrfToken(session.jsessionId),
847
+ "x-restli-protocol-version": "2.0.0",
848
+ accept: "application/vnd.linkedin.normalized+json+2.1",
849
+ "x-li-lang": "en_US",
850
+ "user-agent": session.userAgent
851
+ };
852
+ }
853
+
854
+ // src/engine/classify.ts
855
+ var CHALLENGE_MARKERS = /checkpoint|challenge|captcha|security verification|unusual activity/i;
856
+ var LOGIN_REDIRECT = /\/login|\/uas\/login|session_redirect/i;
857
+ function fail(code, message, extra = {}) {
858
+ return { outcome: "error", code, message, retry: false, ...extra };
859
+ }
860
+ var CHALLENGE_HINT = "Open LinkedIn in a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.";
861
+ function classifyRedirect(location) {
862
+ if (CHALLENGE_MARKERS.test(location)) {
863
+ return fail("CHALLENGE_DETECTED", `redirected to a challenge: ${location}`, {
864
+ cooldown: "CHALLENGE_DETECTED",
865
+ hint: CHALLENGE_HINT
866
+ });
867
+ }
868
+ if (LOGIN_REDIRECT.test(location)) {
869
+ return fail("AUTH_FAILED", "redirected to the login page", {
870
+ hint: "This signature means expired cookies, NOT bot detection. Re-run `lnrelay login`."
871
+ });
872
+ }
873
+ return fail("FETCH_FAILED", `unexpected redirect to ${location || "(none)"}`);
874
+ }
875
+ function classifyBody(body) {
876
+ if (CHALLENGE_MARKERS.test(body.slice(0, 4e3))) {
877
+ return fail("CHALLENGE_DETECTED", "a challenge page was returned with status 200", {
878
+ cooldown: "CHALLENGE_DETECTED",
879
+ hint: CHALLENGE_HINT
880
+ });
881
+ }
882
+ let json;
883
+ try {
884
+ json = JSON.parse(body);
885
+ } catch {
886
+ return fail("SCHEMA_DRIFT", "response was 200 but not JSON", {
887
+ hint: "LinkedIn may have served HTML \u2014 inspect the raw body."
888
+ });
889
+ }
890
+ const envelope = json;
891
+ const innerStatus = envelope.data?.status;
892
+ if (typeof innerStatus === "number" && innerStatus >= 400) {
893
+ return fail("SCHEMA_DRIFT", `body carries an inner status ${innerStatus}`, {
894
+ hint: "The endpoint answered but reported a failure. Re-capture the operation."
895
+ });
896
+ }
897
+ if (referencesUrns(envelope.data) && (envelope.included?.length ?? 0) === 0) {
898
+ return fail("SCHEMA_DRIFT", "data references entities but included[] is empty", {
899
+ hint: "Decoration failed wholesale \u2014 this is a failed fetch, not an empty result."
900
+ });
901
+ }
902
+ return { outcome: "ok", retry: false, json };
903
+ }
904
+ function classify(res) {
905
+ const headers2 = res.headers ?? {};
906
+ if (res.status >= 300 && res.status < 400) {
907
+ return classifyRedirect(headers2.location ?? "");
908
+ }
909
+ if (res.status === 999) {
910
+ return fail("REQUEST_DENIED", "LinkedIn returned HTTP 999 (Request Denied)", {
911
+ cooldown: "REQUEST_DENIED",
912
+ hint: "A network-layer bot block that lifts only as traffic normalises. Stop making requests."
913
+ });
914
+ }
915
+ if (res.status === 429) {
916
+ const retryAfter = Number(headers2["retry-after"]);
917
+ const out = fail("RATE_LIMITED", "LinkedIn throttled this request", {
918
+ cooldown: "RATE_LIMITED",
919
+ hint: "Not retried automatically \u2014 a throttle is the warning shot before a restriction."
920
+ });
921
+ if (Number.isFinite(retryAfter)) out.retryAfterMs = retryAfter * 1e3;
922
+ return out;
923
+ }
924
+ if (res.status === 401 || res.status === 403) {
925
+ return fail("AUTH_FAILED", `LinkedIn rejected the session (${res.status})`, {
926
+ hint: "Usually expired cookies. Re-run `lnrelay login`."
927
+ });
928
+ }
929
+ if (res.status === 410) {
930
+ return fail("SCHEMA_DRIFT", "endpoint returned 410 Gone \u2014 it no longer exists", {
931
+ hint: "Re-capture the operation with scripts/observe.ts and update src/engine/contracts.ts."
932
+ });
933
+ }
934
+ if (res.status === 400) {
935
+ const hint = /queryid/i.test(res.body) ? "re-capture the queryId with scripts/observe.ts and update src/engine/contracts.ts" : "check the encoded variables against a live capture";
936
+ return fail("SCHEMA_DRIFT", `LinkedIn rejected the request shape (400)`, { hint });
937
+ }
938
+ if (res.status === 404) {
939
+ return fail("NOT_FOUND", "no such resource");
940
+ }
941
+ if (res.status !== 200) {
942
+ return fail("FETCH_FAILED", `unexpected status ${res.status}`);
943
+ }
944
+ return classifyBody(res.body);
945
+ }
946
+ function referencesUrns(data) {
947
+ if (data === void 0) return false;
948
+ let found = false;
949
+ const walk = (node) => {
950
+ if (found || node === null || typeof node !== "object") return;
951
+ if (Array.isArray(node)) {
952
+ for (const item of node) walk(item);
953
+ return;
954
+ }
955
+ for (const [key, value] of Object.entries(node)) {
956
+ if (key.startsWith("*") && Array.isArray(value) && value.length > 0) {
957
+ found = true;
958
+ return;
959
+ }
960
+ if (typeof value === "string" && value.startsWith("urn:li:")) {
961
+ found = true;
962
+ return;
963
+ }
964
+ walk(value);
965
+ }
966
+ };
967
+ walk(data);
968
+ return found;
969
+ }
970
+
971
+ // src/engine/client.ts
972
+ var MAX_GAP_MS = 15e3;
973
+ function createClient(session, deps) {
974
+ async function request(spec) {
975
+ const now = deps.now();
976
+ const cooldown = deps.loadCooldown();
977
+ if (activeCooldown(cooldown, now)) {
978
+ const until = cooldown?.until === null ? "indefinitely" : `until ${new Date(cooldown?.until ?? 0).toISOString()}`;
979
+ return {
980
+ ok: false,
981
+ code: "COOLDOWN_ACTIVE",
982
+ message: `refusing to call LinkedIn: ${cooldown?.reason} cooldown is active ${until}`,
983
+ hint: cooldown?.clearRequires === "human" ? "Log in through a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`." : "Wait for it to lift, or inspect `lnrelay risk`."
984
+ };
985
+ }
986
+ const ledger2 = deps.loadLedger();
987
+ const result = spend(ledger2, spec.spendClass, now);
988
+ if ("error" in result) {
989
+ return {
990
+ ok: false,
991
+ code: result.error.code,
992
+ message: result.error.message,
993
+ hint: result.error.hint
994
+ };
995
+ }
996
+ deps.saveLedger(result.ledger);
997
+ const gap = MIN_GAP_MS + Math.floor(deps.random() * (MAX_GAP_MS - MIN_GAP_MS));
998
+ deps.progress?.(`${spec.operation}: pacing ${Math.round(gap / 1e3)}s before the request\u2026`);
999
+ await deps.sleep(gap);
1000
+ deps.progress?.(`${spec.operation}: requesting\u2026`);
1001
+ const raw = await fetchRaw(spec, session, deps);
1002
+ if (raw === null) {
1003
+ return { ok: false, code: "FETCH_FAILED", message: "the request could not be completed" };
1004
+ }
1005
+ const classification = classify(raw);
1006
+ if (classification.cooldown !== void 0) {
1007
+ deps.saveCooldown(openCooldown(classification.cooldown, deps.now()));
1008
+ }
1009
+ if (classification.outcome === "error") {
1010
+ const out = {
1011
+ ok: false,
1012
+ code: classification.code ?? "FETCH_FAILED",
1013
+ message: classification.message ?? "request failed"
1014
+ };
1015
+ if (classification.hint !== void 0) out.hint = classification.hint;
1016
+ if (classification.retryAfterMs !== void 0) out.retryAfterMs = classification.retryAfterMs;
1017
+ return out;
1018
+ }
1019
+ return { ok: true, json: classification.json, classification };
1020
+ }
1021
+ return { request };
1022
+ }
1023
+ async function fetchRaw(spec, session, deps) {
1024
+ try {
1025
+ const res = await deps.fetch(spec.url, {
1026
+ method: spec.method ?? "GET",
1027
+ headers: buildHeaders(session),
1028
+ // Manual, so a login or checkpoint redirect is classified rather than
1029
+ // silently followed into an HTML page that parses as "no data".
1030
+ redirect: "manual"
1031
+ });
1032
+ const headers2 = {};
1033
+ res.headers.forEach((value, key) => {
1034
+ headers2[key.toLowerCase()] = value;
1035
+ });
1036
+ return { status: res.status, body: await res.text(), headers: headers2 };
1037
+ } catch {
1038
+ return null;
1039
+ }
1040
+ }
1041
+
1042
+ // src/engine/contracts.ts
1043
+ var VOYAGER = "https://www.linkedin.com/voyager/api";
1044
+ var CONTRACTS = {
1045
+ me: {
1046
+ name: "me",
1047
+ transport: "voyager-restli",
1048
+ path: `${VOYAGER}/me`,
1049
+ provenance: "verified",
1050
+ capturedAt: "2026-08-01"
1051
+ },
1052
+ // Three `voyagerIdentityDashProfiles` queryIds were observed on one page —
1053
+ // they are different PROJECTIONS of one operation, and picking the wrong one
1054
+ // gets you a 200 containing nothing useful:
1055
+ //
1056
+ // b5c27c04… identity only — entityUrn + versionTag. Looks like success.
1057
+ // e9b08094… the real profile: headline, geo, top position, education. ← this
1058
+ // da93c92b… 400s with (profileUrn:…); its variables shape is unknown.
1059
+ //
1060
+ // None of them returns firstName/lastName/publicIdentifier — LinkedIn splits
1061
+ // names into a projection we have not identified. Documented rather than
1062
+ // faked; the caller already knows who they asked for.
1063
+ profile: {
1064
+ name: "profile",
1065
+ transport: "voyager-graphql",
1066
+ path: `${VOYAGER}/graphql`,
1067
+ queryId: "voyagerIdentityDashProfiles.e9b0809465a07db1f02e70a82d455e10",
1068
+ provenance: "verified",
1069
+ capturedAt: "2026-08-01"
1070
+ },
1071
+ feed: {
1072
+ name: "feed",
1073
+ transport: "voyager-restli",
1074
+ path: `${VOYAGER}/feed/updatesV2`,
1075
+ provenance: "verified",
1076
+ capturedAt: "2026-08-01"
1077
+ },
1078
+ // The November-2024 queryId, still returning 200 in August 2026 — roughly 21
1079
+ // months unchanged. Notable because kill criterion #3 assumed queryIds might
1080
+ // rotate weekly; on this evidence they are build-pinned but long-lived.
1081
+ search: {
1082
+ name: "search",
1083
+ transport: "voyager-graphql",
1084
+ path: `${VOYAGER}/graphql`,
1085
+ queryId: "voyagerSearchDashClusters.b0928897b71bd00a5a7291755dcd64f0",
1086
+ provenance: "verified",
1087
+ capturedAt: "2026-08-01"
1088
+ },
1089
+ reactions: {
1090
+ name: "reactions",
1091
+ transport: "voyager-graphql",
1092
+ path: `${VOYAGER}/graphql`,
1093
+ queryId: "voyagerSocialDashReactions.41ebf31a9f4c4a84e35a49d5abc9010b",
1094
+ provenance: "verified",
1095
+ capturedAt: "2026-08-02"
1096
+ },
1097
+ // Comments. The variables carry a COMPOSITE socialDetailUrn assembled from the
1098
+ // post's own urn, repeated, plus a highlightedReply placeholder:
1099
+ //
1100
+ // urn:li:fsd_socialDetail:(<postUrn>,<postUrn>,urn:li:highlightedReply:-)
1101
+ //
1102
+ // Two things were established by probing rather than assumed. Our codec's
1103
+ // percent-encoding of that urn's colons and parens is REQUIRED — the literal
1104
+ // form returns 400. And an `urn:li:activity:` post urn works directly, so
1105
+ // `post` does not need a feed lookup to find the ugcPost form first.
1106
+ comments: {
1107
+ name: "comments",
1108
+ transport: "voyager-graphql",
1109
+ path: `${VOYAGER}/graphql`,
1110
+ queryId: "voyagerSocialDashComments.afec6d88d7810d45548797a8dac4fb87",
1111
+ provenance: "verified",
1112
+ capturedAt: "2026-08-02"
1113
+ },
1114
+ // The member's own posts. Verified 200; returns an empty collection on an
1115
+ // account with no posts, which is a true empty rather than a failure.
1116
+ myPosts: {
1117
+ name: "myPosts",
1118
+ transport: "voyager-graphql",
1119
+ path: `${VOYAGER}/graphql`,
1120
+ queryId: "voyagerFeedDashProfileUpdates.20c70fe0314184158516a7ec004c0408",
1121
+ provenance: "verified",
1122
+ capturedAt: "2026-08-02"
1123
+ },
1124
+ // Discovered and returns 200, but the projection is useless: 39 KB containing
1125
+ // one `guideFetcher` wrapper and no name, tagline, description or headcount.
1126
+ // The same trap as the thin profile projection, so it stays unverified and
1127
+ // `company` does not ship. The richer path is probably
1128
+ // voyagerOrganizationDashViewWrapper with an organizationalPageUrn, which
1129
+ // first requires resolving that urn — unfinished work, not a dead end.
1130
+ company: {
1131
+ name: "company",
1132
+ transport: "voyager-graphql",
1133
+ path: `${VOYAGER}/graphql`,
1134
+ queryId: "voyagerOrganizationDashCompanies.148b1aebfadd0a455f32806df656c3c1",
1135
+ provenance: "discovered",
1136
+ capturedAt: "2026-08-02"
1137
+ },
1138
+ // A job CARDS list, not a job detail. Observed on /jobs/collections/recommended
1139
+ // and never exercised; `job` needs a detail endpoint we have not captured.
1140
+ jobCards: {
1141
+ name: "jobCards",
1142
+ transport: "voyager-graphql",
1143
+ path: `${VOYAGER}/graphql`,
1144
+ queryId: "voyagerJobsDashJobCards.e5b6b761ede078dabe8ad857aa42c220",
1145
+ provenance: "discovered",
1146
+ capturedAt: "2026-08-02"
1147
+ }
1148
+ };
1149
+ var RETIRED = {
1150
+ profileView: {
1151
+ path: `${VOYAGER}/identity/profiles/{id}/profileView`,
1152
+ diedBy: "2026-08-01",
1153
+ note: "Returns 410 Gone inside a well-formed Voyager envelope. Superseded by the `profile` contract above. Every client that reads profiles through this is broken."
1154
+ }
1155
+ };
1156
+ function shippableContracts() {
1157
+ return Object.fromEntries(
1158
+ Object.entries(CONTRACTS).filter(([, c]) => c.provenance === "verified")
1159
+ );
1160
+ }
1161
+ function contractFor(name) {
1162
+ return shippableContracts()[name];
1163
+ }
1164
+
1165
+ // src/engine/parse.ts
1166
+ var DROP_TYPE_FRAGMENTS = [
1167
+ "promoted",
1168
+ "sponsored",
1169
+ "adunit",
1170
+ "peopleyoumayknow",
1171
+ "recommendedentity",
1172
+ "discoveryentity",
1173
+ "discoverymodule",
1174
+ "promptcomponent",
1175
+ "carouselcomponent",
1176
+ "lego",
1177
+ // Search-result chrome, observed live alongside real results.
1178
+ "feedbackcard",
1179
+ "lazyloadedactions",
1180
+ "bannercard",
1181
+ "searchsuggestion",
1182
+ "keywordssuggestion",
1183
+ "queryclarification",
1184
+ "knowledgecard",
1185
+ "topicalquestion"
1186
+ ];
1187
+ var DECORATION_FRAGMENTS = [
1188
+ "socialdetail",
1189
+ "socialactivitycounts",
1190
+ "socialpermissions",
1191
+ "saveaction",
1192
+ "updateactions",
1193
+ "hidepostaction",
1194
+ "followinginfo",
1195
+ "miniprofile",
1196
+ "minicompany",
1197
+ "videoplaymetadata",
1198
+ "hidecommentaction",
1199
+ "followingstate",
1200
+ "followaction",
1201
+ "connectaction"
1202
+ ];
1203
+ function typeOf2(node) {
1204
+ const t = node.$type ?? node._type;
1205
+ return typeof t === "string" ? t : "";
1206
+ }
1207
+ function isPromotedPost(node) {
1208
+ const actor = node.actor;
1209
+ const sub = actor?.subDescription?.text;
1210
+ return typeof sub === "string" && /^promoted\b/i.test(sub.trim());
1211
+ }
1212
+ function isNoise(node) {
1213
+ if (isPromotedPost(node)) return true;
1214
+ const t = typeOf2(node).toLowerCase();
1215
+ if (t === "") return false;
1216
+ return DROP_TYPE_FRAGMENTS.some((f) => t.includes(f));
1217
+ }
1218
+ function isDecoration(node) {
1219
+ const t = typeOf2(node).toLowerCase();
1220
+ return DECORATION_FRAGMENTS.some((f) => t.includes(f));
1221
+ }
1222
+ var KNOWN_CONTENT = [
1223
+ "updatev2",
1224
+ "profile",
1225
+ "jobposting",
1226
+ "company",
1227
+ "comment",
1228
+ "reaction",
1229
+ "entityresult"
1230
+ ];
1231
+ function isKnown(node) {
1232
+ const t = typeOf2(node).toLowerCase();
1233
+ return KNOWN_CONTENT.some((f) => t.includes(f)) || isDecoration(node) || isNoise(node);
1234
+ }
1235
+ function indexIncluded(included) {
1236
+ const index = /* @__PURE__ */ new Map();
1237
+ if (!Array.isArray(included)) return index;
1238
+ for (const raw of included) {
1239
+ if (raw === null || typeof raw !== "object") continue;
1240
+ const node = raw;
1241
+ const urn = node.entityUrn;
1242
+ if (typeof urn !== "string") continue;
1243
+ const canonical = canonicalUrn(urn);
1244
+ index.set(canonical, node);
1245
+ if (canonical !== urn) index.set(urn, node);
1246
+ }
1247
+ return index;
1248
+ }
1249
+ function resolveRefs(refs, index) {
1250
+ const resolved = [];
1251
+ const unresolved = [];
1252
+ if (!Array.isArray(refs)) return { resolved, unresolved };
1253
+ for (const ref of refs) {
1254
+ if (typeof ref !== "string") continue;
1255
+ const node = index.get(ref) ?? index.get(canonicalUrn(ref));
1256
+ if (node === void 0) unresolved.push(ref);
1257
+ else resolved.push(node);
1258
+ }
1259
+ return { resolved, unresolved };
1260
+ }
1261
+ function findRefs(data) {
1262
+ if (data === null || typeof data !== "object") return [];
1263
+ const queue = [data];
1264
+ while (queue.length > 0) {
1265
+ const node = queue.shift();
1266
+ if (node === null || typeof node !== "object") continue;
1267
+ if (Array.isArray(node)) {
1268
+ queue.push(...node);
1269
+ continue;
1270
+ }
1271
+ for (const [key, value] of Object.entries(node)) {
1272
+ if (key.startsWith("*") && Array.isArray(value)) return value;
1273
+ }
1274
+ for (const value of Object.values(node)) {
1275
+ if (value !== null && typeof value === "object") queue.push(value);
1276
+ }
1277
+ }
1278
+ const refs = [];
1279
+ const walk = (node) => {
1280
+ if (node === null || typeof node !== "object") return;
1281
+ if (Array.isArray(node)) {
1282
+ for (const item of node) walk(item);
1283
+ return;
1284
+ }
1285
+ for (const [key, value] of Object.entries(node)) {
1286
+ if (key.startsWith("*") && typeof value === "string") refs.push(value);
1287
+ else walk(value);
1288
+ }
1289
+ };
1290
+ walk(data);
1291
+ return refs;
1292
+ }
1293
+ function parseSingle(payload) {
1294
+ const envelope = payload ?? {};
1295
+ const nodes = [...new Set(indexIncluded(envelope.included).values())];
1296
+ if (nodes.length === 0) return void 0;
1297
+ return nodes.find((n) => !isNoise(n) && !isDecoration(n)) ?? nodes[0];
1298
+ }
1299
+ function parseCollection(payload, opts) {
1300
+ const envelope = payload ?? {};
1301
+ const index = indexIncluded(envelope.included);
1302
+ const refs = findRefs(envelope.data);
1303
+ const { resolved, unresolved } = resolveRefs(refs, index);
1304
+ const items = [];
1305
+ const unknownTypes = /* @__PURE__ */ new Map();
1306
+ let excludedCount = 0;
1307
+ let unknownCount = 0;
1308
+ for (const node of resolved) {
1309
+ try {
1310
+ if (isNoise(node) || isDecoration(node)) {
1311
+ excludedCount++;
1312
+ continue;
1313
+ }
1314
+ if (!isKnown(node)) {
1315
+ const t = typeOf2(node);
1316
+ unknownTypes.set(t, (unknownTypes.get(t) ?? 0) + 1);
1317
+ unknownCount++;
1318
+ }
1319
+ items.push(node);
1320
+ } catch {
1321
+ excludedCount++;
1322
+ }
1323
+ }
1324
+ const warnings = [];
1325
+ if (unresolved.length > 0) {
1326
+ warnings.push(
1327
+ `${unresolved.length} referenced entities were not present in included[] \u2014 the decoration failed for those, so this record is incomplete rather than short.`
1328
+ );
1329
+ }
1330
+ if (opts.claimedCount !== void 0 && opts.claimedCount > 0 && items.length === 0) {
1331
+ warnings.push(
1332
+ `LinkedIn claims ${opts.claimedCount} items but returned none \u2014 treat this as a FAILED FETCH, not an empty result.`
1333
+ );
1334
+ }
1335
+ const state = unresolved.length > 0 ? "partial" : opts.truncated === true ? "unknown" : "complete";
1336
+ const meta = {
1337
+ state,
1338
+ operation: opts.operation,
1339
+ contractCapturedAt: opts.contractCapturedAt ?? "unknown",
1340
+ // parsedCount counts what we kept; `items` includes the unknowns, which is
1341
+ // why unknownCount is reported separately rather than added again here.
1342
+ rawCandidateCount: resolved.length,
1343
+ parsedCount: items.length - unknownCount,
1344
+ excludedCount,
1345
+ unknownCount,
1346
+ returnedCount: items.length,
1347
+ truncated: opts.truncated ?? false,
1348
+ warnings
1349
+ };
1350
+ if (opts.claimedCount !== void 0) meta.claimedCount = opts.claimedCount;
1351
+ if (unresolved.length > 0) meta.unresolved = unresolved;
1352
+ if (unknownTypes.size > 0) {
1353
+ meta.unknownTypes = [...unknownTypes.entries()].map(([type, count2]) => ({ type, count: count2 }));
1354
+ }
1355
+ return { items, meta };
1356
+ }
1357
+
1358
+ // src/engine/index.ts
1359
+ var RESULT_TYPE = {
1360
+ people: "PEOPLE",
1361
+ companies: "COMPANIES",
1362
+ jobs: "JOBS"
1363
+ };
1364
+ function missingContract(name) {
1365
+ return {
1366
+ ok: false,
1367
+ code: "NOT_IMPLEMENTED",
1368
+ message: `no verified contract for '${name}'`,
1369
+ hint: "Only endpoints that returned 200 on this machine may back a command. Capture it with `bun run scripts/observe.ts`, verify it, then mark it verified in src/engine/contracts.ts."
1370
+ };
1371
+ }
1372
+ function createEngine(session, deps, quiet = false) {
1373
+ const client = createClient(session, {
1374
+ fetch: globalThis.fetch,
1375
+ // stdout stays JSON-only; progress is human chatter and goes to stderr.
1376
+ progress: progressReporter(quiet),
1377
+ now: () => Date.now(),
1378
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
1379
+ random: () => Math.random(),
1380
+ loadLedger: () => {
1381
+ const r = loadJson(cachePath("budget.json"));
1382
+ return r.state === "ok" ? r.value : emptyLedger();
1383
+ },
1384
+ saveLedger: (l) => saveJson(cachePath("budget.json"), l),
1385
+ loadCooldown: () => {
1386
+ const r = loadJson(cachePath("cooldown.json"));
1387
+ return r.state === "ok" ? r.value : null;
1388
+ },
1389
+ saveCooldown: (c) => saveJson(cachePath("cooldown.json"), c),
1390
+ ...deps
1391
+ });
1392
+ return {
1393
+ async whoami() {
1394
+ const contract = contractFor("me");
1395
+ if (contract === void 0) return missingContract("me");
1396
+ const res = await client.request({
1397
+ url: contract.path,
1398
+ spendClass: "profile",
1399
+ operation: "me"
1400
+ });
1401
+ if (!res.ok) return res;
1402
+ return { ok: true, value: parseSingle(res.json) };
1403
+ },
1404
+ async profile(memberId) {
1405
+ const contract = contractFor("profile");
1406
+ if (contract === void 0) return missingContract("profile");
1407
+ const variables = encodeVariables({ memberIdentity: memberId });
1408
+ const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;
1409
+ const res = await client.request({ url, spendClass: "profile", operation: "profile" });
1410
+ if (!res.ok) return res;
1411
+ const envelope = res.json;
1412
+ const index = indexIncluded(envelope.included);
1413
+ const profile = [...new Set(index.values())].find(
1414
+ (n) => String(n.$type ?? "").endsWith("profile.Profile")
1415
+ );
1416
+ if (profile === void 0) return { ok: true, value: void 0 };
1417
+ return { ok: true, value: { profile, index } };
1418
+ },
1419
+ async feed(limit) {
1420
+ const contract = contractFor("feed");
1421
+ if (contract === void 0) return missingContract("feed");
1422
+ const url = `${contract.path}?q=chronFeed&count=${limit}&start=0`;
1423
+ const res = await client.request({ url, spendClass: "page", operation: "feed" });
1424
+ if (!res.ok) return res;
1425
+ const envelope = res.json;
1426
+ return {
1427
+ ok: true,
1428
+ value: {
1429
+ parsed: parseCollection(res.json, {
1430
+ operation: "feed",
1431
+ contractCapturedAt: contract.capturedAt
1432
+ }),
1433
+ index: indexIncluded(envelope.included)
1434
+ }
1435
+ };
1436
+ },
1437
+ async myPosts(profileUrn, limit) {
1438
+ const contract = contractFor("myPosts");
1439
+ if (contract === void 0) return missingContract("myPosts");
1440
+ const variables = encodeVariables({ count: Math.min(limit, 100), start: 0, profileUrn });
1441
+ const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;
1442
+ const res = await client.request({ url, spendClass: "page", operation: "myPosts" });
1443
+ if (!res.ok) return res;
1444
+ const envelope = res.json;
1445
+ return {
1446
+ ok: true,
1447
+ value: {
1448
+ parsed: parseCollection(res.json, {
1449
+ operation: "myPosts",
1450
+ contractCapturedAt: contract.capturedAt,
1451
+ truncated: true
1452
+ }),
1453
+ index: indexIncluded(envelope.included)
1454
+ }
1455
+ };
1456
+ },
1457
+ /**
1458
+ * Connections are a FILTERED PEOPLE SEARCH, not a list endpoint — LinkedIn
1459
+ * exposes no change stream for them. That is why the cache stores them as a
1460
+ * snapshot and diffs, rather than pretending a watermark exists.
1461
+ */
1462
+ async connections(limit) {
1463
+ const contract = contractFor("search");
1464
+ if (contract === void 0) return missingContract("search");
1465
+ const variables = encodeVariables({
1466
+ start: 0,
1467
+ origin: "FACETED_SEARCH",
1468
+ query: {
1469
+ flagshipSearchIntent: "SEARCH_SRP",
1470
+ queryParameters: [
1471
+ { key: "resultType", value: ["PEOPLE"] },
1472
+ { key: "network", value: ["F"] }
1473
+ ],
1474
+ includeFiltersInResponse: false
1475
+ }
1476
+ });
1477
+ const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;
1478
+ const res = await client.request({ url, spendClass: "search", operation: "connections" });
1479
+ if (!res.ok) return res;
1480
+ const parsed = parseCollection(res.json, {
1481
+ operation: "connections",
1482
+ contractCapturedAt: contract.capturedAt,
1483
+ claimedCount: totalResultCount(res.json),
1484
+ truncated: true
1485
+ });
1486
+ parsed.items = parsed.items.slice(0, limit);
1487
+ parsed.meta.returnedCount = parsed.items.length;
1488
+ const envelope = res.json;
1489
+ return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1490
+ },
1491
+ async post(postUrn, limit) {
1492
+ const contract = contractFor("comments");
1493
+ if (contract === void 0) return missingContract("comments");
1494
+ const variables = encodeVariables({
1495
+ count: Math.min(limit, 100),
1496
+ numReplies: 1,
1497
+ socialDetailUrn: socialDetailUrn(postUrn),
1498
+ sortOrder: "RELEVANCE",
1499
+ start: 0
1500
+ });
1501
+ const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;
1502
+ const res = await client.request({ url, spendClass: "page", operation: "comments" });
1503
+ if (!res.ok) return res;
1504
+ const parsed = parseCollection(res.json, {
1505
+ operation: "comments",
1506
+ contractCapturedAt: contract.capturedAt,
1507
+ // A page of many; we follow no cursor yet, so never claim exhaustion.
1508
+ truncated: true
1509
+ });
1510
+ const envelope = res.json;
1511
+ return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1512
+ },
1513
+ async reactions(postUrn, limit) {
1514
+ const contract = contractFor("reactions");
1515
+ if (contract === void 0) return missingContract("reactions");
1516
+ const variables = encodeVariables({
1517
+ count: Math.min(limit, 100),
1518
+ start: 0,
1519
+ threadUrn: postUrn
1520
+ });
1521
+ const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;
1522
+ const res = await client.request({ url, spendClass: "page", operation: "reactions" });
1523
+ if (!res.ok) return res;
1524
+ const parsed = parseCollection(res.json, {
1525
+ operation: "reactions",
1526
+ contractCapturedAt: contract.capturedAt,
1527
+ truncated: true
1528
+ });
1529
+ const envelope = res.json;
1530
+ return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1531
+ },
1532
+ async search(kind, query, limit) {
1533
+ const contract = contractFor("search");
1534
+ if (contract === void 0) return missingContract("search");
1535
+ const variables = encodeVariables({
1536
+ start: 0,
1537
+ origin: "GLOBAL_SEARCH_HEADER",
1538
+ query: {
1539
+ keywords: query,
1540
+ flagshipSearchIntent: "SEARCH_SRP",
1541
+ queryParameters: [{ key: "resultType", value: [RESULT_TYPE[kind]] }],
1542
+ includeFiltersInResponse: false
1543
+ }
1544
+ });
1545
+ const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;
1546
+ const res = await client.request({ url, spendClass: "search", operation: "search" });
1547
+ if (!res.ok) return res;
1548
+ const parsed = parseCollection(res.json, {
1549
+ operation: "search",
1550
+ contractCapturedAt: contract.capturedAt,
1551
+ claimedCount: totalResultCount(res.json),
1552
+ truncated: true
1553
+ // one page of many; we never claim exhaustion
1554
+ });
1555
+ parsed.items = parsed.items.slice(0, limit);
1556
+ parsed.meta.returnedCount = parsed.items.length;
1557
+ const envelope = res.json;
1558
+ return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1559
+ }
1560
+ };
1561
+ }
1562
+ function socialDetailUrn(postUrn) {
1563
+ return `urn:li:fsd_socialDetail:(${postUrn},${postUrn},urn:li:highlightedReply:-)`;
1564
+ }
1565
+ function totalResultCount(json) {
1566
+ const found = JSON.stringify(json ?? {}).match(/"totalResultCount":(\d+)/);
1567
+ return found?.[1] === void 0 ? void 0 : Number(found[1]);
1568
+ }
1569
+
1570
+ // src/engine/session.ts
1571
+ init_store();
1572
+ var SESSION_FILE = "session.json";
1573
+ function loadSession() {
1574
+ const result = loadJson(cachePath(SESSION_FILE));
1575
+ if (result.state === "ok") return { state: "ok", session: result.value };
1576
+ if (result.state === "missing") return { state: "missing" };
1577
+ return { state: "corrupt", quarantinedTo: result.quarantinedTo };
1578
+ }
1579
+ function saveSession(session) {
1580
+ saveJson(cachePath(SESSION_FILE), session);
1581
+ }
1582
+ var CDP = "http://127.0.0.1:9222";
1583
+ var LAUNCH_HINT = 'Start Chrome with remote debugging first, DETACHED so it survives:\n nohup /Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome \\\n --remote-debugging-port=9222 --user-data-dir="$HOME/.lnrelay/chrome" \\\n https://www.linkedin.com/feed/ >/dev/null 2>&1 & disown\nThen log into LinkedIn in that window and visit /feed/ once.';
1584
+ async function mintSessionFromBrowser() {
1585
+ let targets;
1586
+ let userAgent;
1587
+ try {
1588
+ targets = await (await fetch(`${CDP}/json/list`)).json();
1589
+ const version = await (await fetch(`${CDP}/json/version`)).json();
1590
+ userAgent = (version["User-Agent"] ?? "").replace("HeadlessChrome", "Chrome");
1591
+ } catch {
1592
+ return { ok: false, message: `no Chrome DevTools endpoint at ${CDP}`, hint: LAUNCH_HINT };
1593
+ }
1594
+ const page = targets.find((t) => t.type === "page" && t.webSocketDebuggerUrl !== void 0);
1595
+ if (page?.webSocketDebuggerUrl === void 0) {
1596
+ return { ok: false, message: "no debuggable Chrome page found", hint: LAUNCH_HINT };
1597
+ }
1598
+ if (userAgent === "") {
1599
+ return { ok: false, message: "Chrome did not report a User-Agent" };
1600
+ }
1601
+ let cookies;
1602
+ try {
1603
+ cookies = await getAllCookies(page.webSocketDebuggerUrl);
1604
+ } catch (e) {
1605
+ return { ok: false, message: `CDP failed: ${e.message}`, hint: LAUNCH_HINT };
1606
+ }
1607
+ const linkedin = cookies.filter((c) => c.domain.includes("linkedin.com"));
1608
+ const liAt = linkedin.find((c) => c.name === "li_at");
1609
+ const jsession = linkedin.find((c) => c.name === "JSESSIONID");
1610
+ if (liAt === void 0) {
1611
+ return {
1612
+ ok: false,
1613
+ message: "no li_at cookie \u2014 you are not logged in",
1614
+ hint: "Log into linkedin.com in the debug Chrome window, then re-run. Note that JSESSIONID alone is set pre-login and does not mean a session exists."
1615
+ };
1616
+ }
1617
+ if (jsession === void 0) {
1618
+ return {
1619
+ ok: false,
1620
+ message: "no JSESSIONID cookie",
1621
+ hint: "Visit https://www.linkedin.com/feed/ in the debug window \u2014 that navigation is what sets it."
1622
+ };
1623
+ }
1624
+ return {
1625
+ ok: true,
1626
+ session: {
1627
+ liAt: liAt.value,
1628
+ jsessionId: jsession.value,
1629
+ userAgent,
1630
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
1631
+ }
1632
+ };
1633
+ }
1634
+ function getAllCookies(wsUrl) {
1635
+ return new Promise((resolve, reject) => {
1636
+ const ws = new WebSocket(wsUrl);
1637
+ const timer = setTimeout(() => {
1638
+ ws.close();
1639
+ reject(new Error("timed out talking to Chrome"));
1640
+ }, 1e4);
1641
+ ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: "Network.getAllCookies" }));
1642
+ ws.onmessage = (ev) => {
1643
+ const msg = JSON.parse(String(ev.data));
1644
+ if (msg.id === 1 && msg.result !== void 0) {
1645
+ clearTimeout(timer);
1646
+ ws.close();
1647
+ resolve(msg.result.cookies);
1648
+ }
1649
+ };
1650
+ ws.onerror = () => {
1651
+ clearTimeout(timer);
1652
+ reject(new Error("websocket error"));
1653
+ };
1654
+ });
1655
+ }
1656
+
1657
+ // src/commands/live.ts
1658
+ function withSession(command, quiet = false) {
1659
+ const loaded = loadSession();
1660
+ if (loaded.state === "corrupt") {
1661
+ return err(
1662
+ command,
1663
+ "CACHE_CORRUPT",
1664
+ "the stored session was unreadable and has been quarantined",
1665
+ `Moved to ${loaded.quarantinedTo}. Re-run \`lnrelay login\`.`
1666
+ );
1667
+ }
1668
+ if (loaded.state === "missing") {
1669
+ return err(command, "AUTH_FAILED", "no session \u2014 run `lnrelay login` first", LAUNCH_HINT);
1670
+ }
1671
+ return { engine: createEngine(loaded.session, void 0, quiet) };
1672
+ }
1673
+ function toEnvelope(command, result) {
1674
+ return err(command, result.code, result.message, result.hint, void 0, result.retryAfterMs);
1675
+ }
1676
+ async function runLogin() {
1677
+ const minted = await mintSessionFromBrowser();
1678
+ if (!minted.ok) return err("login", "AUTH_FAILED", minted.message, minted.hint);
1679
+ saveSession(minted.session);
1680
+ return ok("login", {
1681
+ stored: true,
1682
+ liAtLength: minted.session.liAt.length,
1683
+ userAgent: minted.session.userAgent,
1684
+ capturedAt: minted.session.capturedAt,
1685
+ notice: "Session stored with owner-only permissions. This tool breaches LinkedIn User Agreement \xA78.2 and the account can be restricted or banned."
1686
+ });
1687
+ }
1688
+ async function runWhoami(raw = false) {
1689
+ const ctx = withSession("whoami");
1690
+ if ("ok" in ctx) return ctx;
1691
+ const result = await ctx.engine.whoami();
1692
+ if (!result.ok) return toEnvelope("whoami", result);
1693
+ if (result.value === void 0) {
1694
+ return err(
1695
+ "whoami",
1696
+ "SCHEMA_DRIFT",
1697
+ "LinkedIn returned no member entity",
1698
+ "re-capture the `me` contract"
1699
+ );
1700
+ }
1701
+ return ok(
1702
+ "whoami",
1703
+ raw ? { ...shapeEntity(result.value), raw: result.value } : shapeEntity(result.value)
1704
+ );
1705
+ }
1706
+ async function runProfile(memberId, raw = false) {
1707
+ if (memberId === void 0 || memberId === "") {
1708
+ return err(
1709
+ "profile",
1710
+ "INVALID_INPUT",
1711
+ "a member id or urn is required",
1712
+ "lnrelay profile <public-id|urn>"
1713
+ );
1714
+ }
1715
+ const ctx = withSession("profile");
1716
+ if ("ok" in ctx) return ctx;
1717
+ const result = await ctx.engine.profile(normaliseMemberId(memberId));
1718
+ if (!result.ok) return toEnvelope("profile", result);
1719
+ if (result.value === void 0) {
1720
+ return err("profile", "NOT_FOUND", `no profile for '${memberId}'`);
1721
+ }
1722
+ const shaped = shapeProfile(result.value.profile, result.value.index);
1723
+ return ok("profile", raw ? { ...shaped, raw: result.value.profile } : shaped);
1724
+ }
1725
+ async function runFeed(limit, opts = {}) {
1726
+ const ctx = withSession("feed", opts.quiet === true);
1727
+ if ("ok" in ctx) return ctx;
1728
+ const result = await ctx.engine.feed(limit);
1729
+ if (!result.ok) return toEnvelope("feed", result);
1730
+ return ok("feed", collection(result.value, opts));
1731
+ }
1732
+ async function runSearch(kind, query, limit, opts = {}) {
1733
+ if (kind === void 0 || !["people", "companies", "jobs"].includes(kind)) {
1734
+ return err(
1735
+ "search",
1736
+ "INVALID_INPUT",
1737
+ "kind must be people, companies or jobs",
1738
+ 'lnrelay search people "<query>"'
1739
+ );
1740
+ }
1741
+ if (query === void 0 || query === "") {
1742
+ return err("search", "INVALID_INPUT", "a query is required", 'lnrelay search people "<query>"');
1743
+ }
1744
+ const ctx = withSession("search", opts.quiet === true);
1745
+ if ("ok" in ctx) return ctx;
1746
+ const result = await ctx.engine.search(kind, query, limit);
1747
+ if (!result.ok) return toEnvelope("search", result);
1748
+ return ok("search", { query, kind, ...collection(result.value, opts) });
1749
+ }
1750
+ async function runPost(urn, limit, opts = {}) {
1751
+ const postUrn = normalisePostUrn(urn);
1752
+ if (postUrn === void 0) {
1753
+ return err(
1754
+ "post",
1755
+ "INVALID_INPUT",
1756
+ "a post urn or feed URL is required",
1757
+ "lnrelay post <activity-urn|https://www.linkedin.com/feed/update/...>"
1758
+ );
1759
+ }
1760
+ const ctx = withSession("post", opts.quiet === true);
1761
+ if ("ok" in ctx) return ctx;
1762
+ const result = await ctx.engine.post(postUrn, limit);
1763
+ if (!result.ok) return toEnvelope("post", result);
1764
+ return ok("post", { urn: postUrn, ...collection(result.value, opts) });
1765
+ }
1766
+ async function runReactions(urn, limit, opts = {}) {
1767
+ const postUrn = normalisePostUrn(urn);
1768
+ if (postUrn === void 0) {
1769
+ return err("reactions", "INVALID_INPUT", "a post urn or feed URL is required");
1770
+ }
1771
+ const ctx = withSession("reactions", opts.quiet === true);
1772
+ if ("ok" in ctx) return ctx;
1773
+ const result = await ctx.engine.reactions(postUrn, limit);
1774
+ if (!result.ok) return toEnvelope("reactions", result);
1775
+ return ok("reactions", { urn: postUrn, ...collection(result.value, opts) });
1776
+ }
1777
+ function normalisePostUrn(input) {
1778
+ if (input === void 0 || input === "") return void 0;
1779
+ const found = input.match(/urn:li:(?:activity|ugcPost|share):\d+/);
1780
+ if (found !== null) return found[0];
1781
+ return /^\d+$/.test(input) ? `urn:li:activity:${input}` : void 0;
1782
+ }
1783
+ function normaliseMemberId(input) {
1784
+ const fromUrl = input.match(/linkedin\.com\/in\/([^/?#]+)/);
1785
+ if (fromUrl?.[1] !== void 0) return fromUrl[1];
1786
+ const fromUrn = input.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/);
1787
+ if (fromUrn?.[1] !== void 0) return fromUrn[1];
1788
+ return input;
1789
+ }
1790
+ function collection(result, opts = {}) {
1791
+ const { parsed, index } = result;
1792
+ const shaped = shapeAll(parsed.items, index);
1793
+ const meta = { ...parsed.meta };
1794
+ if (opts.retain === true) meta.retained = retain("third-party", shaped);
1795
+ if (opts.raw === true) {
1796
+ return {
1797
+ items: parsed.items.map((node, i) => ({ ...shaped[i], raw: node })),
1798
+ meta
1799
+ };
1800
+ }
1801
+ if (opts.compact === true) return { items: compactRows(shaped), meta };
1802
+ if (opts.fields !== void 0 && opts.fields !== "") {
1803
+ return { items: project(shaped, opts.fields), meta };
1804
+ }
1805
+ return { items: shaped, meta };
1806
+ }
1807
+
1808
+ // src/commands/local.ts
1809
+ init_store();
1810
+ import { existsSync as existsSync2 } from "fs";
1811
+ import { version as nodeVersion } from "process";
1812
+ var LEDGER_FILE = "budget.json";
1813
+ var COOLDOWN_FILE = "cooldown.json";
1814
+ function loadState(file, fallback) {
1815
+ const path = cachePath(file);
1816
+ const result = loadJson(path);
1817
+ if (result.state === "ok") return { value: result.value, corrupt: null };
1818
+ if (result.state === "missing") return { value: fallback, corrupt: null };
1819
+ return {
1820
+ value: null,
1821
+ corrupt: { path, quarantinedTo: result.quarantinedTo, reason: result.reason }
1822
+ };
1823
+ }
1824
+ function loadLedger() {
1825
+ return loadState(LEDGER_FILE, emptyLedger());
1826
+ }
1827
+ function loadCooldown() {
1828
+ return loadState(COOLDOWN_FILE, null);
1829
+ }
1830
+ function runRisk(now) {
1831
+ const { value: cooldown, corrupt } = loadCooldown();
1832
+ if (corrupt !== null) {
1833
+ return err(
1834
+ "risk",
1835
+ "CACHE_CORRUPT",
1836
+ `cooldown state was unreadable and has been quarantined: ${corrupt.reason}`,
1837
+ `moved to ${corrupt.quarantinedTo}. Inspect it, then re-run \u2014 a fresh cooldown file will be created.`
1838
+ );
1839
+ }
1840
+ const blocked = activeCooldown(cooldown ?? null, now);
1841
+ return ok("risk", {
1842
+ state: blocked ? "blocked" : "ok",
1843
+ cooldown: cooldown ?? null,
1844
+ tosNotice: "Voyager reads breach LinkedIn User Agreement \xA78.2. This tool is not ToS-compliant and any account it touches can be restricted or permanently banned."
1845
+ });
1846
+ }
1847
+ function runBudget(now, resetCooldown, confirmed) {
1848
+ if (resetCooldown && !confirmed) {
1849
+ return err(
1850
+ "budget",
1851
+ "CONFIRMATION_REQUIRED",
1852
+ "clearing a cooldown requires --confirm",
1853
+ "A cooldown means LinkedIn signalled a throttle, block or challenge. Log in through a real browser and confirm you are unblocked before clearing it. Re-run with --confirm."
1854
+ );
1855
+ }
1856
+ if (resetCooldown) {
1857
+ saveJson(cachePath(COOLDOWN_FILE), null);
1858
+ }
1859
+ const { value: ledger2, corrupt } = loadLedger();
1860
+ if (corrupt !== null) {
1861
+ return err(
1862
+ "budget",
1863
+ "CACHE_CORRUPT",
1864
+ `the spend ledger was unreadable and has been quarantined: ${corrupt.reason}`,
1865
+ `moved to ${corrupt.quarantinedTo}. A corrupt ledger is NOT treated as an empty one \u2014 that would silently restore a full budget. Inspect it, then re-run.`
1866
+ );
1867
+ }
1868
+ const classes = ["profile", "search", "page", "write", "global"];
1869
+ const { value: cooldown } = loadCooldown();
1870
+ return ok("budget", {
1871
+ classes: classes.map((c) => ({
1872
+ ...summarise(ledger2 ?? emptyLedger(), c, now),
1873
+ note: CAPS[c].note
1874
+ })),
1875
+ cooldown: cooldown ?? null,
1876
+ caveat: "Every cap is guessed or transplanted vendor lore \u2014 the field research found no corroborated LinkedIn rate limits. These are starting knobs, not safe thresholds. They also cannot see your manual browser activity."
1877
+ });
1878
+ }
1879
+ function runDoctor(now, offline) {
1880
+ const checks = [];
1881
+ checks.push({
1882
+ name: "runtime",
1883
+ ok: true,
1884
+ detail: `node ${nodeVersion}; cache dir ${cacheDir()}${existsSync2(cacheDir()) ? "" : " (not created yet)"}`
1885
+ });
1886
+ const { value: cooldown, corrupt: cooldownCorrupt } = loadCooldown();
1887
+ if (cooldownCorrupt !== null) {
1888
+ checks.push({
1889
+ name: "cooldown",
1890
+ ok: false,
1891
+ detail: `state file was corrupt; quarantined to ${cooldownCorrupt.quarantinedTo}`
1892
+ });
1893
+ } else {
1894
+ const blocked = activeCooldown(cooldown ?? null, now);
1895
+ checks.push({
1896
+ name: "cooldown",
1897
+ ok: !blocked,
1898
+ detail: blocked ? `BLOCKED \u2014 ${cooldown?.reason}, clears by ${cooldown?.clearRequires}${cooldown?.until === null ? " (indefinite)" : ` at ${new Date(cooldown?.until ?? 0).toISOString()}`}` : "clear"
1899
+ });
1900
+ }
1901
+ const { value: ledger2, corrupt: ledgerCorrupt } = loadLedger();
1902
+ if (ledgerCorrupt !== null) {
1903
+ checks.push({
1904
+ name: "budget",
1905
+ ok: false,
1906
+ detail: `ledger was corrupt; quarantined to ${ledgerCorrupt.quarantinedTo}`
1907
+ });
1908
+ } else {
1909
+ const g = summarise(ledger2 ?? emptyLedger(), "global", now);
1910
+ checks.push({
1911
+ name: "budget",
1912
+ ok: g.remaining > 0,
1913
+ detail: `${g.spentInWindow}/${g.cap} global calls used in the last 24h (cap provenance: ${g.capProvenance})`
1914
+ });
1915
+ }
1916
+ const cookiePath = cachePath("cookies.json");
1917
+ checks.push({
1918
+ name: "session",
1919
+ ok: false,
1920
+ detail: existsSync2(cookiePath) ? "a cookie file exists, but the engine is not implemented yet (Phase 2)" : "no session yet \u2014 the Phase 0 capture gate has not been run. See docs/PLAN.md."
1921
+ });
1922
+ checks.push({
1923
+ name: "engine",
1924
+ ok: false,
1925
+ detail: "not implemented. Phase 0 (three human-paced requests from a residential IP) must pass before engine code is written \u2014 see docs/PLAN.md."
1926
+ });
1927
+ if (!offline) {
1928
+ checks.push({
1929
+ name: "live",
1930
+ ok: false,
1931
+ detail: "no live checks available yet; --offline is currently the only meaningful mode"
1932
+ });
1933
+ }
1934
+ return ok("doctor", {
1935
+ healthy: checks.every((c) => c.ok),
1936
+ phase: "Phase 1 \u2014 local scaffolding. No network capability exists yet, by design.",
1937
+ checks
1938
+ });
1939
+ }
1940
+
1941
+ // src/commands/registry.ts
1942
+ var COMMANDS = [
1943
+ // ─── local / meta — no network, available today ────────────────────────────
1944
+ {
1945
+ name: "doctor",
1946
+ cost: "free with --offline",
1947
+ summary: "Diagnose setup: entry point, cache dir, cookies, cooldown, budget.",
1948
+ usage: "lnrelay doctor [--offline]",
1949
+ audience: ["cli", "mcp"],
1950
+ risk: "local",
1951
+ implemented: true
1952
+ },
1953
+ {
1954
+ name: "budget",
1955
+ cost: "free",
1956
+ summary: "Spend ledger per class, with each cap's provenance. Reset a cooldown here.",
1957
+ usage: "lnrelay budget [--reset-cooldown --confirm]",
1958
+ audience: ["cli", "mcp"],
1959
+ risk: "local",
1960
+ implemented: true
1961
+ },
1962
+ {
1963
+ name: "risk",
1964
+ cost: "free",
1965
+ summary: "Circuit-breaker state. Check this BEFORE spending budget on research.",
1966
+ usage: "lnrelay risk",
1967
+ audience: ["cli", "mcp"],
1968
+ risk: "local",
1969
+ implemented: true
1970
+ },
1971
+ // ─── session ───────────────────────────────────────────────────────────────
1972
+ {
1973
+ name: "login",
1974
+ cost: "free \u2014 local browser",
1975
+ summary: "Mint a session from a logged-in Chrome via DevTools. Stores cookies owner-only.",
1976
+ usage: "lnrelay login\n Requires a Chrome started with remote debugging on port 9222 (see docs/PLAN.md).",
1977
+ audience: ["cli"],
1978
+ risk: "local",
1979
+ implemented: true
1980
+ },
1981
+ // ─── reads — verified live 2026-08-01 ─────────────────────────────────────
1982
+ {
1983
+ name: "whoami",
1984
+ cost: "1 call",
1985
+ summary: "The authenticated member: name, headline, URN.",
1986
+ usage: "lnrelay whoami",
1987
+ audience: ["cli", "mcp"],
1988
+ risk: "read",
1989
+ implemented: true
1990
+ },
1991
+ {
1992
+ name: "profile",
1993
+ cost: "1 call (+1 per section)",
1994
+ summary: "A member profile. Expensive sections are opt-in.",
1995
+ usage: "lnrelay profile <public-id|urn|url> [--raw]\n Returns headline, location, current title, company and school. LinkedIn's profile\n projections do not return a name \u2014 use the identifier you passed in.",
1996
+ audience: ["cli", "mcp"],
1997
+ risk: "read",
1998
+ implemented: true
1999
+ },
2000
+ {
2001
+ name: "search",
2002
+ cost: "cheap \u2014 the net",
2003
+ summary: "Search people, companies or jobs. Cast wide, then deep-read the finalists.",
2004
+ usage: 'lnrelay search people|companies|jobs "<query>" [--limit N]\n [--compact | --fields a,b,c] [--retain] [--raw]',
2005
+ audience: ["cli", "mcp"],
2006
+ risk: "read",
2007
+ implemented: true
2008
+ },
2009
+ {
2010
+ name: "post",
2011
+ cost: "expensive \u2014 full read",
2012
+ summary: "A post plus its comment thread, cursor-followed.",
2013
+ usage: "lnrelay post <activity-urn|url> [--limit N] [--compact | --fields a,b] [--retain]\n Check meta.returnedCount / claimedCount / state. claimedCount > 0 with\n returnedCount 0 is a FAILED FETCH, not an empty thread.",
2014
+ audience: ["cli", "mcp"],
2015
+ risk: "read",
2016
+ implemented: true
2017
+ },
2018
+ {
2019
+ name: "reactions",
2020
+ cost: "medium",
2021
+ summary: "Who reacted to a post, and with which reaction.",
2022
+ usage: "lnrelay reactions <activity-urn|url> [--limit N] [--compact | --fields a,b]",
2023
+ audience: ["cli", "mcp"],
2024
+ risk: "read",
2025
+ implemented: true
2026
+ },
2027
+ {
2028
+ name: "company",
2029
+ cost: "medium",
2030
+ summary: "A company page, optionally with a bounded sample of its updates.",
2031
+ usage: "lnrelay company <universal-name|url> [--updates N]",
2032
+ audience: ["cli", "mcp"],
2033
+ risk: "read",
2034
+ implemented: false
2035
+ },
2036
+ {
2037
+ name: "job",
2038
+ cost: "1 call",
2039
+ summary: "A job posting detail.",
2040
+ usage: "lnrelay job <job-id|url>",
2041
+ audience: ["cli", "mcp"],
2042
+ risk: "read",
2043
+ implemented: false
2044
+ },
2045
+ {
2046
+ name: "feed",
2047
+ cost: "medium",
2048
+ summary: "Your own chronological feed.",
2049
+ usage: "lnrelay feed [--limit N] [--compact | --fields a,b,c] [--retain] [--raw]",
2050
+ audience: ["cli", "mcp"],
2051
+ risk: "read",
2052
+ implemented: true
2053
+ },
2054
+ // ─── cache-backed — Phase 4 ────────────────────────────────────────────────
2055
+ {
2056
+ name: "sync",
2057
+ cost: "medium \u2014 1-2 calls",
2058
+ summary: "Pull your own posts or connections into the local cache for offline search.",
2059
+ usage: "lnrelay sync my-posts|connections [--limit N] [--force]",
2060
+ audience: ["cli"],
2061
+ risk: "read",
2062
+ implemented: true
2063
+ },
2064
+ {
2065
+ name: "connections",
2066
+ cost: "free \u2014 local cache",
2067
+ summary: "Your connections, from the local cache. Fill it with `sync connections`.",
2068
+ usage: 'lnrelay connections [-q "<query>"] [--limit N] [--compact | --fields a,b] # free; cache',
2069
+ audience: ["cli", "mcp"],
2070
+ risk: "read",
2071
+ implemented: true
2072
+ },
2073
+ {
2074
+ name: "my-posts",
2075
+ cost: "free \u2014 local cache",
2076
+ summary: "Your own authored posts, from the local cache. Fill it with `sync my-posts`.",
2077
+ usage: 'lnrelay my-posts [-q "<query>"] [--limit N] [--compact | --fields a,b] # free; cache',
2078
+ audience: ["cli", "mcp"],
2079
+ risk: "read",
2080
+ implemented: true
2081
+ },
2082
+ {
2083
+ name: "local",
2084
+ cost: "free \u2014 local cache",
2085
+ summary: "Offline search across everything synced. The default research path after a sync.",
2086
+ usage: 'lnrelay local "<query>" [--source connections,my-posts,third-party] [--since YYYY-MM-DD]\n [--limit N] [--compact | --fields a,b,c]',
2087
+ audience: ["cli", "mcp"],
2088
+ risk: "read",
2089
+ implemented: true
2090
+ },
2091
+ {
2092
+ name: "cache-status",
2093
+ cost: "free \u2014 local cache",
2094
+ summary: "What is cached, per source, with sync checkpoints and the retention policy.",
2095
+ usage: "lnrelay cache-status",
2096
+ audience: ["cli", "mcp"],
2097
+ risk: "local",
2098
+ implemented: true
2099
+ },
2100
+ {
2101
+ name: "purge",
2102
+ cost: "free",
2103
+ summary: "Delete cached data. Never contacts LinkedIn.",
2104
+ usage: "lnrelay purge [--all] --confirm # default scope: third-party only",
2105
+ audience: ["cli"],
2106
+ risk: "local",
2107
+ implemented: true
2108
+ },
2109
+ // ─── writes — Phase 6, official OAuth only, never MCP ──────────────────────
2110
+ {
2111
+ name: "oauth",
2112
+ cost: "free",
2113
+ summary: "OAuth token status for writes. Never prints the token.",
2114
+ usage: "lnrelay oauth",
2115
+ audience: ["cli"],
2116
+ risk: "local",
2117
+ implemented: true
2118
+ },
2119
+ {
2120
+ name: "share",
2121
+ cost: "1 call \u2014 write",
2122
+ summary: "Post to your own feed via LinkedIn's official OAuth scope.",
2123
+ usage: 'lnrelay share "<text>" [--visibility public|connections]\n Stops and asks at an interactive terminal. No TTY = no write, and no network call.',
2124
+ audience: ["cli"],
2125
+ risk: "write",
2126
+ implemented: true
2127
+ },
2128
+ {
2129
+ name: "comment",
2130
+ cost: "1 call \u2014 write",
2131
+ summary: "Comment on a post via the official OAuth scope.",
2132
+ usage: 'lnrelay comment <activity-urn> "<text>"',
2133
+ audience: ["cli"],
2134
+ risk: "write",
2135
+ implemented: true
2136
+ },
2137
+ {
2138
+ name: "react",
2139
+ cost: "1 call \u2014 write",
2140
+ summary: "React to a post via the official OAuth scope. Reversible.",
2141
+ usage: "lnrelay react <activity-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION]",
2142
+ audience: ["cli"],
2143
+ risk: "write",
2144
+ implemented: true
2145
+ }
2146
+ ];
2147
+ var commandNames = COMMANDS.map((c) => c.name);
2148
+ function findCommand(name) {
2149
+ return COMMANDS.find((c) => c.name === name);
2150
+ }
2151
+ function helpText() {
2152
+ const lines = ["lnrelay \u2014 deep research over LinkedIn from your own account", "", "Commands:"];
2153
+ const width = Math.max(...commandNames.map((n) => n.length));
2154
+ for (const c of COMMANDS) {
2155
+ const flag = c.implemented ? " " : "\xB7";
2156
+ lines.push(` ${flag} ${c.name.padEnd(width)} ${c.summary} [${c.cost}]`);
2157
+ }
2158
+ lines.push("", " \xB7 = specified in docs/DESIGN.md, not yet implemented");
2159
+ lines.push("", "Run `lnrelay <command> --help` for usage.");
2160
+ return lines.join("\n");
2161
+ }
2162
+
2163
+ // src/commands/sync.ts
2164
+ init_db();
2165
+ var CONNECTIONS_MIN_INTERVAL_MS = 7 * 864e5;
2166
+ function searchText(item) {
2167
+ return [item.name, item.headline, item.location, item.text, item.author, item.company, item.title].filter((v) => typeof v === "string").join(" ");
2168
+ }
2169
+ function rowsFrom(items) {
2170
+ return items.filter((i) => typeof i.urn === "string" && i.urn !== "").map((i) => ({ urn: i.urn, body: i, text: searchText(i) }));
2171
+ }
2172
+ function diffSnapshot(before, seen, claimed) {
2173
+ const complete = claimed === void 0 || seen.size >= claimed;
2174
+ if (!complete) return { removed: [], complete: false };
2175
+ return { removed: [...before].filter((urn) => !seen.has(urn)), complete: true };
2176
+ }
2177
+ async function runSync(source, limit, force, now = Date.now()) {
2178
+ if (source !== "my-posts" && source !== "connections") {
2179
+ return err(
2180
+ "sync",
2181
+ "INVALID_INPUT",
2182
+ `unknown sync source '${source ?? ""}'`,
2183
+ "lnrelay sync my-posts | lnrelay sync connections"
2184
+ );
2185
+ }
2186
+ const session = loadSession();
2187
+ if (session.state === "corrupt") {
2188
+ return err("sync", "CACHE_CORRUPT", "the stored session was unreadable", LAUNCH_HINT);
2189
+ }
2190
+ if (session.state === "missing") {
2191
+ return err("sync", "AUTH_FAILED", "no session \u2014 run `lnrelay login` first", LAUNCH_HINT);
2192
+ }
2193
+ const engine = createEngine(session.session);
2194
+ try {
2195
+ const db = openDb(now);
2196
+ if (source === "my-posts") {
2197
+ const me = await engine.whoami();
2198
+ if (!me.ok) return err("sync", me.code, me.message, me.hint);
2199
+ const profileUrn = typeof me.value?.entityUrn === "string" ? me.value.entityUrn : void 0;
2200
+ if (profileUrn === void 0) {
2201
+ return err("sync", "SCHEMA_DRIFT", "could not determine the owner profile urn");
2202
+ }
2203
+ const result2 = await engine.myPosts(profileUrn, limit);
2204
+ if (!result2.ok) return err("sync", result2.code, result2.message, result2.hint);
2205
+ const items2 = shapeAll(result2.value.parsed.items, result2.value.index);
2206
+ const rows2 = rowsFrom(items2);
2207
+ const stored2 = upsert(db, "my-posts", rows2, now);
2208
+ setCheckpoint(db, {
2209
+ source: "my-posts",
2210
+ lastSuccessfulAt: now,
2211
+ newestCreatedAt: null,
2212
+ headIds: rows2.slice(0, 5).map((r) => r.urn),
2213
+ state: "ok"
2214
+ });
2215
+ return ok("sync", {
2216
+ source,
2217
+ ...stored2,
2218
+ meta: result2.value.parsed.meta,
2219
+ note: rows2.length === 0 ? "LinkedIn returned no posts for this account. That is a genuine empty, not a failed fetch \u2014 meta.state says which." : void 0
2220
+ });
2221
+ }
2222
+ const before = urnsFor(db, "connections");
2223
+ const existing = before.size;
2224
+ if (!force && existing > 0) {
2225
+ const { getCheckpoint: getCheckpoint2 } = await Promise.resolve().then(() => (init_db(), db_exports));
2226
+ const cp = getCheckpoint2(db, "connections");
2227
+ const age = cp === void 0 ? Number.POSITIVE_INFINITY : now - cp.lastSuccessfulAt;
2228
+ if (age < CONNECTIONS_MIN_INTERVAL_MS) {
2229
+ const days = Math.ceil((CONNECTIONS_MIN_INTERVAL_MS - age) / 864e5);
2230
+ return err(
2231
+ "sync",
2232
+ "BUDGET_EXHAUSTED",
2233
+ `connections were synced ${Math.floor(age / 864e5)} days ago`,
2234
+ `This is the most expensive read in the tool and connections change slowly. Wait ${days} more day(s), or pass --force.`
2235
+ );
2236
+ }
2237
+ }
2238
+ const result = await engine.connections(limit);
2239
+ if (!result.ok) return err("sync", result.code, result.message, result.hint);
2240
+ const items = shapeAll(result.value.parsed.items, result.value.index);
2241
+ const rows = rowsFrom(items);
2242
+ const stored = upsert(db, "connections", rows, now);
2243
+ const claimed = result.value.parsed.meta.claimedCount;
2244
+ const seen = new Set(rows.map((r) => r.urn));
2245
+ const { removed, complete } = diffSnapshot(before, seen, claimed);
2246
+ if (removed.length > 0) removeUrns(db, "connections", removed);
2247
+ setCheckpoint(db, {
2248
+ source: "connections",
2249
+ lastSuccessfulAt: now,
2250
+ newestCreatedAt: null,
2251
+ headIds: [],
2252
+ // Honest: a snapshot, never a watermark.
2253
+ state: complete ? "ok" : "snapshot-partial"
2254
+ });
2255
+ return ok("sync", {
2256
+ source,
2257
+ added: stored.added,
2258
+ updated: stored.updated,
2259
+ removed: removed.length,
2260
+ claimed,
2261
+ complete,
2262
+ meta: result.value.parsed.meta,
2263
+ note: complete ? void 0 : `Only ${rows.length} of ${claimed} connections were retrieved, so removals could not be determined and none were applied. Raise --limit to complete the snapshot.`
2264
+ });
2265
+ } catch (e) {
2266
+ if (e instanceof CacheCorrupt) {
2267
+ return err(
2268
+ "sync",
2269
+ "CACHE_CORRUPT",
2270
+ e.message,
2271
+ `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as empty \u2014 that would make this sync re-enumerate everything. Inspect it, then re-run.`
2272
+ );
2273
+ }
2274
+ throw e;
2275
+ }
2276
+ }
2277
+
2278
+ // src/commands/write.ts
2279
+ init_store();
2280
+ import { createInterface } from "readline/promises";
2281
+
2282
+ // src/engine/oauth-write.ts
2283
+ var API = "https://api.linkedin.com";
2284
+ function headers(token) {
2285
+ return {
2286
+ authorization: `Bearer ${token.accessToken}`,
2287
+ "content-type": "application/json",
2288
+ "x-restli-protocol-version": "2.0.0",
2289
+ "linkedin-version": "202601"
2290
+ };
2291
+ }
2292
+ function expired(token, now) {
2293
+ return token.expiresAt <= now;
2294
+ }
2295
+ async function send(url, body, token, deps) {
2296
+ if (expired(token, deps.now())) {
2297
+ return {
2298
+ ok: false,
2299
+ code: "AUTH_FAILED",
2300
+ message: "the OAuth token has expired",
2301
+ hint: "Run `lnrelay oauth` to obtain a fresh token."
2302
+ };
2303
+ }
2304
+ let res;
2305
+ try {
2306
+ res = await deps.fetch(url, {
2307
+ method: "POST",
2308
+ headers: headers(token),
2309
+ body: JSON.stringify(body)
2310
+ });
2311
+ } catch (e) {
2312
+ return { ok: false, code: "FETCH_FAILED", message: e.message };
2313
+ }
2314
+ const text2 = await res.text();
2315
+ if (res.status === 201 || res.status === 200) {
2316
+ const id = res.headers.get("x-restli-id") ?? extractId(text2);
2317
+ return {
2318
+ ok: true,
2319
+ id: id ?? "(unknown)",
2320
+ ...id === null ? {} : { url: `https://www.linkedin.com/feed/update/${id}/` }
2321
+ };
2322
+ }
2323
+ if (res.status === 429) {
2324
+ return {
2325
+ ok: false,
2326
+ code: "RATE_LIMITED",
2327
+ message: "LinkedIn throttled the write",
2328
+ hint: "Not retried automatically. Wait, and check `lnrelay budget`."
2329
+ };
2330
+ }
2331
+ if (res.status === 401 || res.status === 403) {
2332
+ return {
2333
+ ok: false,
2334
+ code: "AUTH_FAILED",
2335
+ message: `LinkedIn rejected the token (${res.status})`,
2336
+ hint: 'The scope may not be granted. Check the app has "Share on LinkedIn" added.'
2337
+ };
2338
+ }
2339
+ return {
2340
+ ok: false,
2341
+ code: "FETCH_FAILED",
2342
+ message: `write failed (${res.status})`,
2343
+ hint: text2.slice(0, 300)
2344
+ };
2345
+ }
2346
+ function extractId(body) {
2347
+ return body.match(/"id"\s*:\s*"([^"]+)"/)?.[1] ?? null;
2348
+ }
2349
+ function share(confirmed, token, deps) {
2350
+ return send(
2351
+ `${API}/rest/posts`,
2352
+ {
2353
+ author: token.memberUrn,
2354
+ commentary: confirmed.payload.text,
2355
+ visibility: confirmed.payload.visibility,
2356
+ distribution: {
2357
+ feedDistribution: "MAIN_FEED",
2358
+ targetEntities: [],
2359
+ thirdPartyDistributionChannels: []
2360
+ },
2361
+ lifecycleState: "PUBLISHED",
2362
+ isReshareDisabledByAuthor: false
2363
+ },
2364
+ token,
2365
+ deps
2366
+ );
2367
+ }
2368
+ function comment(confirmed, token, deps) {
2369
+ const encoded = encodeURIComponent(confirmed.payload.postUrn);
2370
+ return send(
2371
+ `${API}/rest/socialActions/${encoded}/comments`,
2372
+ {
2373
+ actor: token.memberUrn,
2374
+ object: confirmed.payload.postUrn,
2375
+ message: { text: confirmed.payload.text }
2376
+ },
2377
+ token,
2378
+ deps
2379
+ );
2380
+ }
2381
+ function react(confirmed, token, deps) {
2382
+ return send(
2383
+ `${API}/rest/reactions?actor=${encodeURIComponent(token.memberUrn)}`,
2384
+ { root: confirmed.payload.postUrn, reactionType: confirmed.payload.type },
2385
+ token,
2386
+ deps
2387
+ );
2388
+ }
2389
+
2390
+ // src/commands/confirm.ts
2391
+ import { createHash } from "crypto";
2392
+ function confirmToken(action, payload) {
2393
+ return createHash("sha256").update(`${action}:${JSON.stringify(payload)}`).digest("hex").slice(0, 4);
2394
+ }
2395
+ function renderPlan(plan, budgetLine2) {
2396
+ const token = confirmToken(plan.action, plan.payload);
2397
+ const lines = [
2398
+ "",
2399
+ ` ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,
2400
+ ` ${"\u2500".repeat(58)}`,
2401
+ ...plan.summary.map((l) => ` ${l}`),
2402
+ ` via ${plan.transport === "oauth" ? "official OAuth (w_member_social)" : "Voyager (private API)"}`,
2403
+ ` undo ${plan.reversibility}`,
2404
+ "",
2405
+ " This automation breaches LinkedIn User Agreement \xA78.2 and can",
2406
+ " permanently restrict this account.",
2407
+ ` ${budgetLine2}`,
2408
+ "",
2409
+ ` Type ${token} to confirm, anything else to abort: `
2410
+ ];
2411
+ return lines.join("\n");
2412
+ }
2413
+ async function confirmWrite(plan, budgetLine2, deps) {
2414
+ if (!deps.isTty) {
2415
+ return {
2416
+ ok: false,
2417
+ code: "CONFIRMATION_REQUIRED",
2418
+ message: `'${plan.action}' needs a human to confirm it at an interactive terminal`,
2419
+ hint: "No terminal is attached, so nothing was sent and no network call was made. Run this command yourself in a shell. There is deliberately no --yes flag: an agent that could set one would not be confirming anything."
2420
+ };
2421
+ }
2422
+ const token = confirmToken(plan.action, plan.payload);
2423
+ const answer = (await deps.prompt(renderPlan(plan, budgetLine2))).trim();
2424
+ if (answer !== token) {
2425
+ return {
2426
+ ok: false,
2427
+ code: "CONFIRMATION_REQUIRED",
2428
+ message: "aborted \u2014 the confirmation token did not match",
2429
+ hint: "Nothing was sent. Re-run and type the token shown in the prompt."
2430
+ };
2431
+ }
2432
+ return {
2433
+ ok: true,
2434
+ confirmed: { action: plan.action, payload: plan.payload, token }
2435
+ };
2436
+ }
2437
+
2438
+ // src/commands/write.ts
2439
+ var TOKEN_FILE = "oauth.json";
2440
+ var OAUTH_SETUP = [
2441
+ "No OAuth token stored. Writes go over LinkedIn's OWN self-serve scope rather than the private",
2442
+ "API, which is the one legitimacy wedge an individual actually has \u2014 but the app has to be",
2443
+ "registered by you; it cannot be created on your behalf.",
2444
+ "",
2445
+ " 1. https://www.linkedin.com/developers/apps/new \u2014 create an app (any LinkedIn Page works).",
2446
+ ' 2. Products tab \u2192 add "Sign In with LinkedIn using OpenID Connect" AND "Share on LinkedIn".',
2447
+ " Both are self-serve: no partner review, no verification, no screencast.",
2448
+ " 3. Auth tab \u2192 add redirect URL http://localhost:53682/callback",
2449
+ " 4. Run: lnrelay oauth --client-id <id> --client-secret <secret>"
2450
+ ].join("\n");
2451
+ function loadToken() {
2452
+ const result = loadJson(cachePath(TOKEN_FILE));
2453
+ return result.state === "ok" ? result.value : null;
2454
+ }
2455
+ function ledger() {
2456
+ const result = loadJson(cachePath("budget.json"));
2457
+ return result.state === "ok" ? result.value : emptyLedger();
2458
+ }
2459
+ function budgetLine(now) {
2460
+ const s = summarise(ledger(), "write", now);
2461
+ return `${s.remaining} of ${s.cap} writes left today.`;
2462
+ }
2463
+ function terminalDeps() {
2464
+ return {
2465
+ isTty: process.stdin.isTTY === true && process.stdout.isTTY === true,
2466
+ prompt: async (question) => {
2467
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
2468
+ const answer = await rl.question(question);
2469
+ rl.close();
2470
+ return answer;
2471
+ },
2472
+ write: (s) => process.stderr.write(s)
2473
+ };
2474
+ }
2475
+ function prepare(command, now) {
2476
+ const token = loadToken();
2477
+ if (token === null) {
2478
+ return err(command, "AUTH_FAILED", "no OAuth token \u2014 writes need one", OAUTH_SETUP);
2479
+ }
2480
+ const attempt = spend(ledger(), "write", now);
2481
+ if ("error" in attempt) {
2482
+ return err(command, attempt.error.code, attempt.error.message, attempt.error.hint);
2483
+ }
2484
+ return { token, now };
2485
+ }
2486
+ async function gate(command, plan, ctx, deps) {
2487
+ const outcome = await confirmWrite(plan, budgetLine(ctx.now), deps);
2488
+ if (!outcome.ok) return err(command, outcome.code, outcome.message, outcome.hint);
2489
+ const attempt = spend(ledger(), "write", ctx.now);
2490
+ if ("permit" in attempt) saveJson(cachePath("budget.json"), attempt.ledger);
2491
+ return { confirmed: outcome.confirmed };
2492
+ }
2493
+ async function runShare(text2, visibility, now = Date.now(), deps = terminalDeps()) {
2494
+ if (text2 === void 0 || text2.trim() === "") {
2495
+ return err("share", "INVALID_INPUT", "text is required", 'lnrelay share "<text>"');
2496
+ }
2497
+ const vis = visibility === "connections" ? "CONNECTIONS" : "PUBLIC";
2498
+ const ctx = prepare("share", now);
2499
+ if ("ok" in ctx) return ctx;
2500
+ const plan = {
2501
+ action: "post to your feed",
2502
+ payload: { text: text2, visibility: vis },
2503
+ summary: [`as ${ctx.token.memberUrn}`, `content "${text2}"`, `audience ${vis}`],
2504
+ reversibility: "deletable from the LinkedIn UI; the post may be seen first",
2505
+ transport: "oauth"
2506
+ };
2507
+ const gated = await gate("share", plan, ctx, deps);
2508
+ if ("ok" in gated) return gated;
2509
+ const result = await share(gated.confirmed, ctx.token, {
2510
+ fetch: globalThis.fetch,
2511
+ now: () => now
2512
+ });
2513
+ return result.ok ? ok("share", { id: result.id, url: result.url }) : err("share", result.code, result.message, result.hint);
2514
+ }
2515
+ async function runComment(postUrn, text2, now = Date.now(), deps = terminalDeps()) {
2516
+ if (postUrn === void 0 || text2 === void 0 || text2.trim() === "") {
2517
+ return err(
2518
+ "comment",
2519
+ "INVALID_INPUT",
2520
+ "a post urn and text are required",
2521
+ 'lnrelay comment <urn> "<text>"'
2522
+ );
2523
+ }
2524
+ const ctx = prepare("comment", now);
2525
+ if ("ok" in ctx) return ctx;
2526
+ const plan = {
2527
+ action: "comment on a post",
2528
+ payload: { postUrn, text: text2 },
2529
+ summary: [`as ${ctx.token.memberUrn}`, `on ${postUrn}`, `content "${text2}"`],
2530
+ reversibility: "deletable from the LinkedIn UI; the author is notified immediately",
2531
+ transport: "oauth"
2532
+ };
2533
+ const gated = await gate("comment", plan, ctx, deps);
2534
+ if ("ok" in gated) return gated;
2535
+ const result = await comment(gated.confirmed, ctx.token, {
2536
+ fetch: globalThis.fetch,
2537
+ now: () => now
2538
+ });
2539
+ return result.ok ? ok("comment", { id: result.id }) : err("comment", result.code, result.message, result.hint);
2540
+ }
2541
+ var REACTIONS = ["LIKE", "PRAISE", "EMPATHY", "INTEREST", "APPRECIATION", "ENTERTAINMENT"];
2542
+ async function runReact(postUrn, type, now = Date.now(), deps = terminalDeps()) {
2543
+ const reaction = type.toUpperCase();
2544
+ if (postUrn === void 0) {
2545
+ return err(
2546
+ "react",
2547
+ "INVALID_INPUT",
2548
+ "a post urn is required",
2549
+ "lnrelay react <urn> [--type LIKE]"
2550
+ );
2551
+ }
2552
+ if (!REACTIONS.includes(reaction)) {
2553
+ return err(
2554
+ "react",
2555
+ "INVALID_INPUT",
2556
+ `unknown reaction '${type}'`,
2557
+ `one of: ${REACTIONS.join(", ")}`
2558
+ );
2559
+ }
2560
+ const ctx = prepare("react", now);
2561
+ if ("ok" in ctx) return ctx;
2562
+ const plan = {
2563
+ action: "react to a post",
2564
+ payload: { postUrn, type: reaction },
2565
+ summary: [`as ${ctx.token.memberUrn}`, `on ${postUrn}`, `reaction ${reaction}`],
2566
+ reversibility: "removable from the LinkedIn UI; the author is notified immediately",
2567
+ transport: "oauth"
2568
+ };
2569
+ const gated = await gate("react", plan, ctx, deps);
2570
+ if ("ok" in gated) return gated;
2571
+ const result = await react(gated.confirmed, ctx.token, {
2572
+ fetch: globalThis.fetch,
2573
+ now: () => now
2574
+ });
2575
+ return result.ok ? ok("react", { id: result.id }) : err("react", result.code, result.message, result.hint);
2576
+ }
2577
+ function runOauthStatus() {
2578
+ const token = loadToken();
2579
+ if (token === null) return err("oauth", "AUTH_FAILED", "no OAuth token stored", OAUTH_SETUP);
2580
+ return ok("oauth", {
2581
+ memberUrn: token.memberUrn,
2582
+ expiresAt: new Date(token.expiresAt).toISOString(),
2583
+ expired: token.expiresAt <= Date.now(),
2584
+ scope: "w_member_social",
2585
+ writeCap: CAPS.write.perDay
2586
+ });
2587
+ }
2588
+
2589
+ // src/entry.ts
2590
+ import { realpathSync } from "fs";
2591
+ import { basename } from "path";
2592
+ import { fileURLToPath } from "url";
2593
+ function isMainModule(argv1, moduleUrl, importMetaMain) {
2594
+ if (importMetaMain === true) return true;
2595
+ if (importMetaMain === false) return false;
2596
+ if (argv1 === void 0) return false;
2597
+ const modulePath = fileURLToPath(moduleUrl);
2598
+ try {
2599
+ return realpathSync(argv1) === realpathSync(modulePath);
2600
+ } catch {
2601
+ return argv1 === modulePath;
2602
+ }
2603
+ }
2604
+ function shouldForceEntry(argv1, binNames) {
2605
+ if (argv1 === void 0) return false;
2606
+ return binNames.includes(basename(argv1));
2607
+ }
2608
+ function shouldRunAsEntry(argv1, moduleUrl, importMetaMain, binNames) {
2609
+ if (isMainModule(argv1, moduleUrl, importMetaMain)) {
2610
+ return { run: true, warning: void 0 };
2611
+ }
2612
+ if (importMetaMain === void 0 && shouldForceEntry(argv1, binNames)) {
2613
+ return {
2614
+ run: true,
2615
+ warning: `${binNames[0]}: entry detection failed \u2014 treating as main; report at github.com/gabros20/linkedin-relay/issues`
2616
+ };
2617
+ }
2618
+ return { run: false, warning: void 0 };
2619
+ }
2620
+
2621
+ // src/cli.ts
2622
+ function output(args) {
2623
+ const opts = {};
2624
+ if (bool(args, "raw")) opts.raw = true;
2625
+ if (bool(args, "quiet")) opts.quiet = true;
2626
+ if (bool(args, "retain")) opts.retain = true;
2627
+ if (bool(args, "compact")) opts.compact = true;
2628
+ const fields = str(args, "fields");
2629
+ if (fields !== void 0) opts.fields = fields;
2630
+ return opts;
2631
+ }
2632
+ async function dispatch(argv, now) {
2633
+ const args = parseArgs(argv);
2634
+ const { command } = args;
2635
+ if (command === void 0 || command === "help" || command === "--help") {
2636
+ process.stderr.write(`${helpText()}
2637
+ `);
2638
+ return { ok: true, command: "help", data: { commands: helpText() } };
2639
+ }
2640
+ const def = findCommand(command);
2641
+ if (def === void 0) {
2642
+ return err(
2643
+ command,
2644
+ "UNKNOWN_COMMAND",
2645
+ `unknown command '${command}'`,
2646
+ "run `lnrelay help` to list commands"
2647
+ );
2648
+ }
2649
+ if (!def.implemented) {
2650
+ return err(
2651
+ command,
2652
+ "NOT_IMPLEMENTED",
2653
+ `'${command}' is specified but not yet built`,
2654
+ `Usage when it lands: ${def.usage.split("\n")[0]}. See docs/PLAN.md for the phase it belongs to.`
2655
+ );
2656
+ }
2657
+ switch (command) {
2658
+ case "doctor":
2659
+ return runDoctor(now, bool(args, "offline"));
2660
+ case "budget":
2661
+ return runBudget(now, bool(args, "reset-cooldown"), bool(args, "confirm"));
2662
+ case "risk":
2663
+ return runRisk(now);
2664
+ case "local":
2665
+ return runLocal(
2666
+ args.positionals[0],
2667
+ str(args, "source"),
2668
+ str(args, "since"),
2669
+ num(args, "limit") ?? 25,
2670
+ output(args)
2671
+ );
2672
+ case "purge":
2673
+ return runPurge(
2674
+ str(args, "scope") ?? (bool(args, "all") ? "all" : void 0),
2675
+ bool(args, "confirm")
2676
+ );
2677
+ case "cache-status":
2678
+ return runCacheStatus();
2679
+ case "connections":
2680
+ return runSourceRead(
2681
+ "connections",
2682
+ args.positionals[0] ?? str(args, "q"),
2683
+ num(args, "limit") ?? 25,
2684
+ output(args)
2685
+ );
2686
+ case "my-posts":
2687
+ return runSourceRead(
2688
+ "my-posts",
2689
+ args.positionals[0] ?? str(args, "q"),
2690
+ num(args, "limit") ?? 25,
2691
+ output(args)
2692
+ );
2693
+ case "sync":
2694
+ return runSync(args.positionals[0], num(args, "limit") ?? 50, bool(args, "force"), now);
2695
+ case "login":
2696
+ return runLogin();
2697
+ case "oauth":
2698
+ return runOauthStatus();
2699
+ case "share":
2700
+ return runShare(args.positionals[0], str(args, "visibility") ?? "public", now);
2701
+ case "comment":
2702
+ return runComment(args.positionals[0], args.positionals[1], now);
2703
+ case "react":
2704
+ return runReact(args.positionals[0], str(args, "type") ?? "LIKE", now);
2705
+ case "whoami":
2706
+ return runWhoami(bool(args, "raw"));
2707
+ case "profile":
2708
+ return runProfile(args.positionals[0], bool(args, "raw"));
2709
+ case "feed":
2710
+ return runFeed(num(args, "limit") ?? 10, output(args));
2711
+ case "post":
2712
+ return runPost(args.positionals[0], num(args, "limit") ?? 20, output(args));
2713
+ case "reactions":
2714
+ return runReactions(args.positionals[0], num(args, "limit") ?? 20, output(args));
2715
+ case "search":
2716
+ return runSearch(
2717
+ args.positionals[0],
2718
+ args.positionals[1],
2719
+ num(args, "limit") ?? 10,
2720
+ output(args)
2721
+ );
2722
+ default:
2723
+ return err(command, "NOT_IMPLEMENTED", `'${command}' has no runner wired`);
2724
+ }
2725
+ }
2726
+ var entry = shouldRunAsEntry(process.argv[1], import.meta.url, import.meta.main, [
2727
+ "lnrelay",
2728
+ "linkedin-relay-mcp"
2729
+ ]);
2730
+ if (entry.run) {
2731
+ if (entry.warning !== void 0) process.stderr.write(`${entry.warning}
2732
+ `);
2733
+ const envelope = await dispatch(process.argv.slice(2), Date.now()).catch(
2734
+ (e) => err(
2735
+ process.argv[2] ?? "unknown",
2736
+ "UNEXPECTED",
2737
+ e.message,
2738
+ "This is a bug in lnrelay, not a LinkedIn failure. The stack trace is on stderr."
2739
+ )
2740
+ );
2741
+ if (envelope.command !== "help") process.stdout.write(`${toJson(envelope)}
2742
+ `);
2743
+ process.exit(exitCodeFor(envelope));
2744
+ }
2745
+ export {
2746
+ dispatch
2747
+ };
2748
+ //# sourceMappingURL=cli.js.map