linkedin-relay-mcp 3.23.0 → 3.25.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // src/cli.ts
3
- import { readFileSync as readFileSync4 } from "fs";
3
+ import { readFileSync as readFileSync5 } from "fs";
4
4
 
5
5
  // src/args.ts
6
6
  function parseArgs(argv) {
@@ -1026,6 +1026,17 @@ var CONTRACTS = {
1026
1026
  provenance: "verified",
1027
1027
  capturedAt: "2026-10-16"
1028
1028
  },
1029
+ // The owner's notifications, probed 2026-10-29: the cards the bell opens,
1030
+ // newest first. The page itself also marks them seen; reading them here
1031
+ // does not. See engine/notifications.ts.
1032
+ notifications: {
1033
+ name: "notifications",
1034
+ transport: "voyager-restli",
1035
+ path: `${VOYAGER}/voyagerIdentityDashNotificationCards`,
1036
+ decorationId: "com.linkedin.voyager.dash.deco.identity.notifications.CardsCollectionWithInjectionsNoPills-25",
1037
+ provenance: "verified",
1038
+ capturedAt: "2026-10-29"
1039
+ },
1029
1040
  // A company page, captured 2026-10-14. The GraphQL company query by
1030
1041
  // universalName answers only the company's urn, so this is the REST
1031
1042
  // resource: by id (`/<id>`) or by name (`q=universalName`). It carries the
@@ -1481,10 +1492,10 @@ function classify(res, opts = {}) {
1481
1492
  function referencesUrns(data) {
1482
1493
  if (data === void 0) return false;
1483
1494
  let found = false;
1484
- const walk = (node) => {
1495
+ const walk2 = (node) => {
1485
1496
  if (found || node === null || typeof node !== "object") return;
1486
1497
  if (Array.isArray(node)) {
1487
- for (const item of node) walk(item);
1498
+ for (const item of node) walk2(item);
1488
1499
  return;
1489
1500
  }
1490
1501
  for (const [key, value] of Object.entries(node)) {
@@ -1496,10 +1507,10 @@ function referencesUrns(data) {
1496
1507
  found = true;
1497
1508
  return;
1498
1509
  }
1499
- walk(value);
1510
+ walk2(value);
1500
1511
  }
1501
1512
  };
1502
- walk(data);
1513
+ walk2(data);
1503
1514
  return found;
1504
1515
  }
1505
1516
 
@@ -1698,18 +1709,18 @@ function findRefs(data) {
1698
1709
  }
1699
1710
  }
1700
1711
  const refs = [];
1701
- const walk = (node) => {
1712
+ const walk2 = (node) => {
1702
1713
  if (node === null || typeof node !== "object") return;
1703
1714
  if (Array.isArray(node)) {
1704
- for (const item of node) walk(item);
1715
+ for (const item of node) walk2(item);
1705
1716
  return;
1706
1717
  }
1707
1718
  for (const [key, value] of Object.entries(node)) {
1708
1719
  if (key.startsWith("*") && typeof value === "string") refs.push(value);
1709
- else walk(value);
1720
+ else walk2(value);
1710
1721
  }
1711
1722
  };
1712
- walk(data);
1723
+ walk2(data);
1713
1724
  return refs;
1714
1725
  }
1715
1726
  function parseSingle(payload) {
@@ -1754,9 +1765,9 @@ function parseCollection(payload, opts) {
1754
1765
  `LinkedIn claims ${opts.claimedCount} items but returned none \u2014 treat this as a FAILED FETCH, not an empty result.`
1755
1766
  );
1756
1767
  }
1757
- const state = unresolved.length > 0 ? "partial" : opts.truncated === true ? "unknown" : "complete";
1768
+ const state2 = unresolved.length > 0 ? "partial" : opts.truncated === true ? "unknown" : "complete";
1758
1769
  const meta = {
1759
- state,
1770
+ state: state2,
1760
1771
  operation: opts.operation,
1761
1772
  contractCapturedAt: opts.contractCapturedAt ?? "unknown",
1762
1773
  // parsedCount counts what we kept; `items` includes the unknowns, which is
@@ -2045,7 +2056,7 @@ async function mintSessionFromBrowser() {
2045
2056
  };
2046
2057
  }
2047
2058
  function getAllCookies(wsUrl) {
2048
- return new Promise((resolve, reject) => {
2059
+ return new Promise((resolve2, reject) => {
2049
2060
  const ws = new WebSocket(wsUrl);
2050
2061
  const timer = setTimeout(() => {
2051
2062
  ws.close();
@@ -2057,7 +2068,7 @@ function getAllCookies(wsUrl) {
2057
2068
  if (msg.id === 1 && msg.result !== void 0) {
2058
2069
  clearTimeout(timer);
2059
2070
  ws.close();
2060
- resolve(msg.result.cookies);
2071
+ resolve2(msg.result.cookies);
2061
2072
  }
2062
2073
  };
2063
2074
  ws.onerror = () => {
@@ -2296,14 +2307,14 @@ function evaluate(expression, model) {
2296
2307
  const value = bool2(expression, model);
2297
2308
  return value === null ? unknownExpression(JSON.stringify(expression).slice(0, 80)) : { ok: true, value };
2298
2309
  }
2299
- function wireStates(keys, model, resolve) {
2310
+ function wireStates(keys, model, resolve2) {
2300
2311
  const out = [];
2301
2312
  for (const id of keys) {
2302
- const state = model.get(id);
2303
- if (state === void 0) continue;
2304
- let value = state.value;
2305
- if (state.protoCase === "expression") {
2306
- const r = resolve(id, state) ?? evaluate(state.value, model);
2313
+ const state2 = model.get(id);
2314
+ if (state2 === void 0) continue;
2315
+ let value = state2.value;
2316
+ if (state2.protoCase === "expression") {
2317
+ const r = resolve2(id, state2) ?? evaluate(state2.value, model);
2307
2318
  if (!r.ok) return r;
2308
2319
  value = r.value;
2309
2320
  }
@@ -2311,7 +2322,7 @@ function wireStates(keys, model, resolve) {
2311
2322
  key: id,
2312
2323
  namespace: "MemoryNamespace",
2313
2324
  value,
2314
- originalProtoCase: state.protoCase,
2325
+ originalProtoCase: state2.protoCase,
2315
2326
  protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id } }
2316
2327
  });
2317
2328
  }
@@ -2399,22 +2410,56 @@ function postsPagerBody(q2) {
2399
2410
  }
2400
2411
  };
2401
2412
  }
2413
+ function unitsFor(stream, from, bytes) {
2414
+ let i = from;
2415
+ let left = bytes;
2416
+ while (left > 0 && i < stream.length) {
2417
+ const c = stream.codePointAt(i);
2418
+ left -= c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4;
2419
+ i += c > 65535 ? 2 : 1;
2420
+ }
2421
+ return i - from;
2422
+ }
2402
2423
  var Rows = class {
2403
2424
  constructor(stream) {
2404
2425
  this.stream = stream;
2405
- for (const m of stream.matchAll(/(?:^|\n)([0-9a-f]+):/g)) {
2406
- const at = (m.index ?? 0) + (m[0].startsWith("\n") ? 1 : 0);
2407
- this.starts.push({ id: m[1], at });
2408
- }
2409
- for (let i = 0; i < this.starts.length; i++) {
2410
- const s = this.starts[i];
2411
- const end = this.starts[i + 1]?.at ?? stream.length;
2412
- this.byId.set(s.id, stream.slice(s.at + s.id.length + 1, end));
2426
+ const head = /([0-9a-f]+):(?:T([0-9a-f]+),)?/y;
2427
+ let pos = 0;
2428
+ while (pos < stream.length) {
2429
+ if (stream[pos] === "\n") {
2430
+ pos++;
2431
+ continue;
2432
+ }
2433
+ head.lastIndex = pos;
2434
+ const m = head.exec(stream);
2435
+ if (m === null) {
2436
+ const nl = stream.indexOf("\n", pos);
2437
+ pos = nl === -1 ? stream.length : nl + 1;
2438
+ continue;
2439
+ }
2440
+ const id = m[1];
2441
+ const body = pos + m[0].length;
2442
+ this.starts.push({ id, at: pos });
2443
+ let end;
2444
+ if (m[2] !== void 0) {
2445
+ end = body + unitsFor(stream, body, Number.parseInt(m[2], 16));
2446
+ this.texts.add(id);
2447
+ } else {
2448
+ const nl = stream.indexOf("\n", body);
2449
+ end = nl === -1 ? stream.length : nl;
2450
+ }
2451
+ this.byId.set(id, stream.slice(body, end));
2452
+ pos = end;
2413
2453
  }
2414
2454
  }
2415
2455
  stream;
2416
2456
  byId = /* @__PURE__ */ new Map();
2417
2457
  starts = [];
2458
+ texts = /* @__PURE__ */ new Set();
2459
+ /** Whether a row is raw text (a `T` row) rather than JSON. */
2460
+ isText(id) {
2461
+ return this.texts.has(id);
2462
+ }
2418
2463
  /** The row a stream position falls in. */
2419
2464
  at(pos) {
2420
2465
  let lo = 0;
@@ -2489,7 +2534,7 @@ function firstIn(rows, ids, find) {
2489
2534
  }
2490
2535
  function authorOf(rows, actor) {
2491
2536
  if (actor === void 0) return { fields: {}, used: [] };
2492
- const state = (key) => (row) => {
2537
+ const state2 = (key) => (row) => {
2493
2538
  const m = row.match(new RegExp(`"${key}"[^]*?"stringValue":"((?:[^"\\\\]|\\\\.)*)"`));
2494
2539
  return m?.[1] === void 0 ? void 0 : jsonString(m[1]);
2495
2540
  };
@@ -2500,8 +2545,8 @@ function authorOf(rows, actor) {
2500
2545
  /"(?:https:\/\/www\.linkedin\.com)?(\/(?:in|company|school|showcase)\/[^"?/]+)/
2501
2546
  )?.[1]
2502
2547
  );
2503
- const person = firstIn(rows, actor.under, state("profile_name_loading_state"));
2504
- const headline = firstIn(rows, actor.under, state("profile_headline_loading_state"));
2548
+ const person = firstIn(rows, actor.under, state2("profile_name_loading_state"));
2549
+ const headline = firstIn(rows, actor.under, state2("profile_headline_loading_state"));
2505
2550
  const page = person !== void 0 ? void 0 : firstIn(rows, actor.under, (row) => {
2506
2551
  const labels = [...row.matchAll(/"aria-label":"((?:[^"\\]|\\.)+)"/g)].map(
2507
2552
  (m) => jsonString(m[1]).trim()
@@ -2652,25 +2697,25 @@ function splitLocation(line2) {
2652
2697
  const kind = m?.[2] === void 0 ? void 0 : WORKPLACE_SUFFIX[m[2].toLowerCase()];
2653
2698
  return kind === void 0 || m?.[1] === void 0 ? { location: line2 } : { location: m[1], workplace: kind };
2654
2699
  }
2655
- function cardToJob(card) {
2656
- const urn = card.jobPostingUrn ?? card["*jobPosting"];
2700
+ function cardToJob(card2) {
2701
+ const urn = card2.jobPostingUrn ?? card2["*jobPosting"];
2657
2702
  const id = typeof urn === "string" ? jobIdOf(urn) : void 0;
2658
- const title = typeof card.jobPostingTitle === "string" ? card.jobPostingTitle : text2(card.title);
2703
+ const title = typeof card2.jobPostingTitle === "string" ? card2.jobPostingTitle : text2(card2.title);
2659
2704
  if (id === void 0 || title === void 0) return void 0;
2660
- const footer = Array.isArray(card.footerItems) ? card.footerItems : [];
2705
+ const footer = Array.isArray(card2.footerItems) ? card2.footerItems : [];
2661
2706
  const listed2 = footer.find((f) => f.type === "LISTED_DATE");
2662
2707
  const insights = footer.filter((f) => !["LISTED_DATE", "PROMOTED", "EASY_APPLY_TEXT"].includes(String(f.type))).map((f) => text2(f.text)).filter((t) => t !== void 0);
2663
- const insight2 = text2(card.relevanceInsight?.text);
2708
+ const insight2 = text2(card2.relevanceInsight?.text);
2664
2709
  if (insight2 !== void 0) insights.push(insight2);
2665
2710
  return defined3({
2666
2711
  id,
2667
2712
  title,
2668
- company: text2(card.primaryDescription),
2669
- ...splitLocation(text2(card.secondaryDescription)),
2713
+ company: text2(card2.primaryDescription),
2714
+ ...splitLocation(text2(card2.secondaryDescription)),
2670
2715
  listed: day(listed2?.timeAt),
2671
2716
  easyApply: footer.some((f) => f.type === "EASY_APPLY_TEXT"),
2672
2717
  promoted: footer.some((f) => f.type === "PROMOTED"),
2673
- salary: text2(card.tertiaryDescription),
2718
+ salary: text2(card2.tertiaryDescription),
2674
2719
  insights: insights.length > 0 ? insights : void 0,
2675
2720
  url: viewUrl(id)
2676
2721
  });
@@ -2696,8 +2741,8 @@ function readCards(elements, included) {
2696
2741
  for (const kind of Object.keys(union)) unknownTypes[kind] = (unknownTypes[kind] ?? 0) + 1;
2697
2742
  continue;
2698
2743
  }
2699
- const card = byUrn.get(ref);
2700
- const job = card === void 0 ? void 0 : cardToJob(card);
2744
+ const card2 = byUrn.get(ref);
2745
+ const job = card2 === void 0 ? void 0 : cardToJob(card2);
2701
2746
  if (job === void 0) unresolved++;
2702
2747
  else if (!jobs.some((j) => j.id === job.id)) jobs.push(job);
2703
2748
  }
@@ -2823,11 +2868,11 @@ function hiringTeamBody(jobId) {
2823
2868
  };
2824
2869
  }
2825
2870
  var unquote = (s) => JSON.parse(`"${s}"`);
2826
- function memberOf(card, id) {
2827
- const url = card.match(/"url":"(https:\/\/www\.linkedin\.com\/in\/[^"/]+\/)"/)?.[1];
2828
- const name = card.match(/\[null,"((?:[^"\\]|\\.)+)"/)?.[1];
2871
+ function memberOf(card2, id) {
2872
+ const url = card2.match(/"url":"(https:\/\/www\.linkedin\.com\/in\/[^"/]+\/)"/)?.[1];
2873
+ const name = card2.match(/\[null,"((?:[^"\\]|\\.)+)"/)?.[1];
2829
2874
  if (url === void 0 || name === void 0) return void 0;
2830
- const lines = [...card.matchAll(/"children":\["((?:[^"\\$]|\\.)(?:[^"\\]|\\.)*)"\]/g)].map(
2875
+ const lines = [...card2.matchAll(/"children":\["((?:[^"\\$]|\\.)(?:[^"\\]|\\.)*)"\]/g)].map(
2831
2876
  (m) => unquote(m[1]).trim()
2832
2877
  );
2833
2878
  const degree = lines.find((l) => l.startsWith("\u2022"));
@@ -2839,7 +2884,7 @@ function memberOf(card, id) {
2839
2884
  headline,
2840
2885
  degree: degree?.replace(/^•\s*/, ""),
2841
2886
  role: role3,
2842
- verified: /"role":"img","aria-label"/.test(card) ? true : void 0
2887
+ verified: /"role":"img","aria-label"/.test(card2) ? true : void 0
2843
2888
  });
2844
2889
  }
2845
2890
  function parseHiringTeam(stream) {
@@ -2848,7 +2893,7 @@ function parseHiringTeam(stream) {
2848
2893
  return drift2("the hiring team answer was not the hiring team component");
2849
2894
  const rows = new Rows(stream);
2850
2895
  const cards = [...rows.byId].filter(([, row]) => /linkedin\.com\\?\/in\\?\//.test(row));
2851
- const at = (card) => stream.indexOf(`"$L${card}"`);
2896
+ const at = (card2) => stream.indexOf(`"$L${card2}"`);
2852
2897
  const placed = cards.map(([key]) => at(key)).sort((a, b) => a - b);
2853
2898
  const members = [];
2854
2899
  for (const [key, row] of cards) {
@@ -4105,8 +4150,8 @@ async function fetchScheduled(client, pageSize = PAGE_SIZE2) {
4105
4150
  }
4106
4151
  if (posts.length >= claimedCount || fresh.length === 0) break;
4107
4152
  }
4108
- const state = posts.length >= claimedCount ? "complete" : "partial";
4109
- return { ok: true, posts, claimedCount, state };
4153
+ const state2 = posts.length >= claimedCount ? "complete" : "partial";
4154
+ return { ok: true, posts, claimedCount, state: state2 };
4110
4155
  }
4111
4156
 
4112
4157
  // src/engine/voyager-write.ts
@@ -4275,8 +4320,8 @@ async function share(confirmed, client, bytes) {
4275
4320
  }
4276
4321
  }
4277
4322
  const media = [];
4278
- const { card } = confirmed.payload;
4279
- if (card !== void 0) media.push({ category: "ARTICLE", urn: card.urn });
4323
+ const { card: card2 } = confirmed.payload;
4324
+ if (card2 !== void 0) media.push({ category: "ARTICLE", urn: card2.urn });
4280
4325
  const { poll } = confirmed.payload;
4281
4326
  if (poll !== void 0) {
4282
4327
  const created = await createPoll(poll, client);
@@ -6389,6 +6434,106 @@ async function runNetwork(list2, req, opts = {}, fetch2) {
6389
6434
  });
6390
6435
  }
6391
6436
 
6437
+ // src/engine/notifications.ts
6438
+ function notificationsUrl(count3, start) {
6439
+ const c = CONTRACTS.notifications;
6440
+ if (c?.decorationId === void 0) throw new Error("the 'notifications' contract is missing");
6441
+ return `${c.path}?decorationId=${c.decorationId}&q=filterVanityName&count=${count3}&start=${start}`;
6442
+ }
6443
+ var drift7 = (message) => ({ ok: false, code: "SCHEMA_DRIFT", message });
6444
+ var textOf = (v) => {
6445
+ const t = v?.text;
6446
+ return typeof t === "string" && t.trim() !== "" ? t.trim() : void 0;
6447
+ };
6448
+ var absolute = (v) => typeof v === "string" && v !== "" ? v.startsWith("/") ? `https://www.linkedin.com${v}` : v : void 0;
6449
+ function card(n) {
6450
+ const text6 = textOf(n.headline);
6451
+ if (text6 === void 0) return void 0;
6452
+ const kind = String(n.entityUrn ?? "").match(/fsd_notificationCard:\(([^,]+),/)?.[1] ?? "UNKNOWN";
6453
+ const detail = [n.subHeadline, n.contentPrimaryText, n.contentSecondaryText, n.kickerText].map(textOf).filter((t) => t !== void 0).join(" \xB7 ");
6454
+ const at = typeof n.publishedAt === "number" ? new Date(n.publishedAt).toISOString() : void 0;
6455
+ const url = absolute(n.cardAction?.actionTarget);
6456
+ const from = absolute(n.headerImage?.actionTarget);
6457
+ return {
6458
+ kind,
6459
+ text: text6,
6460
+ ...detail !== "" ? { detail } : {},
6461
+ ...at !== void 0 ? { at } : {},
6462
+ read: n.read === true,
6463
+ ...url !== void 0 ? { url } : {},
6464
+ ...from !== void 0 ? { from } : {}
6465
+ };
6466
+ }
6467
+ function parseNotifications(json) {
6468
+ const root = json;
6469
+ const data = root?.data;
6470
+ const listed2 = data?.["*elements"] ?? data?.elements;
6471
+ if (!Array.isArray(listed2)) return drift7("the notifications answer carried no card list");
6472
+ const byUrn = new Map((root?.included ?? []).map((n) => [n.entityUrn, n]));
6473
+ const items = listed2.flatMap((u) => {
6474
+ const n = byUrn.get(u);
6475
+ const c = n === void 0 ? void 0 : card(n);
6476
+ return c === void 0 ? [] : [c];
6477
+ });
6478
+ if (listed2.length > 0 && items.length === 0)
6479
+ return drift7(`${listed2.length} notifications were listed but none could be read`);
6480
+ const meta = data?.metadata ?? {};
6481
+ return {
6482
+ ok: true,
6483
+ items,
6484
+ ...typeof meta.numUnseen === "number" ? { unseen: meta.numUnseen } : {},
6485
+ ...typeof meta.nextStart === "number" ? { next: meta.nextStart } : {}
6486
+ };
6487
+ }
6488
+
6489
+ // src/commands/notifications.ts
6490
+ function liveFetch8(quiet) {
6491
+ const session = loadSession();
6492
+ if (session.state !== "ok")
6493
+ return err("notifications", "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
6494
+ const client = createLiveClient(session.session, void 0, quiet);
6495
+ return async (url, spendClass) => {
6496
+ const r = await client.request({ url, spendClass, operation: "notifications" });
6497
+ return r.ok ? { ok: true, json: r.json } : r;
6498
+ };
6499
+ }
6500
+ var PAGE = 25;
6501
+ var compactNotification = (n) => line([n.read ? void 0 : "unread", n.at, n.kind, n.text, n.detail, n.url]);
6502
+ async function runNotifications(req, opts = {}, fetch2) {
6503
+ const get = fetch2 ?? liveFetch8(opts.quiet === true);
6504
+ if (typeof get !== "function") return get;
6505
+ const limit = Math.max(1, req.limit);
6506
+ const items = [];
6507
+ let unseen;
6508
+ let start = 0;
6509
+ let stoppedBy;
6510
+ while (start !== void 0 && items.length < limit) {
6511
+ const res = await get(notificationsUrl(PAGE, start), "page");
6512
+ const page = res.ok ? parseNotifications(res.json) : res;
6513
+ if (!page.ok) {
6514
+ if (items.length === 0 && start === 0)
6515
+ return err("notifications", page.code, page.message, page.hint);
6516
+ stoppedBy = page.code;
6517
+ break;
6518
+ }
6519
+ unseen ??= page.unseen;
6520
+ items.push(...page.items.filter((n) => req.unread !== true || !n.read));
6521
+ start = page.next !== void 0 && page.next > start ? page.next : void 0;
6522
+ }
6523
+ const kept = items.slice(0, limit);
6524
+ const state2 = stoppedBy !== void 0 || start !== void 0 && kept.length === limit ? "partial" : "complete";
6525
+ return ok("notifications", {
6526
+ ...unseen !== void 0 ? { unseen } : {},
6527
+ items: shape(kept, opts, compactNotification),
6528
+ meta: {
6529
+ state: state2,
6530
+ operation: "notifications",
6531
+ returnedCount: kept.length,
6532
+ ...stoppedBy !== void 0 ? { stoppedBy } : {}
6533
+ }
6534
+ });
6535
+ }
6536
+
6392
6537
  // src/commands/oauth.ts
6393
6538
  import { spawn } from "child_process";
6394
6539
  import { createServer } from "http";
@@ -6401,12 +6546,12 @@ var USERINFO = "https://api.linkedin.com/v2/userinfo";
6401
6546
  var CALLBACK_PORT = 53682;
6402
6547
  var REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;
6403
6548
  var SCOPES = ["openid", "profile", "w_member_social"];
6404
- function authorizationUrl(clientId, state) {
6549
+ function authorizationUrl(clientId, state2) {
6405
6550
  const params = new URLSearchParams({
6406
6551
  response_type: "code",
6407
6552
  client_id: clientId,
6408
6553
  redirect_uri: REDIRECT_URI,
6409
- state,
6554
+ state: state2,
6410
6555
  scope: SCOPES.join(" ")
6411
6556
  });
6412
6557
  return `${AUTHORIZE}?${params.toString()}`;
@@ -6483,8 +6628,8 @@ function parseCallback(rawUrl, expectedState) {
6483
6628
  const description = url.searchParams.get("error_description") ?? "";
6484
6629
  return { ok: false, message: `LinkedIn denied the request: ${error} ${description}`.trim() };
6485
6630
  }
6486
- const state = url.searchParams.get("state");
6487
- if (state !== expectedState) {
6631
+ const state2 = url.searchParams.get("state");
6632
+ if (state2 !== expectedState) {
6488
6633
  return { ok: false, message: "state mismatch \u2014 this callback did not come from this login" };
6489
6634
  }
6490
6635
  const code = url.searchParams.get("code");
@@ -6529,7 +6674,7 @@ var CALLBACK_TIMEOUT_MS = 3e5;
6529
6674
  var DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>lnrelay</title>
6530
6675
  <body style="font:16px system-ui;padding:3rem;max-width:32rem">
6531
6676
  <h1>Authorised.</h1><p>You can close this tab and go back to the terminal.</p>`;
6532
- function listenForCallback(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
6677
+ function listenForCallback(state2, timeoutMs = CALLBACK_TIMEOUT_MS) {
6533
6678
  return new Promise((ready) => {
6534
6679
  let settle = () => {
6535
6680
  };
@@ -6545,7 +6690,7 @@ function listenForCallback(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
6545
6690
  }
6546
6691
  res.writeHead(200, { "content-type": "text/html; charset=utf-8", connection: "close" });
6547
6692
  res.end(DONE_PAGE);
6548
- settle(parseCallback(url, state));
6693
+ settle(parseCallback(url, state2));
6549
6694
  });
6550
6695
  const timer = setTimeout(() => {
6551
6696
  settle({
@@ -6579,7 +6724,7 @@ function openBrowser(url) {
6579
6724
  function loginDeps() {
6580
6725
  return {
6581
6726
  state: () => crypto.randomUUID(),
6582
- listen: (state) => listenForCallback(state),
6727
+ listen: (state2) => listenForCallback(state2),
6583
6728
  open: openBrowser,
6584
6729
  write: (s) => process.stderr.write(s),
6585
6730
  isTty: process.stdin.isTTY === true && process.stderr.isTTY === true,
@@ -6617,13 +6762,13 @@ ${OAUTH_SETUP}`
6617
6762
  async function runOauthLogin(opts, deps = loginDeps()) {
6618
6763
  const creds = await credentials(opts, deps);
6619
6764
  if ("ok" in creds) return creds;
6620
- const state = deps.state();
6621
- const listener = await deps.listen(state);
6765
+ const state2 = deps.state();
6766
+ const listener = await deps.listen(state2);
6622
6767
  if (!listener.ok) {
6623
6768
  return err("oauth", "AUTH_FAILED", listener.message);
6624
6769
  }
6625
6770
  try {
6626
- const url = authorizationUrl(creds.clientId, state);
6771
+ const url = authorizationUrl(creds.clientId, state2);
6627
6772
  deps.write(`Opening LinkedIn for consent. If nothing opens, visit:
6628
6773
 
6629
6774
  ${url}
@@ -6695,7 +6840,7 @@ function contactInfoBody(publicId, firstName, lastName) {
6695
6840
  isModal: true
6696
6841
  };
6697
6842
  }
6698
- var drift7 = (message) => ({ ok: false, code: "SCHEMA_DRIFT", message });
6843
+ var drift8 = (message) => ({ ok: false, code: "SCHEMA_DRIFT", message });
6699
6844
  var unquote2 = (s) => JSON.parse(`"${s}"`);
6700
6845
  var LABEL = /\["\$","p",null,\{"className":"[^"]*","children":\["((?:[^"\\]|\\.)+)"\]\}\]/g;
6701
6846
  var VIEW = /"viewName":"contact-([a-z-]+)"/g;
@@ -6766,9 +6911,9 @@ function put(contact, f) {
6766
6911
  }
6767
6912
  function parseContactInfo(stream) {
6768
6913
  if (!stream.includes("profile-contact-info-details-view"))
6769
- return drift7("the contact info answer was not the contact info overlay");
6914
+ return drift8("the contact info answer was not the contact info overlay");
6770
6915
  const fields = fieldsOf(stream);
6771
- if (fields.length === 0) return drift7("the contact info overlay had no fields");
6916
+ if (fields.length === 0) return drift8("the contact info overlay had no fields");
6772
6917
  const contact = {};
6773
6918
  for (const f of fields) put(contact, f);
6774
6919
  return { ok: true, contact };
@@ -6789,7 +6934,7 @@ function positionsPageUrl(profileUrn, start) {
6789
6934
  const c = contract3("profilePositions");
6790
6935
  return `${c.path}?q=viewee&profileUrn=${encodeURIComponent(profileUrn)}&decorationId=${c.decorationId}&start=${start}&count=${POSITIONS_PAGE}`;
6791
6936
  }
6792
- var drift8 = (message) => ({ ok: false, code: "SCHEMA_DRIFT", message });
6937
+ var drift9 = (message) => ({ ok: false, code: "SCHEMA_DRIFT", message });
6793
6938
  var str4 = (v) => typeof v === "string" && v.trim() !== "" && v.trim() !== "-" ? v.trim() : void 0;
6794
6939
  var idOf3 = (urn) => String(urn ?? "").match(/:(\d+)$/)?.[1];
6795
6940
  function defined7(obj) {
@@ -6902,13 +7047,13 @@ var some = (xs) => xs.length > 0 ? xs : void 0;
6902
7047
  function parseFullProfile(json) {
6903
7048
  const root = json;
6904
7049
  const listed2 = root?.data?.["*elements"];
6905
- if (!Array.isArray(listed2)) return drift8("the profile answer carried no profile list");
7050
+ if (!Array.isArray(listed2)) return drift9("the profile answer carried no profile list");
6906
7051
  if (listed2.length === 0)
6907
7052
  return { ok: false, code: "NOT_FOUND", message: "no profile has that id on LinkedIn" };
6908
7053
  const ix = new Index(root?.included ?? []);
6909
7054
  const p = ix.get(listed2[0]);
6910
7055
  const urn = typeof p?.entityUrn === "string" ? p.entityUrn : void 0;
6911
- if (p === void 0 || urn === void 0) return drift8("the profile was listed but not sent");
7056
+ if (p === void 0 || urn === void 0) return drift9("the profile was listed but not sent");
6912
7057
  const counts2 = {};
6913
7058
  const count3 = (key, shown, total) => {
6914
7059
  if (total !== void 0 && total > shown) counts2[key] = { shown, total };
@@ -6963,11 +7108,11 @@ function parseFullProfile(json) {
6963
7108
  function parsePositionsPage(json) {
6964
7109
  const root = json;
6965
7110
  const refs = root?.data?.["*elements"];
6966
- if (!Array.isArray(refs)) return drift8("the experience page carried no position groups");
7111
+ if (!Array.isArray(refs)) return drift9("the experience page carried no position groups");
6967
7112
  const ix = new Index(root?.included ?? []);
6968
7113
  const groups = refs.flatMap((r) => ix.list(r));
6969
7114
  if (refs.length > 0 && groups.length === 0)
6970
- return drift8(`${refs.length} position groups were listed but none sent`);
7115
+ return drift9(`${refs.length} position groups were listed but none sent`);
6971
7116
  const total = root?.data?.paging?.total;
6972
7117
  return {
6973
7118
  ok: true,
@@ -6977,153 +7122,625 @@ function parsePositionsPage(json) {
6977
7122
  };
6978
7123
  }
6979
7124
 
6980
- // src/commands/profile.ts
6981
- function liveFetch8(quiet) {
6982
- const session = loadSession();
6983
- if (session.state !== "ok")
6984
- return err("profile", "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
6985
- const client = createLiveClient(session.session, void 0, quiet);
6986
- return async (url, spendClass, body) => {
6987
- const r = await client.request({
6988
- url,
6989
- ...body !== void 0 ? { method: "POST", body } : {},
6990
- spendClass,
6991
- operation: "profile"
6992
- });
6993
- if (!r.ok) return r;
6994
- return { ok: true, json: r.json, raw: r.classification.raw ?? "" };
7125
+ // src/engine/recommendations.ts
7126
+ var PAGER = "com.linkedin.sdui.pagers.profile.details.recommendations";
7127
+ var SCREEN3 = "com.linkedin.sdui.flagshipnav.profile.ProfileRecommendationDetails";
7128
+ var RECOMMENDATIONS_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${PAGER}`;
7129
+ var RECOMMENDATIONS_PAGE = 15;
7130
+ function recommendationsBody(kind, vanityName, profileId2, start) {
7131
+ const args = {
7132
+ $type: "proto.sdui.actions.requests.RequestedArguments",
7133
+ requestedStateKeys: [],
7134
+ payload: {
7135
+ type: kind === "received" ? "Received" : "Given",
7136
+ vanityName,
7137
+ profileId: profileId2,
7138
+ start,
7139
+ detailScreenTabIndex: kind === "received" ? "0" : "1",
7140
+ count: RECOMMENDATIONS_PAGE
7141
+ },
7142
+ requestMetadata: { $type: "proto.sdui.common.RequestMetadata" }
6995
7143
  };
6996
- }
6997
- function memberIdOf(input) {
6998
- const s = input.trim();
6999
- const slug = s.match(/linkedin\.com\/in\/([^/?#]+)/)?.[1];
7000
- if (slug !== void 0) {
7001
- try {
7002
- return decodeURIComponent(slug);
7003
- } catch {
7004
- return slug;
7144
+ return {
7145
+ pagerId: PAGER,
7146
+ clientArguments: { ...args, states: [], screenId: SCREEN3, knownTemplateIds: [] },
7147
+ paginationRequest: {
7148
+ $type: "proto.sdui.actions.requests.PaginationRequest",
7149
+ pagerId: PAGER,
7150
+ retryCount: 2,
7151
+ requestedArguments: args
7005
7152
  }
7006
- }
7007
- return s.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/)?.[1] ?? s;
7153
+ };
7008
7154
  }
7009
- async function readRestOfExperience(get, p) {
7010
- const want = p.counts?.experience;
7011
- if (want === void 0) return;
7012
- let start = want.shown;
7013
- while (start < want.total) {
7014
- const res = await get(positionsPageUrl(p.urn, start), "profile");
7015
- const page = res.ok ? parsePositionsPage(res.json) : res;
7016
- if (!page.ok) {
7017
- p.experienceError = `${page.code}: ${page.message}`;
7018
- return;
7155
+ var drift10 = (message) => ({ ok: false, code: "SCHEMA_DRIFT", message });
7156
+ var unquote3 = (s) => JSON.parse(`"${s}"`);
7157
+ var STR = '((?:[^"\\\\]|\\\\.)+)';
7158
+ var loading = (id) => new RegExp(
7159
+ `"id":"${id}"\\}\\},"namespace":"LoadingNamespace"\\},"value":\\{"\\$case":"stringValue","stringValue":"${STR}"`
7160
+ );
7161
+ var NAME = loading("profile_name_loading_state");
7162
+ var HEADLINE = loading("profile_headline_loading_state");
7163
+ var PROFILE_URL = /"url":"(https:\/\/www\.linkedin\.com\/in\/[^"]+)"/;
7164
+ var TEXT3 = /"children":\["((?:[^"\\$]|\\.)(?:[^"\\]|\\.)*)"\]/g;
7165
+ var FRAGMENT = /\["\$","\$9","\d+",\{"children":\[(?:null|\["\$","br",null,\{\}\]),"((?:[^"\\]|\\.)*)"\]/g;
7166
+ var REF = /"\$L([0-9a-f]+)"/g;
7167
+ var ANY_REF = /"\$L?([0-9a-f]+)"/g;
7168
+ function header(rows, id) {
7169
+ const row = rows.byId.get(id) ?? "";
7170
+ const name = row.match(NAME)?.[1];
7171
+ if (name === void 0) return void 0;
7172
+ const headline = row.match(HEADLINE)?.[1];
7173
+ const all = rows.reach(id).map((r) => rows.byId.get(r) ?? "").join("\n");
7174
+ const texts3 = [...all.matchAll(TEXT3)].map((m) => unquote3(m[1]).trim());
7175
+ const degree = texts3.find((t) => t.startsWith("\xB7"));
7176
+ const shown = /* @__PURE__ */ new Set([unquote3(name), headline === void 0 ? "" : unquote3(headline)]);
7177
+ const context = texts3.filter((t) => t !== degree && !shown.has(t)).pop();
7178
+ const url = row.match(PROFILE_URL)?.[1];
7179
+ return {
7180
+ name: unquote3(name).trim(),
7181
+ ...url !== void 0 ? { url } : {},
7182
+ ...headline !== void 0 ? { headline: unquote3(headline).trim() } : {},
7183
+ ...degree !== void 0 ? { degree: degree.replace(/^·\s*/, "") } : {},
7184
+ ...context !== void 0 ? { context } : {}
7185
+ };
7186
+ }
7187
+ function inlined(rows, segment, depth = 0) {
7188
+ if (depth > 3) return segment;
7189
+ return segment.replace(ANY_REF, (ref, id) => {
7190
+ const row = rows.byId.get(id);
7191
+ if (row === void 0) return ref;
7192
+ if (rows.isText(id)) return JSON.stringify(row);
7193
+ return row.startsWith('["$","$9"') ? inlined(rows, row, depth + 1) : ref;
7194
+ });
7195
+ }
7196
+ function bodyOf(segment) {
7197
+ const fragments = [...segment.matchAll(FRAGMENT)].map((m) => unquote3(m[1]));
7198
+ const lines = fragments.length > 0 ? fragments : [...segment.matchAll(TEXT3)].map((m) => unquote3(m[1]));
7199
+ return lines.map((l) => l.replace(/\r/g, "").trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
7200
+ }
7201
+ function parseRecommendations(stream) {
7202
+ if (!stream.includes("isPartialPage") && !stream.includes(PAGER))
7203
+ return drift10("the recommendations answer was not the recommendations list");
7204
+ const rows = new Rows(stream);
7205
+ const headers2 = [...rows.byId].filter(([, row]) => NAME.test(row) && !row.startsWith('[["$"')).map(([id]) => id);
7206
+ const heads = new Set(headers2);
7207
+ const placed = headers2.flatMap((h) => {
7208
+ for (const [id, row] of rows.byId) {
7209
+ const at = row.indexOf(`"$L${h}"`);
7210
+ if (at !== -1) return [{ h, row: id, at }];
7019
7211
  }
7020
- p.experience = [...p.experience ?? [], ...page.experience];
7021
- start += page.groups;
7022
- if (page.groups < POSITIONS_PAGE) break;
7212
+ return [];
7213
+ });
7214
+ const holders = new Set(placed.map((p) => p.row));
7215
+ const items = [];
7216
+ for (const p of placed) {
7217
+ const row = rows.byId.get(p.row) ?? "";
7218
+ let end = row.length;
7219
+ for (const m of row.slice(p.at + 1).matchAll(REF)) {
7220
+ const id = m[1];
7221
+ if (heads.has(id) || holders.has(id) && id !== p.row) {
7222
+ end = p.at + 1 + (m.index ?? 0);
7223
+ break;
7224
+ }
7225
+ }
7226
+ const who = header(rows, p.h);
7227
+ const text6 = bodyOf(inlined(rows, row.slice(p.at, end)));
7228
+ if (who !== void 0 && text6 !== "") items.push({ ...who, text: text6 });
7023
7229
  }
7024
- const counts2 = { ...p.counts };
7025
- if (start >= want.total) delete counts2.experience;
7026
- else counts2.experience = { shown: start, total: want.total };
7027
- if (Object.keys(counts2).length > 0) p.counts = counts2;
7028
- else delete p.counts;
7230
+ if (headers2.length > 0 && items.length === 0)
7231
+ return drift10(`${headers2.length} recommendations were shown but none could be read`);
7232
+ return { ok: true, items };
7029
7233
  }
7030
- async function readContact(get, p) {
7031
- if (p.publicId === void 0 || p.firstName === void 0) {
7032
- p.contactError = "NOT_FOUND: the profile has no public id or name to ask with";
7033
- return;
7234
+
7235
+ // src/engine/sdui-profile.ts
7236
+ var NAV_URL = "https://www.linkedin.com/flagship-web/rsc-action/actions/navigation";
7237
+ var ACTION_URL = "https://www.linkedin.com/flagship-web/rsc-action/actions/server-request";
7238
+ var PROFILE_FIELDS = {
7239
+ headline: {
7240
+ name: "headline",
7241
+ screen: "com.linkedin.sdui.flagshipnav.profile.ProfileEditIntroForm",
7242
+ save: "com.linkedin.sdui.requests.profile.saveProfileIntroForm",
7243
+ binding: "headline",
7244
+ // The web form refuses more ("Exceeded maximum length of 220 characters").
7245
+ maxLength: 220
7246
+ },
7247
+ about: {
7248
+ name: "about",
7249
+ screen: "com.linkedin.sdui.flagshipnav.profile.ProfileAboutForm",
7250
+ save: "com.linkedin.sdui.requests.profile.saveProfileAboutForm",
7251
+ binding: "about",
7252
+ maxLength: 2600
7034
7253
  }
7035
- const body = contactInfoBody(p.publicId, p.firstName, p.lastName ?? "");
7036
- const res = await get(CONTACT_INFO_URL, "profile", body);
7037
- const read = res.ok ? parseContactInfo(res.raw ?? "") : res;
7038
- if (read.ok) p.contact = read.contact;
7039
- else p.contactError = `${read.code}: ${read.message}`;
7040
- }
7041
- var span = (x) => x.start === void 0 && x.end === void 0 ? void 0 : `${x.start ?? "?"} \u2013 ${x.current === true ? "now" : x.end ?? "?"}`;
7042
- var roleLine = (r) => line([r.title, r.company, span(r), r.employmentType, r.location]);
7043
- var schoolLine = (s) => line([s.school, s.degree, s.field, span(s)]);
7044
- var entryLine = (e) => {
7045
- const { description: _d, url, ...rest } = e;
7046
- const dates = span(e);
7047
- const fields = Object.entries(rest).filter(([k, v]) => !["start", "end", "current"].includes(k) && typeof v === "string").map(([, v]) => v);
7048
- return line([...fields, dates, typeof url === "string" ? url : void 0]);
7049
7254
  };
7050
- var LISTS2 = [
7051
- "certifications",
7052
- "languages",
7053
- "honors",
7054
- "publications",
7055
- "projects",
7056
- "volunteering",
7057
- "courses",
7058
- "organizations",
7059
- "patents",
7060
- "testScores"
7061
- ];
7062
- function compact(p) {
7063
- const out = { ...p };
7064
- if (p.experience !== void 0) out.experience = p.experience.map(roleLine);
7065
- if (p.education !== void 0) out.education = p.education.map(schoolLine);
7066
- for (const key of LISTS2) {
7067
- const rows = p[key];
7068
- if (rows !== void 0) out[key] = rows.map(entryLine);
7069
- }
7070
- return out;
7255
+ var drift11 = (message) => ({
7256
+ ok: false,
7257
+ code: "SCHEMA_DRIFT",
7258
+ message,
7259
+ hint: "Re-capture the profile form with scripts/observe-write.ts (edit one character, then revert)."
7260
+ });
7261
+ function readForm(stream, field) {
7262
+ const states2 = readModel(stream);
7263
+ if (states2 === null) return drift11("the profile form carried no initial values");
7264
+ const args = findRequest(stream, field.save);
7265
+ if (args === null)
7266
+ return drift11(`the profile form carried no ${field.save.split(".").pop()} action`);
7267
+ return { ok: true, args, states: states2, screen: field.screen, save: field.save };
7071
7268
  }
7072
- async function runProfile(input, opts = {}, fetch2, req = {}) {
7073
- if (input === void 0 || input.trim() === "")
7074
- return err(
7075
- "profile",
7076
- "INVALID_INPUT",
7077
- "a public id, profile URL or urn is required",
7078
- "lnrelay profile <public-id|url|urn>"
7079
- );
7080
- const get = fetch2 ?? liveFetch8(opts.quiet === true);
7081
- if (typeof get !== "function") return get;
7082
- const res = await get(fullProfileUrl(memberIdOf(input)), "profile");
7083
- if (!res.ok) return err("profile", res.code, res.message, res.hint);
7084
- const parsed = parseFullProfile(res.json);
7085
- if (!parsed.ok) return err("profile", parsed.code, parsed.message, parsed.hint);
7086
- const p = parsed.profile;
7087
- await readRestOfExperience(get, p);
7088
- if (req.contact === true) await readContact(get, p);
7089
- if (opts.raw === true) return ok("profile", { ...p, raw: res.json });
7090
- if (opts.fields !== void 0 && opts.fields !== "")
7091
- return ok("profile", project([p], opts.fields)[0]);
7092
- return ok("profile", opts.compact === true ? compact(p) : p);
7269
+ function boundKey(form, property) {
7270
+ const ref = form.args.payload[property];
7271
+ return ref?.key;
7093
7272
  }
7094
-
7095
- // src/commands/registry.ts
7096
- var COMMANDS = [
7097
- // ─── local / meta — no network, available today ────────────────────────────
7098
- {
7099
- name: "doctor",
7100
- cost: "free with --offline",
7101
- summary: "Diagnose setup: entry point, cache dir, cookies, cooldown, budget.",
7102
- usage: "lnrelay doctor [--offline]",
7103
- audience: ["cli", "mcp"],
7104
- risk: "local",
7105
- implemented: true
7106
- },
7107
- {
7108
- name: "budget",
7109
- cost: "free",
7110
- summary: "Spend ledger per class, with each cap's provenance. Reset a cooldown here.",
7111
- usage: "lnrelay budget [--reset-cooldown --confirm]",
7112
- audience: ["cli", "mcp"],
7113
- risk: "local",
7114
- implemented: true
7115
- },
7116
- {
7117
- name: "risk",
7118
- cost: "free",
7119
- summary: "Circuit-breaker state. Check this BEFORE spending budget on research.",
7120
- usage: "lnrelay risk",
7121
- audience: ["cli", "mcp"],
7122
- risk: "local",
7123
- implemented: true
7124
- },
7125
- // ─── session ───────────────────────────────────────────────────────────────
7126
- {
7273
+ function currentValue(form, field) {
7274
+ const key = boundKey(form, field.binding);
7275
+ const v = key === void 0 ? void 0 : form.states.get(key)?.value;
7276
+ return typeof v === "string" ? v : void 0;
7277
+ }
7278
+ function topSkills(form) {
7279
+ return (key) => {
7280
+ if (!key.endsWith("ReorderableSkillsFormBindingsskillIdsBinding")) return void 0;
7281
+ const initial = [...form.states.entries()].find(([k]) => k.startsWith("initialSkills"))?.[1];
7282
+ if (initial === void 0) return drift11("the About form carried no initial top skills");
7283
+ if (!Array.isArray(initial.value) || initial.value.length > 0) {
7284
+ return {
7285
+ ok: false,
7286
+ code: "NOT_IMPLEMENTED",
7287
+ message: "your About section has top skills, and saving it with them has not been verified",
7288
+ hint: "Edit About in the browser for now; nothing was changed."
7289
+ };
7290
+ }
7291
+ return { ok: true, value: [] };
7292
+ };
7293
+ }
7294
+ function saveBody(form, field, value) {
7295
+ if (value.length > field.maxLength) {
7296
+ return {
7297
+ ok: false,
7298
+ code: "INVALID_INPUT",
7299
+ message: `the ${field.name} is ${value.length} characters; LinkedIn allows ${field.maxLength}`
7300
+ };
7301
+ }
7302
+ const target2 = boundKey(form, field.binding);
7303
+ const current = target2 === void 0 ? void 0 : form.states.get(target2);
7304
+ if (target2 === void 0 || current === void 0) {
7305
+ return drift11(`the profile form has no ${field.name} field`);
7306
+ }
7307
+ const model = new Map(form.states);
7308
+ model.set(target2, { ...current, value });
7309
+ const states2 = wireStates(keysOf(form.args), model, topSkills(form));
7310
+ if (!Array.isArray(states2)) return states2;
7311
+ return { ok: true, body: requestBody(form.save, form.args, states2, form.screen) };
7312
+ }
7313
+ async function fetchProfileForm(field, vanityName, client) {
7314
+ const stream = await openForm(
7315
+ field.screen,
7316
+ { vanityName, isVanityNameResolved: true },
7317
+ client,
7318
+ `profile-${field.name}-form`
7319
+ );
7320
+ return typeof stream === "string" ? readForm(stream, field) : stream;
7321
+ }
7322
+ async function openForm(screen, payload, client, operation) {
7323
+ const result = await client.request({
7324
+ url: `${NAV_URL}?screenId=${screen}&sduiid=${screen}`,
7325
+ method: "POST",
7326
+ body: navBody(screen, payload),
7327
+ spendClass: "page",
7328
+ operation
7329
+ });
7330
+ if (!result.ok) {
7331
+ const out = { ok: false, code: result.code, message: result.message };
7332
+ if (result.hint !== void 0) out.hint = result.hint;
7333
+ return out;
7334
+ }
7335
+ return result.classification.raw ?? "";
7336
+ }
7337
+ async function sendAction(requestId, body, client, operation, spendClass = "write") {
7338
+ const result = await client.request({
7339
+ url: `${ACTION_URL}?sduiid=${requestId}`,
7340
+ method: "POST",
7341
+ body,
7342
+ spendClass,
7343
+ operation
7344
+ });
7345
+ if (!result.ok) {
7346
+ const out = { ok: false, code: result.code, message: result.message };
7347
+ if (result.hint !== void 0) out.hint = result.hint;
7348
+ return out;
7349
+ }
7350
+ const raw = result.classification.raw ?? "";
7351
+ const errors = responseErrors(raw);
7352
+ if (errors !== null) {
7353
+ return { ok: false, code: "INVALID_INPUT", message: `LinkedIn refused it: ${errors}` };
7354
+ }
7355
+ return raw;
7356
+ }
7357
+ async function sendProfileSave(form, body, client) {
7358
+ const r = await sendAction(form.save, body, client, "profile-save");
7359
+ return typeof r === "string" ? { ok: true } : r;
7360
+ }
7361
+
7362
+ // src/engine/sdui-skill.ts
7363
+ var SKILL = {
7364
+ addScreen: "com.linkedin.sdui.flagshipnav.profile.ProfileSkillAddForm",
7365
+ editScreen: "com.linkedin.sdui.flagshipnav.profile.ProfileSkillDetailsEditForm",
7366
+ listScreen: "com.linkedin.sdui.flagshipnav.profile.ProfileSkillDetails",
7367
+ pager: "com.linkedin.sdui.pagers.profile.details.skills",
7368
+ save: "com.linkedin.sdui.requests.profile.saveProfileSkillForm",
7369
+ delete: "com.linkedin.sdui.requests.profile.deleteProfileSkillForm"
7370
+ };
7371
+ var EDIT_NAV = `{"$type":"proto.sdui.actions.core.NavigateToScreen","screenId":"${SKILL.editScreen}"`;
7372
+ var TEXT4 = /"children":\["((?:[^"\\]|\\.)*)"\]/g;
7373
+ function skillsFromPage(stream) {
7374
+ if (!stream.includes(SKILL.pager) && !stream.includes(EDIT_NAV) && !stream.includes("isPartialPage")) {
7375
+ return drift11("the skills page could not be read");
7376
+ }
7377
+ const skills = [];
7378
+ let from = 0;
7379
+ let i = 0;
7380
+ for (; ; ) {
7381
+ i = stream.indexOf(EDIT_NAV, i);
7382
+ if (i === -1) break;
7383
+ const text6 = balanced(stream, i);
7384
+ const end = i;
7385
+ i += EDIT_NAV.length;
7386
+ if (text6 === null) continue;
7387
+ const payload = JSON.parse(text6).requestedArguments?.payload;
7388
+ const id = payload?.skillId;
7389
+ if (typeof id !== "string" || payload === void 0 || skills.some((s) => s.skillId === id))
7390
+ continue;
7391
+ const names = [...stream.slice(from, end).matchAll(TEXT4)].map(
7392
+ (m) => JSON.parse(`"${m[1]}"`)
7393
+ );
7394
+ skills.push({ skillId: id, name: names.length === 1 ? names[0] ?? null : null, payload });
7395
+ from = end + text6.length;
7396
+ }
7397
+ return { ok: true, skills };
7398
+ }
7399
+ var SKILL_COMPONENT = /"componentKey":"com\.linkedin\.sdui\.profile\.skill\([^)]+\)","children":\["\$","\$L[0-9a-f]+","[^"]+",\{"componentKey":"[^"]+","initialContent":"\$L([0-9a-f]+)"/g;
7400
+ var SKILL_NAME = /"fontSize":"medium","fontStyle":"normal","fontWeight":"bold","lineHeight":"[^"]*","textAlign":"[^"]*","children":\["((?:[^"\\]|\\.)+)"\]/;
7401
+ function skillNamesOf(stream) {
7402
+ const rows = new Rows(stream);
7403
+ return [...stream.matchAll(SKILL_COMPONENT)].flatMap((m) => {
7404
+ const name = rows.reach(m[1]).map((r) => rows.byId.get(r)?.match(SKILL_NAME)?.[1]).find((n) => n !== void 0);
7405
+ return name === void 0 ? [] : [JSON.parse(`"${name}"`)];
7406
+ });
7407
+ }
7408
+ function skillRowsOf(stream) {
7409
+ return [...stream.matchAll(SKILL_COMPONENT)].length;
7410
+ }
7411
+ function listPayloadOf(screen) {
7412
+ const at = screen.indexOf('"filter":"ProfileSkillCategory_ALL"');
7413
+ const open = at === -1 ? -1 : screen.lastIndexOf('"payload":{', at);
7414
+ const text6 = open === -1 ? null : balanced(screen, open + '"payload":'.length);
7415
+ return text6 === null ? null : JSON.parse(text6);
7416
+ }
7417
+ function pagerFrom(payload, start) {
7418
+ const args = {
7419
+ $type: "proto.sdui.actions.requests.RequestedArguments",
7420
+ requestedStateKeys: [],
7421
+ payload: { ...payload, start },
7422
+ requestMetadata: { $type: "proto.sdui.common.RequestMetadata" }
7423
+ };
7424
+ return {
7425
+ pagerId: SKILL.pager,
7426
+ clientArguments: { ...args, states: [], screenId: SKILL.listScreen, knownTemplateIds: [] },
7427
+ paginationRequest: {
7428
+ $type: "proto.sdui.actions.requests.PaginationRequest",
7429
+ pagerId: SKILL.pager,
7430
+ retryCount: 0,
7431
+ requestedArguments: args
7432
+ }
7433
+ };
7434
+ }
7435
+ function readSkillForm(stream) {
7436
+ const model = readModel(stream);
7437
+ if (model === null) return drift11("the skill form carried no initial values");
7438
+ const save = findRequest(stream, SKILL.save);
7439
+ const del = findRequest(stream, SKILL.delete);
7440
+ if (save === null && del === null)
7441
+ return drift11("the skill form carried neither a save nor a delete");
7442
+ return { ok: true, model, save, del, screen: del === null ? SKILL.addScreen : SKILL.editScreen };
7443
+ }
7444
+ var nameKey = (model) => [...model.keys()].find((k) => k.startsWith("addSkillsTypeaheadSkillName"));
7445
+ function skillNameOf(form) {
7446
+ const key = nameKey(form.model);
7447
+ const v = key === void 0 ? void 0 : form.model.get(key)?.value;
7448
+ return typeof v === "string" ? v : null;
7449
+ }
7450
+ function addSkillBody(form, name) {
7451
+ if (name.trim() === "")
7452
+ return { ok: false, code: "INVALID_INPUT", message: "a skill needs a name" };
7453
+ if (form.save === null) return drift11("this form has no save action (it is not the add form)");
7454
+ const key = nameKey(form.model);
7455
+ const current = key === void 0 ? void 0 : form.model.get(key);
7456
+ if (key === void 0 || current === void 0) return drift11("the skill form has no name field");
7457
+ const model = new Map(form.model);
7458
+ model.set(key, { ...current, value: name.trim() });
7459
+ const states2 = wireStates(keysOf(form.save), model, () => void 0);
7460
+ if (!Array.isArray(states2)) return states2;
7461
+ return { ok: true, body: requestBody(SKILL.save, form.save, states2, form.screen) };
7462
+ }
7463
+ function removeSkillBody(form) {
7464
+ if (form.del === null)
7465
+ return drift11("this form has no delete action (it is not an existing skill)");
7466
+ const states2 = wireStates(keysOf(form.del), form.model, () => void 0);
7467
+ if (!Array.isArray(states2)) return states2;
7468
+ return { ok: true, body: requestBody(SKILL.delete, form.del, states2, form.screen) };
7469
+ }
7470
+ var PAGER_URL2 = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${SKILL.pager}`;
7471
+ var MAX_PAGES2 = 10;
7472
+ async function fetchSkills(vanityName, client) {
7473
+ const screen = await openForm(
7474
+ SKILL.listScreen,
7475
+ { vanityName, isVanityNameResolved: true },
7476
+ client,
7477
+ "skills-screen"
7478
+ );
7479
+ if (typeof screen !== "string") return screen;
7480
+ const payload = listPayloadOf(screen);
7481
+ if (payload === null) return drift11("the Skills screen carried no list request");
7482
+ const count3 = typeof payload.count === "number" ? payload.count : 10;
7483
+ const skills = [];
7484
+ for (let page = 0; page < MAX_PAGES2; page++) {
7485
+ const result = await client.request({
7486
+ url: PAGER_URL2,
7487
+ method: "POST",
7488
+ body: pagerFrom(payload, skills.length),
7489
+ spendClass: "page",
7490
+ operation: "skills"
7491
+ });
7492
+ if (!result.ok) return { ok: false, code: result.code, message: result.message };
7493
+ const parsed = skillsFromPage(result.classification.raw ?? "");
7494
+ if (!parsed.ok) return parsed;
7495
+ const fresh = parsed.skills.filter((s) => !skills.some((k) => k.skillId === s.skillId));
7496
+ skills.push(...fresh);
7497
+ if (parsed.skills.length < count3 || fresh.length === 0) break;
7498
+ }
7499
+ return { ok: true, skills };
7500
+ }
7501
+ async function openSkillForm(payload, client, edit2) {
7502
+ const stream = await openForm(
7503
+ edit2 ? SKILL.editScreen : SKILL.addScreen,
7504
+ { ...payload, isVanityNameResolved: true },
7505
+ client,
7506
+ edit2 ? "skill-edit-form" : "skill-add-form"
7507
+ );
7508
+ return typeof stream === "string" ? readSkillForm(stream) : stream;
7509
+ }
7510
+ async function sendSkill(body, requestId, client) {
7511
+ const sent = await sendAction(
7512
+ requestId,
7513
+ body,
7514
+ client,
7515
+ requestId === SKILL.save ? "skill-add" : "skill-remove"
7516
+ );
7517
+ return typeof sent === "string" ? { ok: true } : sent;
7518
+ }
7519
+
7520
+ // src/commands/profile.ts
7521
+ function liveFetch9(quiet) {
7522
+ const session = loadSession();
7523
+ if (session.state !== "ok")
7524
+ return err("profile", "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
7525
+ const client = createLiveClient(session.session, void 0, quiet);
7526
+ return async (url, spendClass, body) => {
7527
+ const r = await client.request({
7528
+ url,
7529
+ ...body !== void 0 ? { method: "POST", body } : {},
7530
+ spendClass,
7531
+ operation: "profile"
7532
+ });
7533
+ if (!r.ok) return r;
7534
+ return { ok: true, json: r.json, raw: r.classification.raw ?? "" };
7535
+ };
7536
+ }
7537
+ function memberIdOf(input) {
7538
+ const s = input.trim();
7539
+ const slug = s.match(/linkedin\.com\/in\/([^/?#]+)/)?.[1];
7540
+ if (slug !== void 0) {
7541
+ try {
7542
+ return decodeURIComponent(slug);
7543
+ } catch {
7544
+ return slug;
7545
+ }
7546
+ }
7547
+ return s.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/)?.[1] ?? s;
7548
+ }
7549
+ async function readRestOfExperience(get, p) {
7550
+ const want = p.counts?.experience;
7551
+ if (want === void 0) return;
7552
+ let start = want.shown;
7553
+ while (start < want.total) {
7554
+ const res = await get(positionsPageUrl(p.urn, start), "profile");
7555
+ const page = res.ok ? parsePositionsPage(res.json) : res;
7556
+ if (!page.ok) {
7557
+ p.experienceError = `${page.code}: ${page.message}`;
7558
+ return;
7559
+ }
7560
+ p.experience = [...p.experience ?? [], ...page.experience];
7561
+ start += page.groups;
7562
+ if (page.groups < POSITIONS_PAGE) break;
7563
+ }
7564
+ const counts2 = { ...p.counts };
7565
+ if (start >= want.total) delete counts2.experience;
7566
+ else counts2.experience = { shown: start, total: want.total };
7567
+ if (Object.keys(counts2).length > 0) p.counts = counts2;
7568
+ else delete p.counts;
7569
+ }
7570
+ async function readContact(get, p) {
7571
+ if (p.publicId === void 0 || p.firstName === void 0) {
7572
+ p.contactError = "NOT_FOUND: the profile has no public id or name to ask with";
7573
+ return;
7574
+ }
7575
+ const body = contactInfoBody(p.publicId, p.firstName, p.lastName ?? "");
7576
+ const res = await get(CONTACT_INFO_URL, "profile", body);
7577
+ const read = res.ok ? parseContactInfo(res.raw ?? "") : res;
7578
+ if (read.ok) p.contact = read.contact;
7579
+ else p.contactError = `${read.code}: ${read.message}`;
7580
+ }
7581
+ var SKILL_PAGES = 10;
7582
+ async function readAllSkills(get, p) {
7583
+ const fail2 = (code, message) => {
7584
+ p.skillsError = `${code}: ${message}`;
7585
+ };
7586
+ if (p.publicId === void 0)
7587
+ return fail2("NOT_FOUND", "the profile has no public id to ask with");
7588
+ const screen = SKILL.listScreen;
7589
+ const nav = await get(
7590
+ `${NAV_URL}?screenId=${screen}&sduiid=${screen}`,
7591
+ "page",
7592
+ navBody(screen, { vanityName: p.publicId, isVanityNameResolved: true })
7593
+ );
7594
+ if (!nav.ok) return fail2(nav.code, nav.message);
7595
+ const payload = listPayloadOf(nav.raw ?? "");
7596
+ if (payload === null) return fail2("SCHEMA_DRIFT", "the Skills screen carried no list request");
7597
+ const count3 = typeof payload.count === "number" ? payload.count : 10;
7598
+ const total = p.counts?.skills?.total;
7599
+ const skills = [];
7600
+ let start = 0;
7601
+ for (let page = 0; page < SKILL_PAGES; page++) {
7602
+ const res = await get(PAGER_URL2, "page", pagerFrom(payload, start));
7603
+ if (!res.ok) return fail2(res.code, res.message);
7604
+ const rows = skillRowsOf(res.raw ?? "");
7605
+ const names = skillNamesOf(res.raw ?? "");
7606
+ if (rows > names.length)
7607
+ return fail2("SCHEMA_DRIFT", `${rows} skills were shown, ${names.length} read`);
7608
+ skills.push(...names);
7609
+ start += rows;
7610
+ if (rows < count3 || total !== void 0 && start >= total) break;
7611
+ }
7612
+ if (skills.length === 0) return fail2("SCHEMA_DRIFT", "the skills list held no skills");
7613
+ p.skills = skills;
7614
+ const counts2 = { ...p.counts };
7615
+ if (total === void 0 || skills.length >= total) delete counts2.skills;
7616
+ else counts2.skills = { shown: skills.length, total };
7617
+ if (Object.keys(counts2).length > 0) p.counts = counts2;
7618
+ else delete p.counts;
7619
+ }
7620
+ var RECOMMENDATION_PAGES = 10;
7621
+ async function readRecommendations(get, p) {
7622
+ if (p.publicId === void 0) {
7623
+ p.recommendationsError = "NOT_FOUND: the profile has no public id to ask with";
7624
+ return;
7625
+ }
7626
+ const out = { received: [], given: [] };
7627
+ for (const kind of ["received", "given"]) {
7628
+ for (let page = 0; page < RECOMMENDATION_PAGES; page++) {
7629
+ const body = recommendationsBody(kind, p.publicId, p.id, out[kind].length);
7630
+ const res = await get(RECOMMENDATIONS_URL, "page", body);
7631
+ const read = res.ok ? parseRecommendations(res.raw ?? "") : res;
7632
+ if (!read.ok) {
7633
+ p.recommendationsError = `${read.code}: ${read.message}`;
7634
+ return;
7635
+ }
7636
+ out[kind].push(...read.items);
7637
+ if (read.items.length < RECOMMENDATIONS_PAGE) break;
7638
+ }
7639
+ }
7640
+ p.recommendations = out;
7641
+ }
7642
+ async function readPosts(get, p, n, compact2) {
7643
+ const r = await runPostsSearch(
7644
+ { from: [p.id], sort: "recent", limit: n },
7645
+ compact2 ? { compact: true } : {},
7646
+ async (url, body) => {
7647
+ const res = await get(url, "search", body);
7648
+ return res.ok ? { ok: true, raw: res.raw ?? "" } : res;
7649
+ }
7650
+ );
7651
+ if (r.ok) p.posts = r.data.items;
7652
+ else p.postsError = `${r.error.code}: ${r.error.message}`;
7653
+ }
7654
+ var span = (x) => x.start === void 0 && x.end === void 0 ? void 0 : `${x.start ?? "?"} \u2013 ${x.current === true ? "now" : x.end ?? "?"}`;
7655
+ var roleLine = (r) => line([r.title, r.company, span(r), r.employmentType, r.location]);
7656
+ var schoolLine = (s) => line([s.school, s.degree, s.field, span(s)]);
7657
+ var entryLine = (e) => {
7658
+ const { description: _d, url, ...rest } = e;
7659
+ const dates = span(e);
7660
+ const fields = Object.entries(rest).filter(([k, v]) => !["start", "end", "current"].includes(k) && typeof v === "string").map(([, v]) => v);
7661
+ return line([...fields, dates, typeof url === "string" ? url : void 0]);
7662
+ };
7663
+ var LISTS2 = [
7664
+ "certifications",
7665
+ "languages",
7666
+ "honors",
7667
+ "publications",
7668
+ "projects",
7669
+ "volunteering",
7670
+ "courses",
7671
+ "organizations",
7672
+ "patents",
7673
+ "testScores"
7674
+ ];
7675
+ function compact(p) {
7676
+ const out = { ...p };
7677
+ if (p.experience !== void 0) out.experience = p.experience.map(roleLine);
7678
+ if (p.education !== void 0) out.education = p.education.map(schoolLine);
7679
+ for (const key of LISTS2) {
7680
+ const rows = p[key];
7681
+ if (rows !== void 0) out[key] = rows.map(entryLine);
7682
+ }
7683
+ return out;
7684
+ }
7685
+ async function runProfile(input, opts = {}, fetch2, req = {}) {
7686
+ if (input === void 0 || input.trim() === "")
7687
+ return err(
7688
+ "profile",
7689
+ "INVALID_INPUT",
7690
+ "a public id, profile URL or urn is required",
7691
+ "lnrelay profile <public-id|url|urn>"
7692
+ );
7693
+ const get = fetch2 ?? liveFetch9(opts.quiet === true);
7694
+ if (typeof get !== "function") return get;
7695
+ const res = await get(fullProfileUrl(memberIdOf(input)), "profile");
7696
+ if (!res.ok) return err("profile", res.code, res.message, res.hint);
7697
+ const parsed = parseFullProfile(res.json);
7698
+ if (!parsed.ok) return err("profile", parsed.code, parsed.message, parsed.hint);
7699
+ const p = parsed.profile;
7700
+ await readRestOfExperience(get, p);
7701
+ if (req.skills === true) await readAllSkills(get, p);
7702
+ if (req.recommendations === true) await readRecommendations(get, p);
7703
+ if (req.contact === true) await readContact(get, p);
7704
+ if (req.posts !== void 0 && req.posts > 0)
7705
+ await readPosts(get, p, req.posts, opts.compact === true);
7706
+ if (opts.raw === true) return ok("profile", { ...p, raw: res.json });
7707
+ if (opts.fields !== void 0 && opts.fields !== "")
7708
+ return ok("profile", project([p], opts.fields)[0]);
7709
+ return ok("profile", opts.compact === true ? compact(p) : p);
7710
+ }
7711
+
7712
+ // src/commands/registry.ts
7713
+ var COMMANDS = [
7714
+ // ─── local / meta — no network, available today ────────────────────────────
7715
+ {
7716
+ name: "doctor",
7717
+ cost: "free with --offline",
7718
+ summary: "Diagnose setup: entry point, cache dir, cookies, cooldown, budget.",
7719
+ usage: "lnrelay doctor [--offline]",
7720
+ audience: ["cli", "mcp"],
7721
+ risk: "local",
7722
+ implemented: true
7723
+ },
7724
+ {
7725
+ name: "budget",
7726
+ cost: "free",
7727
+ summary: "Spend ledger per class, with each cap's provenance. Reset a cooldown here.",
7728
+ usage: "lnrelay budget [--reset-cooldown --confirm]",
7729
+ audience: ["cli", "mcp"],
7730
+ risk: "local",
7731
+ implemented: true
7732
+ },
7733
+ {
7734
+ name: "risk",
7735
+ cost: "free",
7736
+ summary: "Circuit-breaker state. Check this BEFORE spending budget on research.",
7737
+ usage: "lnrelay risk",
7738
+ audience: ["cli", "mcp"],
7739
+ risk: "local",
7740
+ implemented: true
7741
+ },
7742
+ // ─── session ───────────────────────────────────────────────────────────────
7743
+ {
7127
7744
  name: "login",
7128
7745
  cost: "free \u2014 local browser",
7129
7746
  summary: "Mint a session from a logged-in Chrome via DevTools. Stores cookies owner-only.",
@@ -7144,9 +7761,9 @@ var COMMANDS = [
7144
7761
  },
7145
7762
  {
7146
7763
  name: "profile",
7147
- cost: "1 profile read (+1 per 50 companies past the first 10; --contact +1)",
7148
- summary: "A profile in full: name, headline, about, every role with dates and descriptions, education, skills, honors, publications, volunteering and the other sections. --contact adds contact info: email, websites, phone, birthday, connected since.",
7149
- usage: "lnrelay profile <public-id|profile-id|urn|url> [--contact] [--compact | --fields a,b,c] [--raw]",
7764
+ cost: "1 profile read (+1 per 50 companies past the first 10; --contact +1; --posts +1 search; --skills +1 page per 10; --recommendations +2 pages)",
7765
+ summary: "A profile in full: name, headline, about, every role with dates and descriptions, education, skills, honors, publications, volunteering and the other sections. --contact adds contact info: email, websites, phone, birthday, connected since. --posts N adds their N newest posts; --skills reads every skill past the top 20; --recommendations adds those they received and gave.",
7766
+ usage: "lnrelay profile <public-id|profile-id|urn|url> [--contact] [--posts N] [--skills]\n [--recommendations]\n [--compact | --fields a,b,c] [--raw]",
7150
7767
  audience: ["cli", "mcp"],
7151
7768
  risk: "read",
7152
7769
  implemented: true
@@ -7305,6 +7922,15 @@ var COMMANDS = [
7305
7922
  risk: "read",
7306
7923
  implemented: true
7307
7924
  },
7925
+ {
7926
+ name: "notifications",
7927
+ cost: "1 page call per 25",
7928
+ summary: "Your notifications, newest first: what each says, when, read or not, where it goes and who it is about. Reading them here does not mark them seen.",
7929
+ usage: "lnrelay notifications [--unread] [--limit N] [--compact | --fields a,b,c]",
7930
+ audience: ["cli", "mcp"],
7931
+ risk: "read",
7932
+ implemented: true
7933
+ },
7308
7934
  {
7309
7935
  name: "viewers",
7310
7936
  cost: "2 page calls",
@@ -7442,210 +8068,83 @@ var COMMANDS = [
7442
8068
  implemented: true
7443
8069
  },
7444
8070
  {
7445
- name: "comment",
7446
- cost: "1 call \u2014 write",
7447
- summary: "Add a comment to a post. Harvests its binding tokens from the rendered page; no browser needed, but it costs one heavy read.",
7448
- usage: 'lnrelay comment <activity-urn> "<text>"\n Fetches the post page (~2.8 MB) to harvest a binding key and trackingId, and proves\n the key belongs to that post before asking. To change a comment, see `edit`.',
7449
- audience: ["cli"],
7450
- risk: "write",
7451
- implemented: true
7452
- },
7453
- {
7454
- name: "delete",
7455
- cost: "1 read + 1 write",
7456
- summary: "Delete one of your own posts or comments. Reads a post back and shows its text first \u2014 this is the one action that cannot be undone.",
7457
- usage: "lnrelay delete <activity-urn> # a post; shows you its text before destroying it\n lnrelay delete <comment-urn> # a comment; the server decides if you may",
7458
- audience: ["cli"],
7459
- risk: "write",
7460
- implemented: true
7461
- },
7462
- {
7463
- name: "reply",
7464
- cost: "1 read + 1 write",
7465
- summary: "Reply to a comment, nested under it. Goes over Voyager \u2014 a different endpoint from commenting, with the parent named in threadUrn.",
7466
- usage: 'lnrelay reply <comment-urn> "<text>"',
7467
- audience: ["cli"],
7468
- risk: "write",
7469
- implemented: true
7470
- },
7471
- {
7472
- name: "edit",
7473
- cost: "1 read + 1 write",
7474
- summary: "Change the text of a comment or post you wrote, or your profile headline or About. Its own verb, so a comment urn can never be mistaken for something to comment ON.",
7475
- usage: 'lnrelay edit <comment-urn | share-urn | ugcPost-urn> "<text>"\n lnrelay edit headline|about ("<text>" | --file <path>)\n A post is edited by the urn it was created as (`share` prints it; `my-posts` lists\n it as shareUrn), not its activity urn. The whole text is replaced. A profile edit\n shows the current text beside the new one, sends every other profile field back as\n LinkedIn holds it, and reads the profile back to confirm. Headline max 220 characters.',
7476
- audience: ["cli"],
7477
- risk: "write",
7478
- implemented: true
7479
- },
7480
- {
7481
- name: "role",
7482
- cost: "3-4 reads + 1 write",
7483
- summary: "Add, edit or remove a role in your Experience. Never rewrites your headline; notify network is off unless --notify.",
7484
- usage: 'lnrelay role add --title "<t>" --company "<c>" --start YYYY-MM [--end YYYY-MM | --current]\n [--location "<l>"] [--description "<d>" | --description-file <path>] [--notify]\n lnrelay role edit <position-id> [any of the flags above]\n lnrelay role remove <position-id>\n Position ids come from `lnrelay experience`. The preview shows the role as it is and\n as it will be; the result is read back from the profile. A role with media attached\n is refused. The company is free text (not linked to a company page).',
7485
- audience: ["cli"],
7486
- risk: "write",
7487
- implemented: true
7488
- },
7489
- {
7490
- name: "skill",
7491
- cost: "4-5 reads + 1 write",
7492
- summary: "Add a skill to your profile, or remove one.",
7493
- usage: 'lnrelay skill add "<name>"\n lnrelay skill remove <skill-id>\n Skill ids come from `lnrelay skills`. A skill is added as free text, linked to no role,\n school or project. Removing a skill removes its endorsements with it.',
7494
- audience: ["cli"],
7495
- risk: "write",
7496
- implemented: true
7497
- },
7498
- {
7499
- name: "react",
7500
- cost: "1 call \u2014 write",
7501
- summary: "React to a post or comment, over LinkedIn's SDUI surface. Reversible with --remove.",
7502
- usage: "lnrelay react <activity-urn | comment-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION|ENTERTAINMENT]\n lnrelay react <urn> --remove # take the reaction back",
7503
- audience: ["cli"],
7504
- risk: "write",
7505
- implemented: true
7506
- }
7507
- ];
7508
- var commandNames = COMMANDS.map((c) => c.name);
7509
- function findCommand(name) {
7510
- return COMMANDS.find((c) => c.name === name);
7511
- }
7512
- function helpText() {
7513
- const lines = ["lnrelay \u2014 deep research over LinkedIn from your own account", "", "Commands:"];
7514
- const width = Math.max(...commandNames.map((n) => n.length));
7515
- for (const c of COMMANDS) {
7516
- const flag = c.implemented ? " " : "\xB7";
7517
- lines.push(` ${flag} ${c.name.padEnd(width)} ${c.summary} [${c.cost}]`);
7518
- }
7519
- lines.push("", " \xB7 = specified in docs/DESIGN.md, not yet implemented");
7520
- lines.push("", "Run `lnrelay <command> --help` for usage.");
7521
- return lines.join("\n");
7522
- }
7523
-
7524
- // src/engine/sdui-profile.ts
7525
- var NAV_URL = "https://www.linkedin.com/flagship-web/rsc-action/actions/navigation";
7526
- var ACTION_URL = "https://www.linkedin.com/flagship-web/rsc-action/actions/server-request";
7527
- var PROFILE_FIELDS = {
7528
- headline: {
7529
- name: "headline",
7530
- screen: "com.linkedin.sdui.flagshipnav.profile.ProfileEditIntroForm",
7531
- save: "com.linkedin.sdui.requests.profile.saveProfileIntroForm",
7532
- binding: "headline",
7533
- // The web form refuses more ("Exceeded maximum length of 220 characters").
7534
- maxLength: 220
7535
- },
7536
- about: {
7537
- name: "about",
7538
- screen: "com.linkedin.sdui.flagshipnav.profile.ProfileAboutForm",
7539
- save: "com.linkedin.sdui.requests.profile.saveProfileAboutForm",
7540
- binding: "about",
7541
- maxLength: 2600
7542
- }
7543
- };
7544
- var drift9 = (message) => ({
7545
- ok: false,
7546
- code: "SCHEMA_DRIFT",
7547
- message,
7548
- hint: "Re-capture the profile form with scripts/observe-write.ts (edit one character, then revert)."
7549
- });
7550
- function readForm(stream, field) {
7551
- const states2 = readModel(stream);
7552
- if (states2 === null) return drift9("the profile form carried no initial values");
7553
- const args = findRequest(stream, field.save);
7554
- if (args === null)
7555
- return drift9(`the profile form carried no ${field.save.split(".").pop()} action`);
7556
- return { ok: true, args, states: states2, screen: field.screen, save: field.save };
7557
- }
7558
- function boundKey(form, property) {
7559
- const ref = form.args.payload[property];
7560
- return ref?.key;
7561
- }
7562
- function currentValue(form, field) {
7563
- const key = boundKey(form, field.binding);
7564
- const v = key === void 0 ? void 0 : form.states.get(key)?.value;
7565
- return typeof v === "string" ? v : void 0;
7566
- }
7567
- function topSkills(form) {
7568
- return (key) => {
7569
- if (!key.endsWith("ReorderableSkillsFormBindingsskillIdsBinding")) return void 0;
7570
- const initial = [...form.states.entries()].find(([k]) => k.startsWith("initialSkills"))?.[1];
7571
- if (initial === void 0) return drift9("the About form carried no initial top skills");
7572
- if (!Array.isArray(initial.value) || initial.value.length > 0) {
7573
- return {
7574
- ok: false,
7575
- code: "NOT_IMPLEMENTED",
7576
- message: "your About section has top skills, and saving it with them has not been verified",
7577
- hint: "Edit About in the browser for now; nothing was changed."
7578
- };
7579
- }
7580
- return { ok: true, value: [] };
7581
- };
7582
- }
7583
- function saveBody(form, field, value) {
7584
- if (value.length > field.maxLength) {
7585
- return {
7586
- ok: false,
7587
- code: "INVALID_INPUT",
7588
- message: `the ${field.name} is ${value.length} characters; LinkedIn allows ${field.maxLength}`
7589
- };
7590
- }
7591
- const target2 = boundKey(form, field.binding);
7592
- const current = target2 === void 0 ? void 0 : form.states.get(target2);
7593
- if (target2 === void 0 || current === void 0) {
7594
- return drift9(`the profile form has no ${field.name} field`);
7595
- }
7596
- const model = new Map(form.states);
7597
- model.set(target2, { ...current, value });
7598
- const states2 = wireStates(keysOf(form.args), model, topSkills(form));
7599
- if (!Array.isArray(states2)) return states2;
7600
- return { ok: true, body: requestBody(form.save, form.args, states2, form.screen) };
7601
- }
7602
- async function fetchProfileForm(field, vanityName, client) {
7603
- const stream = await openForm(
7604
- field.screen,
7605
- { vanityName, isVanityNameResolved: true },
7606
- client,
7607
- `profile-${field.name}-form`
7608
- );
7609
- return typeof stream === "string" ? readForm(stream, field) : stream;
7610
- }
7611
- async function openForm(screen, payload, client, operation) {
7612
- const result = await client.request({
7613
- url: `${NAV_URL}?screenId=${screen}&sduiid=${screen}`,
7614
- method: "POST",
7615
- body: navBody(screen, payload),
7616
- spendClass: "page",
7617
- operation
7618
- });
7619
- if (!result.ok) {
7620
- const out = { ok: false, code: result.code, message: result.message };
7621
- if (result.hint !== void 0) out.hint = result.hint;
7622
- return out;
8071
+ name: "comment",
8072
+ cost: "1 call \u2014 write",
8073
+ summary: "Add a comment to a post. Harvests its binding tokens from the rendered page; no browser needed, but it costs one heavy read.",
8074
+ usage: 'lnrelay comment <activity-urn> "<text>"\n Fetches the post page (~2.8 MB) to harvest a binding key and trackingId, and proves\n the key belongs to that post before asking. To change a comment, see `edit`.',
8075
+ audience: ["cli"],
8076
+ risk: "write",
8077
+ implemented: true
8078
+ },
8079
+ {
8080
+ name: "delete",
8081
+ cost: "1 read + 1 write",
8082
+ summary: "Delete one of your own posts or comments. Reads a post back and shows its text first \u2014 this is the one action that cannot be undone.",
8083
+ usage: "lnrelay delete <activity-urn> # a post; shows you its text before destroying it\n lnrelay delete <comment-urn> # a comment; the server decides if you may",
8084
+ audience: ["cli"],
8085
+ risk: "write",
8086
+ implemented: true
8087
+ },
8088
+ {
8089
+ name: "reply",
8090
+ cost: "1 read + 1 write",
8091
+ summary: "Reply to a comment, nested under it. Goes over Voyager \u2014 a different endpoint from commenting, with the parent named in threadUrn.",
8092
+ usage: 'lnrelay reply <comment-urn> "<text>"',
8093
+ audience: ["cli"],
8094
+ risk: "write",
8095
+ implemented: true
8096
+ },
8097
+ {
8098
+ name: "edit",
8099
+ cost: "1 read + 1 write",
8100
+ summary: "Change the text of a comment or post you wrote, your profile headline or About, or your profile photo or cover image. Its own verb, so a comment urn can never be mistaken for something to comment ON.",
8101
+ usage: 'lnrelay edit <comment-urn | share-urn | ugcPost-urn> "<text>"\n lnrelay edit headline|about ("<text>" | --file <path>)\n lnrelay edit photo|banner <image.png|jpg> (photo square, banner 4:1, max 8 MB)\n A post is edited by the urn it was created as (`share` prints it; `my-posts` lists\n it as shareUrn), not its activity urn. The whole text is replaced. A profile edit\n shows the current text beside the new one, sends every other profile field back as\n LinkedIn holds it, and reads the profile back to confirm. Headline max 220 characters.\n An image is uploaded as it is, uncropped, and read back: it must be the one showing.',
8102
+ audience: ["cli"],
8103
+ risk: "write",
8104
+ implemented: true
8105
+ },
8106
+ {
8107
+ name: "role",
8108
+ cost: "3-4 reads + 1 write",
8109
+ summary: "Add, edit or remove a role in your Experience. Never rewrites your headline; notify network is off unless --notify.",
8110
+ usage: 'lnrelay role add --title "<t>" --company "<c>" --start YYYY-MM [--end YYYY-MM | --current]\n [--location "<l>"] [--description "<d>" | --description-file <path>] [--notify]\n lnrelay role edit <position-id> [any of the flags above]\n lnrelay role remove <position-id>\n Position ids come from `lnrelay experience`. The preview shows the role as it is and\n as it will be; the result is read back from the profile. A role with media attached\n is refused. The company is free text (not linked to a company page).',
8111
+ audience: ["cli"],
8112
+ risk: "write",
8113
+ implemented: true
8114
+ },
8115
+ {
8116
+ name: "skill",
8117
+ cost: "4-5 reads + 1 write",
8118
+ summary: "Add a skill to your profile, or remove one.",
8119
+ usage: 'lnrelay skill add "<name>"\n lnrelay skill remove <skill-id>\n Skill ids come from `lnrelay skills`. A skill is added as free text, linked to no role,\n school or project. Removing a skill removes its endorsements with it.',
8120
+ audience: ["cli"],
8121
+ risk: "write",
8122
+ implemented: true
8123
+ },
8124
+ {
8125
+ name: "react",
8126
+ cost: "1 call \u2014 write",
8127
+ summary: "React to a post or comment, over LinkedIn's SDUI surface. Reversible with --remove.",
8128
+ usage: "lnrelay react <activity-urn | comment-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION|ENTERTAINMENT]\n lnrelay react <urn> --remove # take the reaction back",
8129
+ audience: ["cli"],
8130
+ risk: "write",
8131
+ implemented: true
7623
8132
  }
7624
- return result.classification.raw ?? "";
8133
+ ];
8134
+ var commandNames = COMMANDS.map((c) => c.name);
8135
+ function findCommand(name) {
8136
+ return COMMANDS.find((c) => c.name === name);
7625
8137
  }
7626
- async function sendAction(requestId, body, client, operation, spendClass = "write") {
7627
- const result = await client.request({
7628
- url: `${ACTION_URL}?sduiid=${requestId}`,
7629
- method: "POST",
7630
- body,
7631
- spendClass,
7632
- operation
7633
- });
7634
- if (!result.ok) {
7635
- const out = { ok: false, code: result.code, message: result.message };
7636
- if (result.hint !== void 0) out.hint = result.hint;
7637
- return out;
7638
- }
7639
- const raw = result.classification.raw ?? "";
7640
- const errors = responseErrors(raw);
7641
- if (errors !== null) {
7642
- return { ok: false, code: "INVALID_INPUT", message: `LinkedIn refused it: ${errors}` };
8138
+ function helpText() {
8139
+ const lines = ["lnrelay \u2014 deep research over LinkedIn from your own account", "", "Commands:"];
8140
+ const width = Math.max(...commandNames.map((n) => n.length));
8141
+ for (const c of COMMANDS) {
8142
+ const flag = c.implemented ? " " : "\xB7";
8143
+ lines.push(` ${flag} ${c.name.padEnd(width)} ${c.summary} [${c.cost}]`);
7643
8144
  }
7644
- return raw;
7645
- }
7646
- async function sendProfileSave(form, body, client) {
7647
- const r = await sendAction(form.save, body, client, "profile-save");
7648
- return typeof r === "string" ? { ok: true } : r;
8145
+ lines.push("", " \xB7 = specified in docs/DESIGN.md, not yet implemented");
8146
+ lines.push("", "Run `lnrelay <command> --help` for usage.");
8147
+ return lines.join("\n");
7649
8148
  }
7650
8149
 
7651
8150
  // src/engine/sdui-position.ts
@@ -7657,19 +8156,19 @@ var POSITION = {
7657
8156
  save: "com.linkedin.sdui.requests.profile.saveProfilePositionForm",
7658
8157
  delete: "com.linkedin.sdui.requests.profile.deleteProfilePositionForm"
7659
8158
  };
7660
- var EDIT_NAV = `{"$type":"proto.sdui.actions.core.NavigateToScreen","screenId":"${POSITION.editScreen}"`;
8159
+ var EDIT_NAV2 = `{"$type":"proto.sdui.actions.core.NavigateToScreen","screenId":"${POSITION.editScreen}"`;
7661
8160
  function listPositions(stream) {
7662
- if (readModel(stream) === null && !stream.includes(EDIT_NAV) && !stream.includes('"rows"')) {
7663
- return drift9("the Experience screen could not be read");
8161
+ if (readModel(stream) === null && !stream.includes(EDIT_NAV2) && !stream.includes('"rows"')) {
8162
+ return drift11("the Experience screen could not be read");
7664
8163
  }
7665
8164
  const positions = [];
7666
8165
  const seen = /* @__PURE__ */ new Set();
7667
8166
  let i = 0;
7668
8167
  for (; ; ) {
7669
- i = stream.indexOf(EDIT_NAV, i);
8168
+ i = stream.indexOf(EDIT_NAV2, i);
7670
8169
  if (i === -1) break;
7671
8170
  const text6 = balanced(stream, i);
7672
- i += EDIT_NAV.length;
8171
+ i += EDIT_NAV2.length;
7673
8172
  if (text6 === null) continue;
7674
8173
  const payload = JSON.parse(text6).requestedArguments?.payload;
7675
8174
  const id = payload?.positionId;
@@ -7678,17 +8177,17 @@ function listPositions(stream) {
7678
8177
  positions.push({ positionId: id, title: String(payload.title ?? ""), payload });
7679
8178
  }
7680
8179
  if (positions.length === 0 && !stream.includes('"rows"') && !stream.includes("Experience")) {
7681
- return drift9("the Experience screen listed no roles and did not look like one");
8180
+ return drift11("the Experience screen listed no roles and did not look like one");
7682
8181
  }
7683
8182
  return { ok: true, positions };
7684
8183
  }
7685
8184
  function readPositionForm(stream) {
7686
8185
  const model = readModel(stream);
7687
- if (model === null) return drift9("the position form carried no initial values");
8186
+ if (model === null) return drift11("the position form carried no initial values");
7688
8187
  const media = findRequest(stream, POSITION.media);
7689
8188
  const prefix = media?.payload.formIdPrefix;
7690
8189
  if (media === null || typeof prefix !== "string") {
7691
- return drift9("the position form carried no save step (uploadPositionMedia)");
8190
+ return drift11("the position form carried no save step (uploadPositionMedia)");
7692
8191
  }
7693
8192
  const del = findRequest(stream, POSITION.delete);
7694
8193
  return {
@@ -7739,7 +8238,7 @@ function applyChanges(form, changes) {
7739
8238
  }
7740
8239
  need("dynamicallyCreateHeadline", false);
7741
8240
  need("allowProfileEditBroadcasts", changes.notify === true);
7742
- if (missing.length > 0) return drift9(`the position form has no ${missing.join(", ")} field`);
8241
+ if (missing.length > 0) return drift11(`the position form has no ${missing.join(", ")} field`);
7743
8242
  const s = roleSummary(model);
7744
8243
  if (!s.current && s.start !== null && s.end !== null && s.end < s.start) {
7745
8244
  return {
@@ -7784,7 +8283,7 @@ function mediaBody(form, model) {
7784
8283
  }
7785
8284
  function saveFromReply(reply) {
7786
8285
  const args = findRequest(reply, POSITION.save);
7787
- return args === null ? drift9("the media step did not hand back the save action") : { ok: true, args };
8286
+ return args === null ? drift11("the media step did not hand back the save action") : { ok: true, args };
7788
8287
  }
7789
8288
  function positionSaveBody(save, model, screen) {
7790
8289
  const sending = new Map(model);
@@ -7796,7 +8295,7 @@ function positionSaveBody(save, model, screen) {
7796
8295
  }
7797
8296
  function deleteBody(form) {
7798
8297
  if (form.del === null)
7799
- return drift9("this form has no delete action (it is not an existing role)");
8298
+ return drift11("this form has no delete action (it is not an existing role)");
7800
8299
  const states2 = wireStates(keysOf(form.del), form.model, resolver);
7801
8300
  if (!Array.isArray(states2)) return states2;
7802
8301
  return { ok: true, body: requestBody(POSITION.delete, form.del, states2, form.screen) };
@@ -7839,8 +8338,8 @@ async function sendPositionDelete(form, client) {
7839
8338
  }
7840
8339
 
7841
8340
  // src/commands/write.ts
7842
- import { readFileSync as readFileSync3, statSync } from "fs";
7843
- import { basename } from "path";
8341
+ import { readFileSync as readFileSync4, statSync as statSync2 } from "fs";
8342
+ import { basename as basename2 } from "path";
7844
8343
 
7845
8344
  // src/engine/oauth-write.ts
7846
8345
  var API = "https://api.linkedin.com";
@@ -7975,7 +8474,7 @@ function states(text6, body) {
7975
8474
  function commentBody(activityId, text6, tokens, feedType) {
7976
8475
  const body = keyBody(tokens.bindingKey);
7977
8476
  const activityUrn = { activityUrn: { activityId } };
7978
- const binding = (prefix) => ({
8477
+ const binding2 = (prefix) => ({
7979
8478
  key: stateKey(prefix, body),
7980
8479
  namespace: "MemoryNamespace"
7981
8480
  });
@@ -7995,11 +8494,11 @@ function commentBody(activityId, text6, tokens, feedType) {
7995
8494
  },
7996
8495
  threadUrn: { threadUrnActivityThreadUrn: activityUrn }
7997
8496
  },
7998
- commentFieldBinding: binding("commentBoxText"),
7999
- richCommentFieldBinding: binding("richCommentBoxText"),
8000
- linkPreviewIngestedContentId: binding("commentBoxLinkPreviewIngestedContentId"),
8001
- externalImageUrl: binding("commentBoxExternalImageUrl"),
8002
- externalImageId: binding("commentBoxExternalImageId")
8497
+ commentFieldBinding: binding2("commentBoxText"),
8498
+ richCommentFieldBinding: binding2("richCommentBoxText"),
8499
+ linkPreviewIngestedContentId: binding2("commentBoxLinkPreviewIngestedContentId"),
8500
+ externalImageUrl: binding2("commentBoxExternalImageUrl"),
8501
+ externalImageId: binding2("commentBoxExternalImageId")
8003
8502
  };
8004
8503
  const requestedStateKeys = STATE_PREFIXES.map((p) => ({
8005
8504
  key: { value: { $case: "id", id: stateKey(p, body) } }
@@ -8129,81 +8628,538 @@ function sduiBody(op, target2, reaction) {
8129
8628
  requestMetadata: { $type: "proto.sdui.common.RequestMetadata" }
8130
8629
  };
8131
8630
  return {
8132
- requestId,
8133
- serverRequest: {
8134
- requestId,
8135
- requestedArguments: args,
8136
- isApfcEnabled: false,
8137
- isStreaming: false,
8138
- rumPageKey: ""
8631
+ requestId,
8632
+ serverRequest: {
8633
+ requestId,
8634
+ requestedArguments: args,
8635
+ isApfcEnabled: false,
8636
+ isStreaming: false,
8637
+ rumPageKey: ""
8638
+ },
8639
+ states: [],
8640
+ requestedArguments: {
8641
+ ...args,
8642
+ states: [],
8643
+ screenId: SCREEN_ID4,
8644
+ knownTemplateIds: []
8645
+ }
8646
+ };
8647
+ }
8648
+ async function react(confirmed, client) {
8649
+ const { urn, type, remove } = confirmed.payload;
8650
+ let target2;
8651
+ try {
8652
+ target2 = targetFor(urn);
8653
+ } catch (e) {
8654
+ return { ok: false, code: "INVALID_INPUT", message: e.message };
8655
+ }
8656
+ const op = remove ? "delete" : "create";
8657
+ const result = await client.request({
8658
+ url: reactionUrl(op),
8659
+ method: "POST",
8660
+ body: sduiBody(op, target2, type),
8661
+ spendClass: "write",
8662
+ operation: `reaction.${op}`
8663
+ });
8664
+ if (result.ok) return { ok: true, id: urn };
8665
+ const out = { ok: false, code: result.code, message: result.message };
8666
+ out.hint = result.hint ?? "This surface was captured from the live client but has never been replayed by this tool. If it refuses, the first thing to try is sending `x-li-page-instance` and `x-li-track`, which the browser sends here and which our verified read header set deliberately omits.";
8667
+ return out;
8668
+ }
8669
+
8670
+ // src/engine/voyager-reply.ts
8671
+ var REPLY_DECORATION = "com.linkedin.voyager.dash.deco.social.NormComment-43";
8672
+ var REPLY_URL = `https://www.linkedin.com/voyager/api/voyagerSocialDashNormComments?decorationId=${REPLY_DECORATION}`;
8673
+ function parentThreadUrn(ref) {
8674
+ return `urn:li:comment:(${ref.threadType}:${ref.activityId},${ref.commentId})`;
8675
+ }
8676
+ function replyBody(ref, text6) {
8677
+ return {
8678
+ commentary: {
8679
+ text: text6,
8680
+ // The captured reply carried a profileMention, because LinkedIn's UI
8681
+ // pre-fills "@Author " into the box. We send none: an @mention notifies a
8682
+ // real person, and inventing one would put words — and a notification —
8683
+ // where the user did not ask for them.
8684
+ attributesV2: [],
8685
+ $type: "com.linkedin.voyager.dash.common.text.TextViewModel"
8686
+ },
8687
+ threadUrn: parentThreadUrn(ref)
8688
+ };
8689
+ }
8690
+ async function replyToComment(confirmed, client) {
8691
+ const { ref, text: text6 } = confirmed.payload;
8692
+ const result = await client.request({
8693
+ url: REPLY_URL,
8694
+ method: "POST",
8695
+ body: replyBody(ref, text6),
8696
+ spendClass: "write",
8697
+ operation: "reply"
8698
+ });
8699
+ if (!result.ok) {
8700
+ const out = { ok: false, code: result.code, message: result.message };
8701
+ out.hint = /5\d\d|unexpected status/.test(result.message) ? "DO NOT RETRY BLINDLY. This endpoint has been observed returning 5xx after the reply was already created. Check the thread on LinkedIn before sending again." : result.hint ?? "";
8702
+ if (out.hint === "") delete out.hint;
8703
+ return out;
8704
+ }
8705
+ return { ok: true, parent: parentThreadUrn(ref) };
8706
+ }
8707
+
8708
+ // src/commands/profile-image.ts
8709
+ import { readFileSync as readFileSync3, statSync } from "fs";
8710
+ import { basename, resolve } from "path";
8711
+
8712
+ // src/engine/sdui-profile-image.ts
8713
+ import { randomUUID as randomUUID2 } from "crypto";
8714
+ var IMAGE_KINDS = {
8715
+ photo: {
8716
+ name: "photo",
8717
+ label: "profile photo",
8718
+ screen: "com.linkedin.sdui.flagshipnav.profile.ProfileAddPicture",
8719
+ originalType: "ProfileOriginalPhoto",
8720
+ displayType: "ProfileDisplayPhoto",
8721
+ save: "com.linkedin.sdui.requests.profile.saveProfilePicture",
8722
+ aspect: 1
8723
+ },
8724
+ banner: {
8725
+ name: "banner",
8726
+ label: "cover image",
8727
+ screen: "com.linkedin.sdui.flagshipnav.profile.ProfileAddBackgroundImage",
8728
+ originalType: "ProfileOriginalBackground",
8729
+ displayType: "ProfileDisplayBackground",
8730
+ save: "com.linkedin.sdui.requests.profile.saveProfileBackgroundImage",
8731
+ aspect: 4
8732
+ }
8733
+ };
8734
+ var REGISTER = "com.linkedin.sdui.requests.profile.profileImageRegister";
8735
+ var REGISTER_REQUEST = REGISTER;
8736
+ var NS = "MemoryNamespace";
8737
+ var PHOTO_SAVING = "ADD_PHOTOPROFILE_PHOTO_UPLOAD_IS_SAVING";
8738
+ var binding = () => `auto-binding-${randomUUID2()}`;
8739
+ var pointer = () => Math.random().toString(36).slice(2, 13).padEnd(11, "0");
8740
+ function newKeys(kind) {
8741
+ return {
8742
+ originalMedia: binding(),
8743
+ originalAssetUrns: binding(),
8744
+ displayMedia: binding(),
8745
+ displayAssetUrns: binding(),
8746
+ saving: kind.name === "photo" ? PHOTO_SAVING : binding(),
8747
+ originalPointer: pointer(),
8748
+ displayPointer: pointer()
8749
+ };
8750
+ }
8751
+ var focusKey = (vanity) => `ProfileComponentStateLastPerformedActionRef${vanity}ProfileComponentState`;
8752
+ var bind = (key) => ({ key, namespace: NS });
8753
+ var stateKey2 = (id) => ({ key: { value: { $case: "id", id } } });
8754
+ var META = { $type: "proto.sdui.common.RequestMetadata" };
8755
+ var WHOLE_IMAGE = {
8756
+ $type: "proto.sdui.media.MediaEditData",
8757
+ croppedRegion: {
8758
+ $type: "proto.sdui.common.Rect",
8759
+ topLeft: { $type: "proto.sdui.common.Coordinate2D", x: 0, y: 0 },
8760
+ topRight: { $type: "proto.sdui.common.Coordinate2D", x: 1, y: 0 },
8761
+ bottomLeft: { $type: "proto.sdui.common.Coordinate2D", x: 0, y: 1 },
8762
+ bottomRight: { $type: "proto.sdui.common.Coordinate2D", x: 1, y: 1 }
8763
+ },
8764
+ scaleRatio: 1,
8765
+ brightness: 0,
8766
+ contrast: 0,
8767
+ saturation: 0,
8768
+ vignette: 0,
8769
+ imageFilter: "ImageFilter_None"
8770
+ };
8771
+ function mediaList(file, name, ptr, edited) {
8772
+ const size = String(file.size);
8773
+ return {
8774
+ $type: "proto.sdui.media.MediaList",
8775
+ mediaFiles: [
8776
+ {
8777
+ mediaAttributions: [],
8778
+ analysisData: {},
8779
+ fileName: name,
8780
+ source: {
8781
+ $case: "localFile",
8782
+ localFile: {
8783
+ fileName: name,
8784
+ mimeType: file.mimeType,
8785
+ filePointer: ptr,
8786
+ size,
8787
+ shouldIncludeFileContents: false
8788
+ }
8789
+ },
8790
+ size,
8791
+ mimeType: file.mimeType,
8792
+ filePointer: ptr,
8793
+ mediaFileId: ptr,
8794
+ ...edited ? { editData: WHOLE_IMAGE } : {},
8795
+ captions: [],
8796
+ thumbnails: []
8797
+ }
8798
+ ]
8799
+ };
8800
+ }
8801
+ var CASES = {
8802
+ object: "mediaListValue",
8803
+ array: "stringListValue",
8804
+ string: "stringValue",
8805
+ boolean: "booleanValue"
8806
+ };
8807
+ function state(key, value) {
8808
+ const kind = Array.isArray(value) ? "array" : typeof value;
8809
+ return {
8810
+ key,
8811
+ namespace: NS,
8812
+ value,
8813
+ originalProtoCase: CASES[kind],
8814
+ protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id: key } }
8815
+ };
8816
+ }
8817
+ function serverRequest(requestId, payload, states2, screenId) {
8818
+ const requestedStateKeys = states2.map((s) => stateKey2(s.key));
8819
+ const requestedArguments = {
8820
+ $type: "proto.sdui.actions.requests.RequestedArguments",
8821
+ requestedStateKeys,
8822
+ payload,
8823
+ requestMetadata: META
8824
+ };
8825
+ return {
8826
+ requestId,
8827
+ serverRequest: {
8828
+ requestId,
8829
+ requestedArguments,
8830
+ isApfcEnabled: false,
8831
+ isStreaming: false,
8832
+ rumPageKey: ""
8833
+ },
8834
+ states: states2,
8835
+ requestedArguments: { ...requestedArguments, states: states2, screenId, knownTemplateIds: [] }
8836
+ };
8837
+ }
8838
+ var displayNameOf = (req) => req.displayName ?? `edited-image-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.${req.file.name.split(".").pop()}`;
8839
+ function savePlan(kind, req) {
8840
+ const k = req.keys;
8841
+ const focus = focusKey(req.vanity);
8842
+ if (kind.name === "photo") {
8843
+ return {
8844
+ payload: {
8845
+ profileId: req.profileId,
8846
+ vanityName: req.vanity,
8847
+ newMedia: bind(k.displayMedia),
8848
+ originalAssetUrns: bind(k.originalAssetUrns),
8849
+ displayAssetUrns: bind(k.displayAssetUrns),
8850
+ isSavingProfilePhoto: bind(k.saving),
8851
+ focusableComponentRefKey: bind(focus)
8852
+ },
8853
+ keys: [k.displayMedia, k.originalAssetUrns, k.displayAssetUrns, k.saving, focus],
8854
+ focusValue: "topcard-logo-image-referencekey"
8855
+ };
8856
+ }
8857
+ return {
8858
+ payload: {
8859
+ vanityName: req.vanity,
8860
+ profileId: req.profileId,
8861
+ editedMedia: bind(k.displayMedia),
8862
+ displayAssetUrns: bind(k.displayAssetUrns),
8863
+ originalAssetUrns: bind(k.originalAssetUrns),
8864
+ focusableComponentRefKey: bind(focus),
8865
+ isSaving: bind(k.saving),
8866
+ omitDefaultPhotoFilterEditInfo: true
8867
+ },
8868
+ keys: [k.displayMedia, k.displayAssetUrns, k.originalAssetUrns, focus],
8869
+ focusValue: `${req.vanity}_cover_edit_button`
8870
+ };
8871
+ }
8872
+ function registerBody(kind, req) {
8873
+ const k = req.keys;
8874
+ const save = savePlan(kind, req);
8875
+ const payload = {
8876
+ profileId: req.profileId,
8877
+ originalMedia: bind(k.originalMedia),
8878
+ originalAssetUrns: bind(k.originalAssetUrns),
8879
+ originalMediaType: kind.originalType,
8880
+ displayMedia: bind(k.displayMedia),
8881
+ displayMediaType: kind.displayType,
8882
+ displayAssetUrns: bind(k.displayAssetUrns),
8883
+ uploadOriginal: true,
8884
+ followUpRequest: { key: kind.save, data: save.payload, stateKeys: save.keys.map(bind) },
8885
+ skipEdit: false,
8886
+ isSaving: bind(k.saving)
8887
+ };
8888
+ return serverRequest(
8889
+ REGISTER,
8890
+ payload,
8891
+ [
8892
+ state(k.originalMedia, mediaList(req.file, req.file.name, k.originalPointer, false)),
8893
+ state(k.originalAssetUrns, []),
8894
+ state(k.displayMedia, mediaList(req.file, displayNameOf(req), k.displayPointer, true)),
8895
+ state(k.displayAssetUrns, []),
8896
+ state(k.saving, true)
8897
+ ],
8898
+ kind.screen
8899
+ );
8900
+ }
8901
+ function saveBody2(kind, req) {
8902
+ const k = req.keys;
8903
+ const save = savePlan(kind, req);
8904
+ const values = {
8905
+ [k.displayMedia]: mediaList(req.file, displayNameOf(req), k.displayPointer, true),
8906
+ [k.originalAssetUrns]: [req.originalId],
8907
+ [k.displayAssetUrns]: [req.displayId],
8908
+ [k.saving]: true,
8909
+ [focusKey(req.vanity)]: save.focusValue
8910
+ };
8911
+ return serverRequest(
8912
+ kind.save,
8913
+ save.payload,
8914
+ save.keys.map((key) => state(key, values[key])),
8915
+ kind.screen
8916
+ );
8917
+ }
8918
+ function* walk(v) {
8919
+ if (Array.isArray(v)) for (const x of v) yield* walk(x);
8920
+ else if (v !== null && typeof v === "object") {
8921
+ yield v;
8922
+ for (const x of Object.values(v)) yield* walk(x);
8923
+ }
8924
+ }
8925
+ var headerName = (key) => key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
8926
+ function assetIdOf(n) {
8927
+ if (n.$type !== "proto.sdui.actions.core.SetState") return void 0;
8928
+ const s = n.value?.state;
8929
+ const id = s?.key?.key?.value;
8930
+ const list2 = s?.value?.stringListValue?.stringValues;
8931
+ return typeof id?.id === "string" && typeof list2?.[0] === "string" ? [id.id, list2[0]] : void 0;
8932
+ }
8933
+ function uploadOf(n) {
8934
+ if (typeof n.fileReference !== "string") return void 0;
8935
+ const instruction = n.uploadInstruction?.instruction;
8936
+ const single = instruction?.singleRequestUploadInstruction;
8937
+ if (typeof single?.uploadUrl !== "string") return [n.fileReference, "multipart"];
8938
+ const headers2 = {};
8939
+ for (const h of single.uploadHeaders ?? [])
8940
+ if (typeof h.key === "string" && typeof h.value === "string")
8941
+ headers2[headerName(h.key)] = h.value;
8942
+ return [n.fileReference, { url: single.uploadUrl, headers: headers2 }];
8943
+ }
8944
+ function rowZero(raw) {
8945
+ const row = raw.match(/(?:^|\n)0:(\{.*)/)?.[1];
8946
+ try {
8947
+ return row === void 0 ? void 0 : JSON.parse(row);
8948
+ } catch {
8949
+ return void 0;
8950
+ }
8951
+ }
8952
+ function parseRegister(raw, keys) {
8953
+ const refused = responseErrors(raw);
8954
+ if (refused !== null)
8955
+ return { ok: false, code: "INVALID_INPUT", message: `LinkedIn refused the image: ${refused}` };
8956
+ const ids = /* @__PURE__ */ new Map();
8957
+ const uploads = /* @__PURE__ */ new Map();
8958
+ for (const n of walk(rowZero(raw))) {
8959
+ const id = assetIdOf(n);
8960
+ if (id !== void 0) ids.set(...id);
8961
+ const up = uploadOf(n);
8962
+ if (up !== void 0) uploads.set(...up);
8963
+ }
8964
+ const originalId = ids.get(keys.originalAssetUrns);
8965
+ const displayId = ids.get(keys.displayAssetUrns);
8966
+ const original = uploads.get(keys.originalPointer);
8967
+ const display = uploads.get(keys.displayPointer);
8968
+ if (original === "multipart" || display === "multipart")
8969
+ return {
8970
+ ok: false,
8971
+ code: "NOT_IMPLEMENTED",
8972
+ message: "LinkedIn asked for a multi-part upload, which has not been observed here. Nothing was uploaded. Try a smaller file."
8973
+ };
8974
+ if (originalId === void 0 || displayId === void 0 || !original || !display)
8975
+ return {
8976
+ ok: false,
8977
+ code: "SCHEMA_DRIFT",
8978
+ message: "the image registration carried no asset ids or upload urls; nothing was uploaded"
8979
+ };
8980
+ return { ok: true, originalId, displayId, uploads: { original, display } };
8981
+ }
8982
+ function imageSizeOf(bytes) {
8983
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
8984
+ const png = [137, 80, 78, 71, 13, 10, 26, 10];
8985
+ if (bytes.length >= 24 && png.every((b, i) => bytes[i] === b))
8986
+ return { width: view.getUint32(16), height: view.getUint32(20), mimeType: "image/png" };
8987
+ if (bytes[0] !== 255 || bytes[1] !== 216) return null;
8988
+ let at = 2;
8989
+ while (at + 9 <= bytes.length) {
8990
+ if (bytes[at] !== 255) return null;
8991
+ const marker = bytes[at + 1];
8992
+ if (marker >= 192 && marker <= 207 && ![196, 200, 204].includes(marker))
8993
+ return {
8994
+ height: view.getUint16(at + 5),
8995
+ width: view.getUint16(at + 7),
8996
+ mimeType: "image/jpeg"
8997
+ };
8998
+ at += 2 + view.getUint16(at + 2);
8999
+ }
9000
+ return null;
9001
+ }
9002
+ function picturesOf(json) {
9003
+ const root = json;
9004
+ const urn = root?.data?.["*elements"]?.[0];
9005
+ const p = (root?.included ?? []).find((n) => n.entityUrn === urn);
9006
+ const profileId2 = typeof urn === "string" ? urn.split(":").pop() : void 0;
9007
+ if (p === void 0 || profileId2 === void 0)
9008
+ return { ok: false, code: "SCHEMA_DRIFT", message: "the profile answer carried no profile" };
9009
+ const asset = (pic) => String(pic?.displayImageUrn ?? "").match(/digitalmediaAsset:(.+)$/)?.[1];
9010
+ const photo = asset(p.profilePicture);
9011
+ const banner = asset(p.backgroundPicture);
9012
+ return {
9013
+ ok: true,
9014
+ profileId: profileId2,
9015
+ ...photo !== void 0 ? { photo } : {},
9016
+ ...banner !== void 0 ? { banner } : {}
9017
+ };
9018
+ }
9019
+
9020
+ // src/commands/profile-image.ts
9021
+ function liveImages(session) {
9022
+ const client = createLiveClient(session);
9023
+ return {
9024
+ vanity: async () => {
9025
+ const me = await createEngine(session).whoami();
9026
+ if (!me.ok) return me;
9027
+ const id = me.value?.publicIdentifier;
9028
+ return typeof id === "string" && id !== "" ? { ok: true, vanity: id } : { ok: false, code: "SCHEMA_DRIFT", message: "whoami returned no public profile id" };
8139
9029
  },
8140
- states: [],
8141
- requestedArguments: {
8142
- ...args,
8143
- states: [],
8144
- screenId: SCREEN_ID4,
8145
- knownTemplateIds: []
9030
+ pictures: async (vanity) => {
9031
+ const r = await client.request({
9032
+ url: fullProfileUrl(vanity),
9033
+ spendClass: "profile",
9034
+ operation: "profile-pictures"
9035
+ });
9036
+ return r.ok ? picturesOf(r.json) : r;
9037
+ },
9038
+ register: async (body) => {
9039
+ const raw = await sendAction(REGISTER_REQUEST, body, client, "image-register");
9040
+ return typeof raw === "string" ? { ok: true, raw } : raw;
9041
+ },
9042
+ put: async (upload, bytes, mimeType) => {
9043
+ const r = await client.request({
9044
+ url: upload.url,
9045
+ method: "PUT",
9046
+ bytes,
9047
+ headers: { "content-type": mimeType, ...upload.headers },
9048
+ spendClass: "write",
9049
+ operation: "image-upload"
9050
+ });
9051
+ return r.ok ? { ok: true } : r;
9052
+ },
9053
+ save: async (kind, body) => {
9054
+ const raw = await sendAction(kind.save, body, client, `${kind.name}-save`);
9055
+ return typeof raw === "string" ? { ok: true } : raw;
8146
9056
  }
8147
9057
  };
8148
9058
  }
8149
- async function react(confirmed, client) {
8150
- const { urn, type, remove } = confirmed.payload;
8151
- let target2;
9059
+ var MAX_BYTES = 8 * 1024 * 1024;
9060
+ function pick(kind, path) {
9061
+ let bytes;
8152
9062
  try {
8153
- target2 = targetFor(urn);
8154
- } catch (e) {
8155
- return { ok: false, code: "INVALID_INPUT", message: e.message };
9063
+ if (!statSync(path).isFile()) throw new Error("not a file");
9064
+ bytes = new Uint8Array(readFileSync3(path));
9065
+ } catch {
9066
+ return err("edit", "INVALID_INPUT", `cannot read ${path}`);
9067
+ }
9068
+ if (bytes.byteLength > MAX_BYTES)
9069
+ return err("edit", "INVALID_INPUT", `${basename(path)} is over LinkedIn's 8 MB limit`);
9070
+ const size = imageSizeOf(bytes);
9071
+ if (size === null)
9072
+ return err("edit", "INVALID_INPUT", `${basename(path)} is not a PNG or JPEG image`);
9073
+ const ratio = size.width / size.height;
9074
+ if (Math.abs(ratio / kind.aspect - 1) > 0.02) {
9075
+ const want = kind.name === "photo" ? "square" : "4:1 (1584 \xD7 396)";
9076
+ return err(
9077
+ "edit",
9078
+ "INVALID_INPUT",
9079
+ `${basename(path)} is ${size.width} \xD7 ${size.height}; a ${kind.label} must be ${want}`,
9080
+ "It is uploaded as it is, uncropped: crop it to that shape first."
9081
+ );
8156
9082
  }
8157
- const op = remove ? "delete" : "create";
8158
- const result = await client.request({
8159
- url: reactionUrl(op),
8160
- method: "POST",
8161
- body: sduiBody(op, target2, type),
8162
- spendClass: "write",
8163
- operation: `reaction.${op}`
8164
- });
8165
- if (result.ok) return { ok: true, id: urn };
8166
- const out = { ok: false, code: result.code, message: result.message };
8167
- out.hint = result.hint ?? "This surface was captured from the live client but has never been replayed by this tool. If it refuses, the first thing to try is sending `x-li-page-instance` and `x-li-track`, which the browser sends here and which our verified read header set deliberately omits.";
8168
- return out;
8169
- }
8170
-
8171
- // src/engine/voyager-reply.ts
8172
- var REPLY_DECORATION = "com.linkedin.voyager.dash.deco.social.NormComment-43";
8173
- var REPLY_URL = `https://www.linkedin.com/voyager/api/voyagerSocialDashNormComments?decorationId=${REPLY_DECORATION}`;
8174
- function parentThreadUrn(ref) {
8175
- return `urn:li:comment:(${ref.threadType}:${ref.activityId},${ref.commentId})`;
9083
+ return { bytes, ...size };
8176
9084
  }
8177
- function replyBody(ref, text6) {
9085
+ function planOf(kind, file, picked, was, author) {
9086
+ const sha256 = mediaDigest(picked.bytes);
8178
9087
  return {
8179
- commentary: {
8180
- text: text6,
8181
- // The captured reply carried a profileMention, because LinkedIn's UI
8182
- // pre-fills "@Author " into the box. We send none: an @mention notifies a
8183
- // real person, and inventing one would put words — and a notification —
8184
- // where the user did not ask for them.
8185
- attributesV2: [],
8186
- $type: "com.linkedin.voyager.dash.common.text.TextViewModel"
8187
- },
8188
- threadUrn: parentThreadUrn(ref)
9088
+ action: `replace your ${kind.label}`,
9089
+ payload: { image: kind.name, file, sha256, was: was ?? null },
9090
+ summary: [
9091
+ author,
9092
+ `image ${kind.label}`,
9093
+ `file ${file}`,
9094
+ ` ${picked.width} \xD7 ${picked.height}, ${picked.bytes.byteLength} bytes, sha256 ${sha256.slice(0, 16)}\u2026`,
9095
+ `now ${was === void 0 ? "none" : `asset ${was}`}`
9096
+ ],
9097
+ reversibility: "replaceable again with any file, but the current image is not kept here: have the original file before replacing it. Everyone who can see your profile sees the change.",
9098
+ transport: "voyager"
8189
9099
  };
8190
9100
  }
8191
- async function replyToComment(confirmed, client) {
8192
- const { ref, text: text6 } = confirmed.payload;
8193
- const result = await client.request({
8194
- url: REPLY_URL,
8195
- method: "POST",
8196
- body: replyBody(ref, text6),
8197
- spendClass: "write",
8198
- operation: "reply"
8199
- });
8200
- if (!result.ok) {
8201
- const out = { ok: false, code: result.code, message: result.message };
8202
- out.hint = /5\d\d|unexpected status/.test(result.message) ? "DO NOT RETRY BLINDLY. This endpoint has been observed returning 5xx after the reply was already created. Check the thread on LinkedIn before sending again." : result.hint ?? "";
8203
- if (out.hint === "") delete out.hint;
8204
- return out;
9101
+ async function send2(li, kind, req, picked) {
9102
+ const nothing = (f, step) => err("edit", f.code, `${step} failed (${f.message}); nothing changed on your profile`, f.hint);
9103
+ const registered = await li.register(registerBody(kind, req));
9104
+ if (!registered.ok) return nothing(registered, "registering the image");
9105
+ const ticket = parseRegister(registered.raw, req.keys);
9106
+ if (!ticket.ok) return nothing(ticket, "registering the image");
9107
+ for (const upload of [ticket.uploads.original, ticket.uploads.display]) {
9108
+ const put2 = await li.put(upload, picked.bytes, picked.mimeType);
9109
+ if (!put2.ok) return nothing(put2, "uploading the image");
9110
+ }
9111
+ const saved = await li.save(kind, saveBody2(kind, { ...req, ...ticket }));
9112
+ if (!saved.ok)
9113
+ return err("edit", saved.code, `saving the ${kind.label} failed: ${saved.message}`);
9114
+ return { ok: true, displayId: ticket.displayId };
9115
+ }
9116
+ async function runEditImage(name, path, now = Date.now(), deps = terminalDeps(), surface, keys) {
9117
+ const kind = IMAGE_KINDS[name];
9118
+ if (kind === void 0)
9119
+ return err("edit", "INVALID_INPUT", `'${name}' is not an image this edits`, "photo, banner");
9120
+ if (path === void 0 || path.trim() === "")
9121
+ return err("edit", "INVALID_INPUT", "an image file is required", `lnrelay edit ${name} <file>`);
9122
+ const file = resolve(path);
9123
+ const picked = pick(kind, file);
9124
+ if ("ok" in picked) return picked;
9125
+ const unapprovable = refuseUnapprovable("edit", "editing", deps);
9126
+ if (unapprovable !== null) return unapprovable;
9127
+ const ctx = prepare("edit", now, "voyager", 4);
9128
+ if ("ok" in ctx) return ctx;
9129
+ if (ctx.transport.kind !== "voyager")
9130
+ return err("edit", "NOT_IMPLEMENTED", "profile edits go over the browser session only");
9131
+ const li = surface ?? liveImages(ctx.transport.session);
9132
+ const me = await li.vanity();
9133
+ if (!me.ok) return err("edit", me.code, me.message, me.hint);
9134
+ const before = await li.pictures(me.vanity);
9135
+ if (!before.ok) return err("edit", before.code, before.message, before.hint);
9136
+ const plan = planOf(kind, file, picked, before[kind.name], authorLine(ctx.transport));
9137
+ const gated = await gate("edit", plan, ctx, deps);
9138
+ if ("ok" in gated) return gated;
9139
+ const ext = picked.mimeType === "image/png" ? "png" : "jpg";
9140
+ const sent = await send2(
9141
+ li,
9142
+ kind,
9143
+ {
9144
+ profileId: before.profileId,
9145
+ vanity: me.vanity,
9146
+ file: { name: basename(file), mimeType: picked.mimeType, size: picked.bytes.byteLength },
9147
+ keys: keys ?? newKeys(kind),
9148
+ displayName: `edited-image-${new Date(now).toISOString().replace(/[:.]/g, "-")}.${ext}`
9149
+ },
9150
+ picked
9151
+ );
9152
+ if (!("displayId" in sent)) return sent;
9153
+ const after = await li.pictures(me.vanity);
9154
+ if (!after.ok || after[kind.name] !== sent.displayId) {
9155
+ return err(
9156
+ "edit",
9157
+ "SCHEMA_DRIFT",
9158
+ `LinkedIn accepted the save, but your ${kind.label} does not read back as the new image`,
9159
+ after.ok ? `It shows asset ${after[kind.name] ?? "none"}; the upload was ${sent.displayId}.` : `The read-back failed: ${after.message}`
9160
+ );
8205
9161
  }
8206
- return { ok: true, parent: parentThreadUrn(ref) };
9162
+ return ok("edit", { image: kind.name, verified: true, asset: sent.displayId });
8207
9163
  }
8208
9164
 
8209
9165
  // src/commands/transport.ts
@@ -8370,7 +9326,7 @@ function loadMedia(flag, path) {
8370
9326
  return err(
8371
9327
  "share",
8372
9328
  "INVALID_INPUT",
8373
- `unsupported file type: ${basename(path)}`,
9329
+ `unsupported file type: ${basename2(path)}`,
8374
9330
  "images: png, jpg, jpeg, gif, webp. videos: mp4, mov. documents: pdf."
8375
9331
  );
8376
9332
  }
@@ -8378,21 +9334,21 @@ function loadMedia(flag, path) {
8378
9334
  return err(
8379
9335
  "share",
8380
9336
  "INVALID_INPUT",
8381
- `${basename(path)} is not ${flag === "image" ? "an image" : `a ${flag}`}`,
9337
+ `${basename2(path)} is not ${flag === "image" ? "an image" : `a ${flag}`}`,
8382
9338
  `pass it with ${KIND_FLAG[kind.kind]}`
8383
9339
  );
8384
9340
  }
8385
9341
  let bytes;
8386
9342
  try {
8387
- if (!statSync(path).isFile()) throw new Error("not a file");
8388
- bytes = new Uint8Array(readFileSync3(path));
9343
+ if (!statSync2(path).isFile()) throw new Error("not a file");
9344
+ bytes = new Uint8Array(readFileSync4(path));
8389
9345
  } catch {
8390
9346
  return err("share", "INVALID_INPUT", `cannot read ${path}`);
8391
9347
  }
8392
9348
  return {
8393
9349
  bytes,
8394
9350
  approved: {
8395
- filename: basename(path),
9351
+ filename: basename2(path),
8396
9352
  kind: kind.kind,
8397
9353
  contentType: kind.contentType,
8398
9354
  size: bytes.byteLength,
@@ -8451,10 +9407,10 @@ function sharePlan(p) {
8451
9407
  transport: p.transport
8452
9408
  };
8453
9409
  }
8454
- function cardLines(card) {
8455
- if (card === void 0) return [];
8456
- if (card === null) return ["card none \u2014 LinkedIn has no preview for this link"];
8457
- return [`card "${card.title}" (${card.source})`];
9410
+ function cardLines(card2) {
9411
+ if (card2 === void 0) return [];
9412
+ if (card2 === null) return ["card none \u2014 LinkedIn has no preview for this link"];
9413
+ return [`card "${card2.title}" (${card2.source})`];
8458
9414
  }
8459
9415
  var liveCardLookup = (url, session) => fetchLinkCard(url, createLiveClient(session));
8460
9416
  function shareNeeds(files, scheduledAt, poll, cardUrl) {
@@ -8575,8 +9531,8 @@ async function runShare(text6, visibility, now = Date.now(), deps = terminalDeps
8575
9531
  const needs = shareNeeds(loaded?.approved.length, scheduledAt, pollSpec, cardUrl);
8576
9532
  const ctx = prepare("share", now, needs.voyagerOnly ? "voyager" : via2, needs.calls);
8577
9533
  if ("ok" in ctx) return ctx;
8578
- const card = await cardFor(cardUrl, ctx.transport, link);
8579
- if (card !== void 0 && card !== null && "ok" in card) return card;
9534
+ const card2 = await cardFor(cardUrl, ctx.transport, link);
9535
+ if (card2 !== void 0 && card2 !== null && "ok" in card2) return card2;
8580
9536
  const plan = sharePlan({
8581
9537
  author: authorLine(ctx.transport),
8582
9538
  transport: ctx.transport.kind,
@@ -8585,7 +9541,7 @@ async function runShare(text6, visibility, now = Date.now(), deps = terminalDeps
8585
9541
  media: loaded?.approved,
8586
9542
  scheduledAt,
8587
9543
  poll: pollSpec,
8588
- ...card === void 0 ? {} : { card },
9544
+ ...card2 === void 0 ? {} : { card: card2 },
8589
9545
  now
8590
9546
  });
8591
9547
  const gated = await gate("share", plan, ctx, deps);
@@ -8810,6 +9766,9 @@ async function runEdit(commentUrn, text6, now = Date.now(), deps = terminalDeps(
8810
9766
  'lnrelay edit <comment-urn> "<text>"'
8811
9767
  );
8812
9768
  }
9769
+ if (commentUrn === "photo" || commentUrn === "banner") {
9770
+ return runEditImage(commentUrn, text6, now, deps);
9771
+ }
8813
9772
  const ref = parseCommentUrn(commentUrn);
8814
9773
  if (ref === null && !commentUrn.startsWith("urn:")) {
8815
9774
  return runEditProfile(commentUrn, text6, now, deps);
@@ -9342,149 +10301,6 @@ async function runFindFilters(kind, req, opts = {}, fetch2) {
9342
10301
  });
9343
10302
  }
9344
10303
 
9345
- // src/engine/sdui-skill.ts
9346
- var SKILL = {
9347
- addScreen: "com.linkedin.sdui.flagshipnav.profile.ProfileSkillAddForm",
9348
- editScreen: "com.linkedin.sdui.flagshipnav.profile.ProfileSkillDetailsEditForm",
9349
- listScreen: "com.linkedin.sdui.flagshipnav.profile.ProfileSkillDetails",
9350
- pager: "com.linkedin.sdui.pagers.profile.details.skills",
9351
- save: "com.linkedin.sdui.requests.profile.saveProfileSkillForm",
9352
- delete: "com.linkedin.sdui.requests.profile.deleteProfileSkillForm"
9353
- };
9354
- var EDIT_NAV2 = `{"$type":"proto.sdui.actions.core.NavigateToScreen","screenId":"${SKILL.editScreen}"`;
9355
- var TEXT3 = /"children":\["((?:[^"\\]|\\.)*)"\]/g;
9356
- function skillsFromPage(stream) {
9357
- if (!stream.includes(SKILL.pager) && !stream.includes(EDIT_NAV2) && !stream.includes("isPartialPage")) {
9358
- return drift9("the skills page could not be read");
9359
- }
9360
- const skills = [];
9361
- let from = 0;
9362
- let i = 0;
9363
- for (; ; ) {
9364
- i = stream.indexOf(EDIT_NAV2, i);
9365
- if (i === -1) break;
9366
- const text6 = balanced(stream, i);
9367
- const end = i;
9368
- i += EDIT_NAV2.length;
9369
- if (text6 === null) continue;
9370
- const payload = JSON.parse(text6).requestedArguments?.payload;
9371
- const id = payload?.skillId;
9372
- if (typeof id !== "string" || payload === void 0 || skills.some((s) => s.skillId === id))
9373
- continue;
9374
- const names = [...stream.slice(from, end).matchAll(TEXT3)].map(
9375
- (m) => JSON.parse(`"${m[1]}"`)
9376
- );
9377
- skills.push({ skillId: id, name: names.length === 1 ? names[0] ?? null : null, payload });
9378
- from = end + text6.length;
9379
- }
9380
- return { ok: true, skills };
9381
- }
9382
- function pagerFrom(payload, start) {
9383
- const args = {
9384
- $type: "proto.sdui.actions.requests.RequestedArguments",
9385
- requestedStateKeys: [],
9386
- payload: { ...payload, start },
9387
- requestMetadata: { $type: "proto.sdui.common.RequestMetadata" }
9388
- };
9389
- return {
9390
- pagerId: SKILL.pager,
9391
- clientArguments: { ...args, states: [], screenId: SKILL.listScreen, knownTemplateIds: [] },
9392
- paginationRequest: {
9393
- $type: "proto.sdui.actions.requests.PaginationRequest",
9394
- pagerId: SKILL.pager,
9395
- retryCount: 0,
9396
- requestedArguments: args
9397
- }
9398
- };
9399
- }
9400
- function readSkillForm(stream) {
9401
- const model = readModel(stream);
9402
- if (model === null) return drift9("the skill form carried no initial values");
9403
- const save = findRequest(stream, SKILL.save);
9404
- const del = findRequest(stream, SKILL.delete);
9405
- if (save === null && del === null)
9406
- return drift9("the skill form carried neither a save nor a delete");
9407
- return { ok: true, model, save, del, screen: del === null ? SKILL.addScreen : SKILL.editScreen };
9408
- }
9409
- var nameKey = (model) => [...model.keys()].find((k) => k.startsWith("addSkillsTypeaheadSkillName"));
9410
- function skillNameOf(form) {
9411
- const key = nameKey(form.model);
9412
- const v = key === void 0 ? void 0 : form.model.get(key)?.value;
9413
- return typeof v === "string" ? v : null;
9414
- }
9415
- function addSkillBody(form, name) {
9416
- if (name.trim() === "")
9417
- return { ok: false, code: "INVALID_INPUT", message: "a skill needs a name" };
9418
- if (form.save === null) return drift9("this form has no save action (it is not the add form)");
9419
- const key = nameKey(form.model);
9420
- const current = key === void 0 ? void 0 : form.model.get(key);
9421
- if (key === void 0 || current === void 0) return drift9("the skill form has no name field");
9422
- const model = new Map(form.model);
9423
- model.set(key, { ...current, value: name.trim() });
9424
- const states2 = wireStates(keysOf(form.save), model, () => void 0);
9425
- if (!Array.isArray(states2)) return states2;
9426
- return { ok: true, body: requestBody(SKILL.save, form.save, states2, form.screen) };
9427
- }
9428
- function removeSkillBody(form) {
9429
- if (form.del === null)
9430
- return drift9("this form has no delete action (it is not an existing skill)");
9431
- const states2 = wireStates(keysOf(form.del), form.model, () => void 0);
9432
- if (!Array.isArray(states2)) return states2;
9433
- return { ok: true, body: requestBody(SKILL.delete, form.del, states2, form.screen) };
9434
- }
9435
- var PAGER_URL2 = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${SKILL.pager}`;
9436
- var MAX_PAGES2 = 10;
9437
- async function fetchSkills(vanityName, client) {
9438
- const screen = await openForm(
9439
- SKILL.listScreen,
9440
- { vanityName, isVanityNameResolved: true },
9441
- client,
9442
- "skills-screen"
9443
- );
9444
- if (typeof screen !== "string") return screen;
9445
- const at = screen.indexOf('"filter":"ProfileSkillCategory_ALL"');
9446
- const open = at === -1 ? -1 : screen.lastIndexOf('"payload":{', at);
9447
- const text6 = open === -1 ? null : balanced(screen, open + '"payload":'.length);
9448
- if (text6 === null) return drift9("the Skills screen carried no list request");
9449
- const payload = JSON.parse(text6);
9450
- const count3 = typeof payload.count === "number" ? payload.count : 10;
9451
- const skills = [];
9452
- for (let page = 0; page < MAX_PAGES2; page++) {
9453
- const result = await client.request({
9454
- url: PAGER_URL2,
9455
- method: "POST",
9456
- body: pagerFrom(payload, skills.length),
9457
- spendClass: "page",
9458
- operation: "skills"
9459
- });
9460
- if (!result.ok) return { ok: false, code: result.code, message: result.message };
9461
- const parsed = skillsFromPage(result.classification.raw ?? "");
9462
- if (!parsed.ok) return parsed;
9463
- const fresh = parsed.skills.filter((s) => !skills.some((k) => k.skillId === s.skillId));
9464
- skills.push(...fresh);
9465
- if (parsed.skills.length < count3 || fresh.length === 0) break;
9466
- }
9467
- return { ok: true, skills };
9468
- }
9469
- async function openSkillForm(payload, client, edit2) {
9470
- const stream = await openForm(
9471
- edit2 ? SKILL.editScreen : SKILL.addScreen,
9472
- { ...payload, isVanityNameResolved: true },
9473
- client,
9474
- edit2 ? "skill-edit-form" : "skill-add-form"
9475
- );
9476
- return typeof stream === "string" ? readSkillForm(stream) : stream;
9477
- }
9478
- async function sendSkill(body, requestId, client) {
9479
- const sent = await sendAction(
9480
- requestId,
9481
- body,
9482
- client,
9483
- requestId === SKILL.save ? "skill-add" : "skill-remove"
9484
- );
9485
- return typeof sent === "string" ? { ok: true } : sent;
9486
- }
9487
-
9488
10304
  // src/commands/skill.ts
9489
10305
  function liveSkills(session, quiet = false) {
9490
10306
  const client = createLiveClient(session, void 0, quiet);
@@ -9741,24 +10557,24 @@ var SERVER_REQUEST = "https://www.linkedin.com/flagship-web/rsc-action/actions/s
9741
10557
  var VIEWERS_URL = `${SERVER_REQUEST}?sduiid=WvmpEntityList`;
9742
10558
  var VIEW_TOTALS_URL = `${SERVER_REQUEST}?sduiid=WvmpAnalytics`;
9743
10559
  var RANGE = "WvmpSearchFilterType_DATE_RANGE";
9744
- var META = { $type: "proto.sdui.common.RequestMetadata" };
9745
- function serverRequest(requestId, stateKey2, payload) {
9746
- const state = {
9747
- key: stateKey2,
10560
+ var META2 = { $type: "proto.sdui.common.RequestMetadata" };
10561
+ function serverRequest2(requestId, stateKey3, payload) {
10562
+ const state2 = {
10563
+ key: stateKey3,
9748
10564
  namespace: "MemoryNamespace",
9749
10565
  value: [],
9750
10566
  originalProtoCase: "stringListValue",
9751
- protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id: stateKey2 } }
10567
+ protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id: stateKey3 } }
9752
10568
  };
9753
10569
  const requestedArguments = {
9754
10570
  $type: "proto.sdui.actions.requests.RequestedArguments",
9755
- requestedStateKeys: [{ key: { value: { $case: "id", id: stateKey2 } } }],
10571
+ requestedStateKeys: [{ key: { value: { $case: "id", id: stateKey3 } } }],
9756
10572
  payload: {
9757
10573
  ...payload,
9758
10574
  filterTypeList: [RANGE],
9759
- dateRangeSelectionFilters: { key: stateKey2, namespace: "MemoryNamespace" }
10575
+ dateRangeSelectionFilters: { key: stateKey3, namespace: "MemoryNamespace" }
9760
10576
  },
9761
- requestMetadata: META
10577
+ requestMetadata: META2
9762
10578
  };
9763
10579
  return {
9764
10580
  requestId,
@@ -9769,22 +10585,22 @@ function serverRequest(requestId, stateKey2, payload) {
9769
10585
  isStreaming: false,
9770
10586
  rumPageKey: ""
9771
10587
  },
9772
- states: [state],
10588
+ states: [state2],
9773
10589
  requestedArguments: {
9774
10590
  ...requestedArguments,
9775
- states: [state],
10591
+ states: [state2],
9776
10592
  screenId: "com.linkedin.sdui.flagshipnav.home.Home",
9777
10593
  knownTemplateIds: []
9778
10594
  }
9779
10595
  };
9780
10596
  }
9781
10597
  function viewersBody() {
9782
- return serverRequest("WvmpEntityList", `entityListQueryFilterPrefix${RANGE}`, {
10598
+ return serverRequest2("WvmpEntityList", `entityListQueryFilterPrefix${RANGE}`, {
9783
10599
  sortType: "ProfileViewSortType_TIME_DESCENDING"
9784
10600
  });
9785
10601
  }
9786
10602
  function viewTotalsBody() {
9787
- return serverRequest("WvmpAnalytics", `analyticsFieldsFilterPrefix${RANGE}`, {
10603
+ return serverRequest2("WvmpAnalytics", `analyticsFieldsFilterPrefix${RANGE}`, {
9788
10604
  highlightCardDimensions: [
9789
10605
  "DimensionType_LOCATION",
9790
10606
  "DimensionType_INDUSTRY",
@@ -9795,22 +10611,22 @@ function viewTotalsBody() {
9795
10611
  detailsCardResultCount: 23
9796
10612
  });
9797
10613
  }
9798
- var drift10 = (message) => ({ ok: false, code: "SCHEMA_DRIFT", message });
9799
- var unquote3 = (s) => JSON.parse(`"${s}"`);
9800
- var STR = '((?:[^"\\\\]|\\\\.)+)';
10614
+ var drift12 = (message) => ({ ok: false, code: "SCHEMA_DRIFT", message });
10615
+ var unquote4 = (s) => JSON.parse(`"${s}"`);
10616
+ var STR2 = '((?:[^"\\\\]|\\\\.)+)';
9801
10617
  var ITEM = /"viewName":"viewer-list-item"(?:,"impressionThresholds":\[[^\]]*\])?[^{}]*"semanticPosition"/;
9802
10618
  var TEXT_PROPS = /"textProps":\{"fontFamily":"[^"]*","fontSize":"(\w+)","fontStyle":"[^"]*","fontWeight":"(\w+)","lineHeight":"[^"]*","textAlign":"[^"]*","children":/g;
9803
- var OWN_TEXT = new RegExp(`^\\["${STR}"\\]`);
9804
- var NESTED_TEXT = new RegExp(`\\[null,"${STR}"`);
9805
- var LINK2 = new RegExp(`"urlValue":\\{"\\$case":"url","url":"${STR}"`);
10619
+ var OWN_TEXT = new RegExp(`^\\["${STR2}"\\]`);
10620
+ var NESTED_TEXT = new RegExp(`\\[null,"${STR2}"`);
10621
+ var LINK2 = new RegExp(`"urlValue":\\{"\\$case":"url","url":"${STR2}"`);
9806
10622
  var PROFILE_ID2 = /ACoA[A-Za-z0-9_-]{10,}/;
9807
- var PLAIN_TEXT = new RegExp(`"children":\\["${STR}"\\]`, "g");
10623
+ var PLAIN_TEXT = new RegExp(`"children":\\["${STR2}"\\]`, "g");
9808
10624
  function textsOf(row) {
9809
10625
  return [...row.matchAll(TEXT_PROPS)].flatMap((m) => {
9810
10626
  const after = row.slice((m.index ?? 0) + m[0].length, (m.index ?? 0) + m[0].length + 600);
9811
10627
  const raw = after.match(OWN_TEXT)?.[1] ?? after.match(NESTED_TEXT)?.[1];
9812
10628
  if (raw === void 0) return [];
9813
- const text6 = unquote3(raw).trim();
10629
+ const text6 = unquote4(raw).trim();
9814
10630
  return text6 === "" ? [] : [{ size: m[1], weight: m[2], text: text6 }];
9815
10631
  });
9816
10632
  }
@@ -9824,7 +10640,7 @@ function viewerOf(row, id) {
9824
10640
  const lines = rest.filter((t) => t !== degreeText);
9825
10641
  const viewed = lines.at(-1);
9826
10642
  const link = row.match(LINK2)?.[1];
9827
- const url = link === void 0 ? void 0 : unquote3(link);
10643
+ const url = link === void 0 ? void 0 : unquote4(link);
9828
10644
  if (url === void 0 || !/linkedin\.com\/in\//.test(url)) {
9829
10645
  const v = { anonymous: true, description: first };
9830
10646
  if (viewed !== void 0) v.viewed = viewed;
@@ -9842,7 +10658,7 @@ function viewerOf(row, id) {
9842
10658
  ...viewed !== void 0 ? { viewed } : {}
9843
10659
  };
9844
10660
  }
9845
- var REF = /"\$[LQ]?([0-9a-f]+)"/g;
10661
+ var REF2 = /"\$[LQ]?([0-9a-f]+)"/g;
9846
10662
  function idUnder(rows, ref, items) {
9847
10663
  const seen = /* @__PURE__ */ new Set([ref]);
9848
10664
  const queue = [ref];
@@ -9850,7 +10666,7 @@ function idUnder(rows, ref, items) {
9850
10666
  const row = rows.byId.get(queue.shift()) ?? "";
9851
10667
  const id = row.match(PROFILE_ID2)?.[0];
9852
10668
  if (id !== void 0) return id;
9853
- for (const m of row.matchAll(REF)) {
10669
+ for (const m of row.matchAll(REF2)) {
9854
10670
  const next = m[1];
9855
10671
  if (!seen.has(next) && !items.has(next) && rows.byId.has(next)) {
9856
10672
  seen.add(next);
@@ -9864,7 +10680,7 @@ function idsByViewer(rows, items) {
9864
10680
  const ids = /* @__PURE__ */ new Map();
9865
10681
  for (const row of rows.byId.values()) {
9866
10682
  let current;
9867
- for (const m of row.matchAll(REF)) {
10683
+ for (const m of row.matchAll(REF2)) {
9868
10684
  const ref = m[1];
9869
10685
  if (items.has(ref)) current = ref;
9870
10686
  else if (current !== void 0 && !ids.has(current)) {
@@ -9877,19 +10693,19 @@ function idsByViewer(rows, items) {
9877
10693
  }
9878
10694
  function parseViewers(stream) {
9879
10695
  if (!stream.includes('"viewName":"viewer-list"'))
9880
- return drift10("the profile viewers answer was not the viewer list");
10696
+ return drift12("the profile viewers answer was not the viewer list");
9881
10697
  const rows = new Rows(stream);
9882
10698
  const items = new Set([...rows.byId].filter(([, row]) => ITEM.test(row)).map(([id]) => id));
9883
10699
  const ids = idsByViewer(rows, items);
9884
10700
  const viewers = [...items].flatMap((id) => viewerOf(rows.byId.get(id) ?? "", ids.get(id)) ?? []);
9885
10701
  const shown = Math.max(items.size, (stream.match(new RegExp(ITEM, "g")) ?? []).length);
9886
10702
  if (shown > 0 && viewers.length === 0)
9887
- return drift10(`${shown} profile viewers were shown but none could be read`);
10703
+ return drift12(`${shown} profile viewers were shown but none could be read`);
9888
10704
  let privateViewers;
9889
10705
  for (const [id, row] of rows.byId) {
9890
10706
  if (items.has(id) || privateViewers !== void 0) continue;
9891
10707
  for (const m of row.matchAll(PLAIN_TEXT)) {
9892
- const n = unquote3(m[1]).match(/^(\d[\d.,\s]*)\s+\D/)?.[1];
10708
+ const n = unquote4(m[1]).match(/^(\d[\d.,\s]*)\s+\D/)?.[1];
9893
10709
  if (n !== void 0) {
9894
10710
  privateViewers = Number(n.replace(/\D/g, ""));
9895
10711
  break;
@@ -9899,16 +10715,16 @@ function parseViewers(stream) {
9899
10715
  return privateViewers === void 0 ? { ok: true, viewers } : { ok: true, viewers, privateViewers };
9900
10716
  }
9901
10717
  function parseViewTotals(stream) {
9902
- const texts3 = [...stream.matchAll(PLAIN_TEXT)].map((m) => unquote3(m[1]).trim());
10718
+ const texts3 = [...stream.matchAll(PLAIN_TEXT)].map((m) => unquote4(m[1]).trim());
9903
10719
  const at = texts3.findIndex((t) => /^\d[\d.,\s]*$/.test(t));
9904
- if (at === -1) return drift10("the profile view totals carried no number");
10720
+ if (at === -1) return drift12("the profile view totals carried no number");
9905
10721
  const total = Number(texts3[at].replace(/\D/g, ""));
9906
10722
  const period = texts3[at + 1];
9907
10723
  return period === void 0 ? { ok: true, total } : { ok: true, total, period };
9908
10724
  }
9909
10725
 
9910
10726
  // src/commands/viewers.ts
9911
- function liveFetch9(quiet) {
10727
+ function liveFetch10(quiet) {
9912
10728
  const session = loadSession();
9913
10729
  if (session.state !== "ok")
9914
10730
  return err("viewers", "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
@@ -9921,7 +10737,7 @@ function liveFetch9(quiet) {
9921
10737
  }
9922
10738
  var compactViewer = (v) => "anonymous" in v ? line(["anonymous", v.description, v.viewed]) : line([v.name, v.degree, v.headline, v.viewed, v.url]);
9923
10739
  async function runViewers(opts = {}, fetch2) {
9924
- const get = fetch2 ?? liveFetch9(opts.quiet === true);
10740
+ const get = fetch2 ?? liveFetch10(opts.quiet === true);
9925
10741
  if (typeof get !== "function") return get;
9926
10742
  const totalsRes = await get(VIEW_TOTALS_URL, viewTotalsBody(), "page");
9927
10743
  const totals = totalsRes.ok ? parseViewTotals(totalsRes.raw) : totalsRes;
@@ -9929,18 +10745,18 @@ async function runViewers(opts = {}, fetch2) {
9929
10745
  const list2 = listRes.ok ? parseViewers(listRes.raw) : listRes;
9930
10746
  if (!list2.ok) return err("viewers", list2.code, list2.message, list2.hint);
9931
10747
  const shown = list2.viewers.length;
9932
- const state = !totals.ok ? "unknown" : totals.total > shown ? "partial" : "complete";
10748
+ const state2 = !totals.ok ? "unknown" : totals.total > shown ? "partial" : "complete";
9933
10749
  return ok("viewers", {
9934
10750
  ...totals.ok ? { total: totals.total, ...totals.period !== void 0 ? { period: totals.period } : {} } : { totalError: `${totals.code}: ${totals.message}` },
9935
10751
  ...list2.privateViewers !== void 0 ? { privateViewers: list2.privateViewers } : {},
9936
10752
  items: shape(list2.viewers, opts, compactViewer),
9937
- meta: { state, operation: "viewers", returnedCount: shown }
10753
+ meta: { state: state2, operation: "viewers", returnedCount: shown }
9938
10754
  });
9939
10755
  }
9940
10756
 
9941
10757
  // src/entry.ts
9942
10758
  import { realpathSync } from "fs";
9943
- import { basename as basename2 } from "path";
10759
+ import { basename as basename3 } from "path";
9944
10760
  import { fileURLToPath } from "url";
9945
10761
  function isMainModule(argv1, moduleUrl, importMetaMain) {
9946
10762
  if (importMetaMain === true) return true;
@@ -9955,7 +10771,7 @@ function isMainModule(argv1, moduleUrl, importMetaMain) {
9955
10771
  }
9956
10772
  function shouldForceEntry(argv1, binNames) {
9957
10773
  if (argv1 === void 0) return false;
9958
- return binNames.includes(basename2(argv1));
10774
+ return binNames.includes(basename3(argv1));
9959
10775
  }
9960
10776
  function shouldRunAsEntry(argv1, moduleUrl, importMetaMain, binNames) {
9961
10777
  if (isMainModule(argv1, moduleUrl, importMetaMain)) {
@@ -10313,7 +11129,10 @@ async function dispatch(argv, now) {
10313
11129
  return runWhoami(bool(args, "raw"));
10314
11130
  case "profile":
10315
11131
  return runProfile(args.positionals[0], output(args), void 0, {
10316
- contact: bool(args, "contact")
11132
+ contact: bool(args, "contact"),
11133
+ skills: bool(args, "skills"),
11134
+ recommendations: bool(args, "recommendations"),
11135
+ ...num(args, "posts") !== void 0 ? { posts: num(args, "posts") } : {}
10317
11136
  });
10318
11137
  case "feed":
10319
11138
  return runFeed(num(args, "limit") ?? 10, output(args));
@@ -10333,6 +11152,11 @@ async function dispatch(argv, now) {
10333
11152
  return runPeopleFilters(peopleRequest(args), output(args));
10334
11153
  case "viewers":
10335
11154
  return runViewers(output(args));
11155
+ case "notifications":
11156
+ return runNotifications(
11157
+ { limit: num(args, "limit") ?? 25, ...bool(args, "unread") ? { unread: true } : {} },
11158
+ output(args)
11159
+ );
10336
11160
  case "events":
10337
11161
  case "event":
10338
11162
  case "company":
@@ -10394,13 +11218,14 @@ function edit(args, now, deps) {
10394
11218
  const [target2, inline] = args.positionals;
10395
11219
  if (args.flags.file === true) return err("edit", "INVALID_INPUT", "--file needs a path");
10396
11220
  const file = str(args, "file");
11221
+ if (target2 === "photo" || target2 === "banner") return runEdit(target2, file ?? inline, now, deps);
10397
11222
  if (file === void 0) return runEdit(target2, inline, now, deps);
10398
11223
  if (inline !== void 0) {
10399
11224
  return err("edit", "INVALID_INPUT", "pass the new text inline or with --file, not both");
10400
11225
  }
10401
11226
  let text6;
10402
11227
  try {
10403
- text6 = readFileSync4(file, "utf-8").replace(/\n$/, "");
11228
+ text6 = readFileSync5(file, "utf-8").replace(/\n$/, "");
10404
11229
  } catch {
10405
11230
  return err("edit", "INVALID_INPUT", `cannot read ${file}`);
10406
11231
  }
@@ -10431,7 +11256,7 @@ function role2(args, now, deps) {
10431
11256
  return err("role", "INVALID_INPUT", "pass --description or --description-file, not both");
10432
11257
  }
10433
11258
  try {
10434
- req.description = readFileSync4(file, "utf-8").replace(/\n$/, "");
11259
+ req.description = readFileSync5(file, "utf-8").replace(/\n$/, "");
10435
11260
  } catch {
10436
11261
  return err("role", "INVALID_INPUT", `cannot read ${file}`);
10437
11262
  }