@lobu/runtime-device 22.0.0 → 24.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +33 -30
  3. package/npm-shrinkwrap.json +140 -124
  4. package/package.json +2 -1
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +74 -1
  6. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +9 -11
  7. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +3 -11
  8. package/vendor/cli/dist/commands/_lib/apply/client.js +3 -3
  9. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +0 -6
  10. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +6 -15
  11. package/vendor/cli/dist/commands/_lib/apply/diff.js +1 -0
  12. package/vendor/cli/dist/commands/_lib/apply/map-config.js +8 -0
  13. package/vendor/cli/dist/commands/_lib/view-bundler.d.ts +2 -9
  14. package/vendor/cli/dist/commands/_lib/view-bundler.js +25 -97
  15. package/vendor/cli/dist/config/define.d.ts +8 -0
  16. package/vendor/cli/dist/connectors/README.md +15 -2
  17. package/vendor/cli/dist/connectors/google_gmail.ts +1 -0
  18. package/vendor/cli/dist/connectors/jira-helpers.ts +313 -0
  19. package/vendor/cli/dist/connectors/jira.ts +29 -221
  20. package/vendor/cli/dist/connectors/linkedin-browser-script.ts +13 -0
  21. package/vendor/cli/dist/connectors/linkedin-draft-page.js +104 -0
  22. package/vendor/cli/dist/connectors/linkedin-drafts.ts +73 -0
  23. package/vendor/cli/dist/connectors/linkedin-identity.ts +32 -0
  24. package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +1182 -0
  25. package/vendor/cli/dist/connectors/linkedin-inbox.ts +156 -0
  26. package/vendor/cli/dist/connectors/linkedin-like.ts +114 -0
  27. package/vendor/cli/dist/connectors/linkedin-takeout.ts +577 -0
  28. package/vendor/cli/dist/connectors/linkedin.ts +4017 -0
  29. package/vendor/cli/dist/connectors/reddit.ts +92 -20
  30. package/vendor/cli/dist/connectors/slack.ts +1 -0
  31. package/vendor/cli/dist/connectors/takeout-utils.ts +240 -0
  32. package/vendor/cli/dist/connectors/tiktok-inbox-page.js +9 -9
  33. package/vendor/cli/dist/connectors/tiktok-web-page.js +21 -15
  34. package/vendor/cli/dist/connectors/tiktok_web.ts +63 -30
  35. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +104 -574
  36. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +30 -444
  37. package/vendor/cli/dist/connectors/whatsapp-web-identity.ts +20 -6
  38. package/vendor/cli/dist/connectors/whatsapp_web.ts +46 -646
  39. package/vendor/cli/dist/connectors/x-dm-adapter.js +556 -0
  40. package/vendor/cli/dist/connectors/x-identity.ts +33 -2
  41. package/vendor/cli/dist/connectors/x.ts +266 -120
  42. package/vendor/cli/dist/runtime-components.json +4 -4
  43. package/vendor/cli/dist/templates/AGENTS.md.tmpl +12 -5
  44. package/vendor/cli/package.json +1 -1
  45. package/vendor/connector-sdk/dist/browser-handoff-banner.d.ts +39 -0
  46. package/vendor/connector-sdk/dist/browser-handoff-banner.js +175 -0
  47. package/vendor/connector-sdk/dist/browser-source-read.d.ts +52 -0
  48. package/vendor/connector-sdk/dist/browser-source-read.js +107 -0
  49. package/vendor/connector-sdk/dist/connector-types.d.ts +10 -0
  50. package/vendor/connector-sdk/dist/index.d.ts +3 -0
  51. package/vendor/connector-sdk/dist/index.js +2 -0
  52. package/vendor/connector-sdk/package.json +9 -1
  53. package/vendor/connector-worker/dist/agent-turn/gateway-tools.d.ts +2 -2
  54. package/vendor/connector-worker/dist/agent-turn/gateway-tools.js +2 -2
  55. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +49 -8
  56. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +650 -448
  57. package/vendor/connector-worker/dist/agent-turn/native-session.d.ts +12 -0
  58. package/vendor/connector-worker/dist/agent-turn/native-session.js +32 -6
  59. package/vendor/connector-worker/dist/agent-turn/types.d.ts +24 -3
  60. package/vendor/connector-worker/dist/daemon/agent-turn.js +5 -1
  61. package/vendor/connector-worker/dist/daemon/automation.d.ts +4 -11
  62. package/vendor/connector-worker/dist/daemon/automation.js +26 -21
  63. package/vendor/connector-worker/dist/daemon/client.d.ts +2 -4
  64. package/vendor/connector-worker/dist/daemon/client.js +0 -3
  65. package/vendor/connector-worker/dist/daemon/executor.js +0 -3
  66. package/vendor/connector-worker/dist/daemon/mac-device-daemon.d.ts +4 -3
  67. package/vendor/connector-worker/dist/daemon/mac-device-daemon.js +4 -10
  68. package/vendor/connector-worker/dist/daemon/native-bridge/executor.js +27 -25
  69. package/vendor/connector-worker/dist/daemon/start.js +3 -15
  70. package/vendor/connector-worker/dist/daemon/terminal-failure.js +0 -11
  71. package/vendor/connector-worker/dist/daemon/worker-id.d.ts +17 -0
  72. package/vendor/connector-worker/dist/daemon/worker-id.js +22 -0
  73. package/vendor/connector-worker/dist/isolate/prelude.js +93 -44
  74. package/vendor/connector-worker/dist/mac-device-daemon.js +14 -26
  75. package/vendor/connector-worker/package.json +1 -1
  76. package/vendor/core/dist/agent-policy.js +0 -3
  77. package/vendor/core/dist/agent-tooling.d.ts +1 -1
  78. package/vendor/core/dist/agent-tooling.js +3 -1
  79. package/vendor/core/dist/capabilities.d.ts +1 -1
  80. package/vendor/core/dist/capabilities.js +0 -1
  81. package/vendor/core/dist/connector-query-errors.d.ts +32 -0
  82. package/vendor/core/dist/connector-query-errors.js +41 -1
  83. package/vendor/core/dist/contracts/agent-settings.d.ts +6 -2
  84. package/vendor/core/dist/contracts/agent-settings.js +12 -1
  85. package/vendor/core/dist/contracts/tools/manage-conversations.js +2 -2
  86. package/vendor/core/dist/contracts/tools/manage-feeds.d.ts +14 -0
  87. package/vendor/core/dist/contracts/tools/manage-feeds.js +17 -0
  88. package/vendor/core/dist/contracts/tools/manage-views.d.ts +53 -234
  89. package/vendor/core/dist/contracts/tools/manage-views.js +50 -76
  90. package/vendor/core/dist/contracts/tools/view-attach.d.ts +5 -8
  91. package/vendor/core/dist/contracts/tools/view-attach.js +14 -31
  92. package/vendor/core/dist/contracts/tools/view-definition.d.ts +21 -0
  93. package/vendor/core/dist/contracts/tools/view-definition.js +165 -0
  94. package/vendor/core/dist/contracts/worker/protocol.d.ts +47 -133
  95. package/vendor/core/dist/contracts/worker/protocol.js +33 -62
  96. package/vendor/core/dist/device-pin-tombstones.d.ts +44 -0
  97. package/vendor/core/dist/device-pin-tombstones.js +57 -0
  98. package/vendor/core/dist/index.d.ts +3 -2
  99. package/vendor/core/dist/index.js +3 -1
  100. package/vendor/core/dist/logger.js +10 -25
  101. package/vendor/core/dist/suggestions.d.ts +15 -2
  102. package/vendor/core/dist/suggestions.js +48 -3
  103. package/vendor/core/dist/types.d.ts +26 -0
  104. package/vendor/core/dist/types.js +5 -0
  105. package/vendor/core/dist/utils/diagnostic-scrubber.js +258 -21
  106. package/vendor/core/dist/worker/wire.d.ts +0 -10
  107. package/vendor/core/package.json +16 -10
  108. package/vendor/postgres/cf/src/connection.js +18 -0
  109. package/vendor/postgres/cjs/src/connection.js +18 -0
  110. package/vendor/postgres/src/connection.js +18 -0
  111. package/vendor/connector-worker/dist/daemon/device-chat.d.ts +0 -9
  112. package/vendor/connector-worker/dist/daemon/device-chat.js +0 -61
  113. package/vendor/core/dist/contracts/worker/device-chat.d.ts +0 -4
  114. package/vendor/core/dist/contracts/worker/device-chat.js +0 -26
  115. /package/vendor/postgres/{.bun-tag-f39dafdb2305d504 → .bun-tag-2f292c6554a8475e} +0 -0
@@ -0,0 +1,1182 @@
1
+ /** Serialized into the signed-in page. All bindings must remain inside this function. */
2
+ export function linkedInInboxProgram() {
3
+ const key = "__lobuLinkedInInboxV1";
4
+ // An identical program keeps a warm tab's listeners; any code change reinstalls
5
+ // and asks the replaced program's listeners to reattach.
6
+ const version = linkedInInboxProgram.toString();
7
+ if (globalThis[key]?.version === version) return;
8
+ globalThis[key]?.detach();
9
+ const listeners = new Map();
10
+ const pagerId = "com.linkedin.sdui.pagers.notificationsList";
11
+ const encode = (value) =>
12
+ encodeURIComponent(value).replace(
13
+ /[!'()*]/g,
14
+ (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`
15
+ );
16
+ const clean = (value) =>
17
+ String(value ?? "")
18
+ .replace(/\s+/g, " ")
19
+ .trim();
20
+ function fail(message) {
21
+ throw new Error(`LinkedIn inbox: ${message}`);
22
+ }
23
+ function headers() {
24
+ const cookie = document.cookie
25
+ .split("; ")
26
+ .find((value) => value.startsWith("JSESSIONID="));
27
+ if (!cookie) fail("Sign in to LinkedIn in the paired browser");
28
+ return {
29
+ "csrf-token": decodeURIComponent(cookie.slice(11)).replace(/^"|"$/g, ""),
30
+ "x-restli-protocol-version": "2.0.0",
31
+ };
32
+ }
33
+ // `denied` names what a 401/403 means for this request, when it means more
34
+ // than a failed request.
35
+ async function request(url, init = {}, denied = null) {
36
+ const response = await fetch(url, {
37
+ credentials: "include",
38
+ signal: AbortSignal.timeout(20000),
39
+ ...init,
40
+ headers: { ...headers(), ...init.headers },
41
+ });
42
+ if (denied && (response.status === 401 || response.status === 403))
43
+ fail(denied);
44
+ if (!response.ok) fail(`Source request failed (HTTP ${response.status})`);
45
+ if (
46
+ response.redirected &&
47
+ /\/login|\/checkpoint|\/authwall/.test(new URL(response.url).pathname)
48
+ ) {
49
+ fail("Sign in to LinkedIn in the paired browser");
50
+ }
51
+ return response;
52
+ }
53
+ async function account() {
54
+ const self = await (await request("/voyager/api/me")).json();
55
+ const urn = self.miniProfile?.entityUrn;
56
+ if (typeof urn !== "string" || !urn.startsWith("urn:li:fs_miniProfile:"))
57
+ fail("Account identity is unavailable");
58
+ return urn.replace("fs_miniProfile", "fsd_profile");
59
+ }
60
+ const PAGE_MAILBOX = /^urn:li:fsd_pageMailbox:[0-9]+$/;
61
+ const NOT_ADMIN =
62
+ "The signed-in LinkedIn account does not administer this page inbox";
63
+ // The page's own inbox answers its admins only: LinkedIn's page inbox reads
64
+ // these counts first, and a non-admin is refused.
65
+ async function assertAdministers(mailbox) {
66
+ const json = await (
67
+ await request(
68
+ `/voyager/api/voyagerMessagingGraphQL/graphql?queryId=messengerMailboxCounts.fc528a5a81a76dff212a4a3d2d48e84b&variables=(mailboxUrn:${encode(mailbox)})`,
69
+ {},
70
+ NOT_ADMIN
71
+ )
72
+ ).json();
73
+ // Only the status and an answer are verified live; the collection's name
74
+ // is not, so any non-null answer counts and nothing else does.
75
+ if (
76
+ (Array.isArray(json?.errors) && json.errors.length) ||
77
+ !json?.data ||
78
+ typeof json.data !== "object" ||
79
+ Object.values(json.data).every((value) => value == null)
80
+ )
81
+ fail(NOT_ADMIN);
82
+ }
83
+ // The inbox one feed reads: the signed-in member's own ("me", the default),
84
+ // or a company page's mailbox the member administers. `member` is the
85
+ // signed-in account, which must not change while the inbox is in use.
86
+ async function inboxOf(selected) {
87
+ const member = await account();
88
+ if (selected === undefined || selected === null || selected === "me")
89
+ return { mailbox: member, member, page: false };
90
+ if (typeof selected !== "string" || !PAGE_MAILBOX.test(selected))
91
+ fail(
92
+ 'inbox must be "me" or a page mailbox URN (urn:li:fsd_pageMailbox:<number>)'
93
+ );
94
+ await assertAdministers(selected);
95
+ return { mailbox: selected, member, page: true };
96
+ }
97
+ // Whether a message was sent from this inbox. A member inbox's own messages
98
+ // carry the member's identity. A page inbox holds conversations between the
99
+ // page and members: a page reply's sender is the page's mailbox or the page
100
+ // as an organization participant, with the admin who sent it only as its
101
+ // actor. The signed-in admin writing as themselves is a member like any other.
102
+ function fromMe(sender, inbox) {
103
+ const host = sender?.hostIdentityUrn;
104
+ if (typeof host !== "string") return null;
105
+ if (!inbox.page) return host === inbox.mailbox;
106
+ return host === inbox.mailbox || !!sender.participantType?.organization;
107
+ }
108
+ // A page conversation's visitor-chosen topic, when LinkedIn shows one.
109
+ function topicOf(conversation, inbox) {
110
+ if (!inbox.page) return undefined;
111
+ for (const value of [
112
+ conversation?.topic,
113
+ conversation?.conversationTopic,
114
+ conversation?.subject,
115
+ ]) {
116
+ const text = clean(typeof value === "string" ? value : value?.text);
117
+ if (text) return text;
118
+ }
119
+ return undefined;
120
+ }
121
+ async function graph(query, variables, collection) {
122
+ const json = await (
123
+ await request(
124
+ `/voyager/api/voyagerMessagingGraphQL/graphql?queryId=${query}&variables=(${variables})`
125
+ )
126
+ ).json();
127
+ const result = json.data?.[collection];
128
+ if (!Array.isArray(result?.elements))
129
+ fail("Messaging source format changed");
130
+ return result;
131
+ }
132
+ function decodeFlight(stream) {
133
+ // Flight's T records count UTF-8 bytes, not UTF-16 characters or lines.
134
+ const bytes = new TextEncoder().encode(stream);
135
+ const decoder = new TextDecoder();
136
+ const records = new Map();
137
+ let position = 0;
138
+ while (position < bytes.length) {
139
+ if (bytes[position] === 10) {
140
+ position++;
141
+ continue;
142
+ }
143
+ const colon = bytes.indexOf(58, position);
144
+ if (colon < 0) break;
145
+ const id = decoder.decode(bytes.slice(position, colon));
146
+ if (!/^[0-9a-f]+$/.test(id)) fail("Invalid notification stream record");
147
+ position = colon + 1;
148
+ if (bytes[position] === 84) {
149
+ const comma = bytes.indexOf(44, position);
150
+ const hex = decoder.decode(bytes.slice(position + 1, comma));
151
+ if (comma < 0 || !/^[0-9a-f]+$/.test(hex))
152
+ fail("Invalid notification text record");
153
+ const end = comma + 1 + Number.parseInt(hex, 16);
154
+ if (end > bytes.length) fail("Truncated notification text");
155
+ records.set(id, decoder.decode(bytes.slice(comma + 1, end)));
156
+ position = end;
157
+ } else {
158
+ const newline = bytes.indexOf(10, position);
159
+ const end = newline < 0 ? bytes.length : newline;
160
+ const value = decoder.decode(bytes.slice(position, end));
161
+ if (/^[[{"]/.test(value)) records.set(id, JSON.parse(value));
162
+ position = end + 1;
163
+ }
164
+ }
165
+ return records;
166
+ }
167
+ function parseNotifications(stream, continuation = false) {
168
+ const records = decodeFlight(stream);
169
+ let visits = 0;
170
+ function resolve(value, depth = 0) {
171
+ if (++visits > 250000 || depth > 120)
172
+ fail("Notification structure exceeds the read budget");
173
+ if (typeof value === "string" && /^\$(?:L|Q)?[0-9a-f]+$/.test(value)) {
174
+ const id = value.replace(/^\$(L|Q)?/, "");
175
+ return records.has(id) ? resolve(records.get(id), depth + 1) : null;
176
+ }
177
+ if (Array.isArray(value))
178
+ return value.map((child) => resolve(child, depth + 1));
179
+ if (value && typeof value === "object")
180
+ return Object.fromEntries(
181
+ Object.entries(value).map(([name, child]) => [
182
+ name,
183
+ resolve(child, depth + 1),
184
+ ])
185
+ );
186
+ return value;
187
+ }
188
+ function walk(value, callback) {
189
+ if (!value || typeof value !== "object") return;
190
+ callback(value);
191
+ for (const child of Object.values(value)) walk(child, callback);
192
+ }
193
+ function text(value) {
194
+ if (typeof value === "string")
195
+ return value.startsWith("$$")
196
+ ? value.slice(1)
197
+ : value.startsWith("$")
198
+ ? ""
199
+ : value;
200
+ if (!Array.isArray(value)) return "";
201
+ if (value[0] === "$")
202
+ return text(value[3]?.textProps?.children ?? value[3]?.children);
203
+ return value.map(text).join("");
204
+ }
205
+ const rows = new Map();
206
+ let next = null;
207
+ let recognized = false;
208
+ for (const raw of records.values()) {
209
+ if (
210
+ typeof raw === "string" &&
211
+ raw.startsWith(
212
+ '{"$type":"proto.sdui.actions.requests.PaginationRequest"'
213
+ )
214
+ ) {
215
+ const request = JSON.parse(raw);
216
+ if (request.pagerId === pagerId) {
217
+ next = request.requestedArguments?.payload;
218
+ recognized = true;
219
+ }
220
+ }
221
+ if (raw?.[3]?.nextPageRequest?.pagerId === pagerId) {
222
+ next = raw[3].nextPageRequest.requestedArguments?.payload;
223
+ recognized = true;
224
+ }
225
+ if (!Array.isArray(raw) || raw[0]?.[0] !== "Original") continue;
226
+ recognized = true;
227
+ visits = 0;
228
+ const card = resolve(raw[0][1]);
229
+ let id = null;
230
+ let headline = "";
231
+ let url = null;
232
+ let age = null;
233
+ walk(card, (node) => {
234
+ const state = node.selectedStateKey?.key?.value?.id;
235
+ if (
236
+ typeof state === "string" &&
237
+ state.startsWith("NotificationReadState_FeNotificationV2Urn(")
238
+ ) {
239
+ id = state.slice("NotificationReadState_".length);
240
+ }
241
+ const props = node.textProps ?? node;
242
+ if (
243
+ String(props.componentkey ?? props.componentKey ?? "").startsWith(
244
+ "notification-card-headline_"
245
+ )
246
+ ) {
247
+ headline ||= clean(text(props.children));
248
+ }
249
+ const ageText = clean(text(node.textProps?.children));
250
+ if (/^\d+\s*(m|h|d|w|mo|yr)$/.test(ageText)) age ||= ageText;
251
+ if (
252
+ typeof node.url === "string" &&
253
+ node.url.startsWith("https://www.linkedin.com/")
254
+ )
255
+ url ||= node.url;
256
+ });
257
+ if (!id || !headline)
258
+ fail("Notification card identity or headline is unavailable");
259
+ // Unread state, relative age, and per-render tracking IDs are not content changes.
260
+ rows.set(id, {
261
+ id,
262
+ text: headline,
263
+ url: url ?? "https://www.linkedin.com/notifications/",
264
+ notification_type: /notificationType=([^)]*)\)$/.exec(id)?.[1] ?? null,
265
+ occurred_at: null,
266
+ source_age: age,
267
+ revision: headline,
268
+ });
269
+ }
270
+ // A continuation can end with the provider's empty partial-page envelope,
271
+ // without the full page's empty-state component. Accept that exact shape
272
+ // only after pagination; unknown content must still fail closed.
273
+ const root = records.get("0");
274
+ const shell = root?.[0]?.[0];
275
+ const emptyContinuation =
276
+ continuation &&
277
+ Array.isArray(root) &&
278
+ root.length === 10 &&
279
+ Array.isArray(root[0]) &&
280
+ root[0].length === 2 &&
281
+ root[0][1] === "$undefined" &&
282
+ Array.isArray(shell) &&
283
+ shell.length === 4 &&
284
+ shell[0] === "$" &&
285
+ typeof shell[1] === "string" &&
286
+ /^\$L[0-9a-f]+$/.test(shell[1]) &&
287
+ shell[2] === null &&
288
+ shell[3]?.isPartialPage === true &&
289
+ Object.keys(shell[3]).length === 2 &&
290
+ Array.isArray(shell[3].modelStates) &&
291
+ shell[3].modelStates.length === 0 &&
292
+ JSON.stringify(root.slice(1, 7)) ===
293
+ JSON.stringify([
294
+ "$undefined",
295
+ [],
296
+ "$undefined",
297
+ "$undefined",
298
+ "$0:0:0:props:modelStates",
299
+ null,
300
+ ]) &&
301
+ typeof root[7] === "string" &&
302
+ root[8] === "$undefined" &&
303
+ root[9]?.version === root[7] &&
304
+ Object.keys(root[9]).length === 1;
305
+ if (
306
+ !recognized &&
307
+ !emptyContinuation &&
308
+ !stream.includes("notifications-empty-state")
309
+ )
310
+ fail("Notification source format changed");
311
+ return { rows: [...rows.values()], next };
312
+ }
313
+ function pagePayload(value) {
314
+ if (
315
+ !value ||
316
+ !Number.isSafeInteger(value.startIndex) ||
317
+ value.startIndex < 0 ||
318
+ value.filterPillType !== "All" ||
319
+ !Array.isArray(value.trackingIdsToDrop) ||
320
+ value.trackingIdsToDrop.length > 1000 ||
321
+ value.trackingIdsToDrop.some(
322
+ (id) =>
323
+ typeof id !== "string" ||
324
+ !id.startsWith("EntityUrn(") ||
325
+ id.length > 2000
326
+ )
327
+ ) {
328
+ fail("Invalid notification cursor");
329
+ }
330
+ return {
331
+ startIndex: value.startIndex,
332
+ filterPillType: "All",
333
+ trackingIdsToDrop: value.trackingIdsToDrop,
334
+ };
335
+ }
336
+ async function notificationsPage(payload) {
337
+ let stream;
338
+ if (payload) {
339
+ const requestedArguments = {
340
+ $type: "proto.sdui.actions.requests.RequestedArguments",
341
+ requestedStateKeys: [],
342
+ payload: pagePayload(payload),
343
+ requestMetadata: { $type: "proto.sdui.common.RequestMetadata" },
344
+ };
345
+ // This one verified pagination action is read-only. Never replay arbitrary
346
+ // actions or headers from the provider response or from a caller's cursor.
347
+ const body = {
348
+ pagerId,
349
+ clientArguments: {
350
+ ...requestedArguments,
351
+ states: [],
352
+ screenId:
353
+ "com.linkedin.sdui.flagshipnav.notifications.NotificationPillType",
354
+ knownTemplateIds: [],
355
+ },
356
+ paginationRequest: {
357
+ $type: "proto.sdui.actions.requests.PaginationRequest",
358
+ pagerId,
359
+ retryCount: 2,
360
+ trigger: {
361
+ $case: "itemDistanceTrigger",
362
+ itemDistanceTrigger: {
363
+ $type: "proto.sdui.actions.requests.ItemDistanceTrigger",
364
+ preloadDistance: 3,
365
+ preloadLength: 250,
366
+ },
367
+ },
368
+ requestedArguments,
369
+ },
370
+ };
371
+ stream = await (
372
+ await request(
373
+ `/flagship-web/rsc-action/actions/pagination?sduiid=${pagerId}`,
374
+ {
375
+ method: "POST",
376
+ headers: {
377
+ "content-type": "application/json",
378
+ "x-li-rsc-stream": "true",
379
+ },
380
+ body: JSON.stringify(body),
381
+ }
382
+ )
383
+ ).text();
384
+ } else {
385
+ const html = await (await request("/notifications/")).text();
386
+ // Extract JSON as text; the live page strips scripts during DOM parsing.
387
+ // This is not an HTML sanitizer: nothing is rendered or
388
+ // executed. Honor quoted attributes and whitespace on closing tags.
389
+ const assignment = [
390
+ ...html.matchAll(
391
+ /<script\b(?:[^>"']|"[^"]*"|'[^']*')*>([\s\S]*?)<\/script\b[^>]*>/gi
392
+ ),
393
+ ]
394
+ .map((match) => match[1].trimStart())
395
+ .find((value) => value.startsWith("window.__como_rehydration__"));
396
+ if (!assignment)
397
+ fail("Notification source is unavailable; check sign-in");
398
+ const chunks = JSON.parse(
399
+ assignment
400
+ .slice(assignment.indexOf("=") + 1)
401
+ .trim()
402
+ .replace(/;$/, "")
403
+ );
404
+ if (
405
+ !Array.isArray(chunks) ||
406
+ chunks.some((chunk) => typeof chunk !== "string")
407
+ )
408
+ fail("Invalid notification stream");
409
+ stream = chunks.join("");
410
+ }
411
+ return parseNotifications(stream, !!payload);
412
+ }
413
+ async function conversationsPage(mailbox, cursor) {
414
+ return graph(
415
+ "messengerConversations.9501074288a12f3ae9e3c7ea243bccbf",
416
+ `query:(predicateUnions:List((conversationCategoryPredicate:(category:INBOX)))),count:20,mailboxUrn:${encode(mailbox)}${cursor ? `,nextCursor:${encode(cursor)}` : ""}`,
417
+ "messengerConversationsByCategoryQuery"
418
+ );
419
+ }
420
+ // A conversation is a group when LinkedIn says so or it has more than two
421
+ // participants. Null when neither is shown: callers treat unknown as "not a
422
+ // direct message", so nothing is ever sent into a group by mistake.
423
+ function groupOf(conversation) {
424
+ const participants = conversation?.conversationParticipants;
425
+ if (Array.isArray(participants) && participants.length > 2) return true;
426
+ if (typeof conversation?.groupChat === "boolean")
427
+ return conversation.groupChat;
428
+ return Array.isArray(participants) && participants.length > 0
429
+ ? false
430
+ : null;
431
+ }
432
+ // The thread token is the conversation's chat id: the URN minus the mailbox.
433
+ function threadOf(conversation, mailbox) {
434
+ if (
435
+ typeof conversation !== "string" ||
436
+ !conversation.startsWith(`urn:li:msg_conversation:(${mailbox},`)
437
+ )
438
+ fail("Invalid conversation identity");
439
+ const thread = conversation.slice(
440
+ `urn:li:msg_conversation:(${mailbox},`.length,
441
+ -1
442
+ );
443
+ if (!/^[A-Za-z0-9_-]+=*$/.test(thread))
444
+ fail("Unsupported conversation URL identity");
445
+ return thread;
446
+ }
447
+ function memberIdOf(urn) {
448
+ const match =
449
+ typeof urn === "string" &&
450
+ urn.match(/^urn:li:(?:fsd_profile|member):([A-Za-z0-9_-]+)$/);
451
+ return match ? match[1] : null;
452
+ }
453
+ // Only a vanity `/in/<slug>` URL names a slug; a member-id URL does not.
454
+ function slugOf(profileUrl) {
455
+ const match =
456
+ typeof profileUrl === "string" && profileUrl.match(/\/in\/([^/?#]+)/i);
457
+ if (!match || /^ACo/.test(match[1])) return null;
458
+ const slug = match[1].toLowerCase();
459
+ return /^[a-z0-9_-]+$/.test(slug) ? slug : null;
460
+ }
461
+ async function messageElements(conversation) {
462
+ return (
463
+ await graph(
464
+ "messengerMessages.5846eeb71c981f11e0134cb6626cc314",
465
+ `conversationUrn:${encode(conversation)}`,
466
+ "messengerMessagesBySyncToken"
467
+ )
468
+ ).elements;
469
+ }
470
+ async function messagesPage(conversation, inbox, group = null, topic) {
471
+ const thread = threadOf(conversation, inbox.mailbox);
472
+ const messages = await Promise.all(
473
+ (await messageElements(conversation)).map(async (message) => {
474
+ if (
475
+ typeof message.entityUrn !== "string" ||
476
+ !Number.isFinite(message.deliveredAt)
477
+ )
478
+ fail("Message identity or timestamp is unavailable");
479
+ const member = message.sender?.participantType?.member;
480
+ const recalled = message.messageBodyRenderFormat === "RECALLED";
481
+ const text = recalled
482
+ ? ""
483
+ : (message.body?.text ?? message.renderContentFallbackText ?? "");
484
+ const hasAttachments =
485
+ Array.isArray(message.renderContent) &&
486
+ message.renderContent.length > 0;
487
+ return {
488
+ id: message.entityUrn,
489
+ conversation_id: conversation,
490
+ thread_id: thread,
491
+ is_group: group,
492
+ // LinkedIn's router retains base64 padding in its canonical URL.
493
+ // Encoding '=' here leaves page-activated drafts waiting on a URL
494
+ // that differs from the one the user actually visits.
495
+ conversation_url: `https://www.linkedin.com/messaging/thread/${thread}/`,
496
+ text,
497
+ recalled,
498
+ // `text` is answerable; `media` carries attachments; `revoked` was
499
+ // recalled; `system` is LinkedIn's own event in the thread.
500
+ content_kind: recalled
501
+ ? "revoked"
502
+ : message.messageBodyRenderFormat === "SYSTEM"
503
+ ? "system"
504
+ : hasAttachments
505
+ ? "media"
506
+ : text.trim()
507
+ ? "text"
508
+ : "system",
509
+ source_revision: await digest(
510
+ JSON.stringify([
511
+ message.entityUrn,
512
+ conversation,
513
+ message.body,
514
+ message.renderContentFallbackText,
515
+ message.renderContent,
516
+ message.messageBodyRenderFormat,
517
+ message.sender?.hostIdentityUrn,
518
+ message.deliveredAt,
519
+ message.lastEditedAt,
520
+ ])
521
+ ),
522
+ has_attachments: hasAttachments,
523
+ sender_id: message.sender?.hostIdentityUrn ?? null,
524
+ sender_member_id: memberIdOf(message.sender?.hostIdentityUrn),
525
+ sender_slug: slugOf(member?.profileUrl),
526
+ sender_name: clean(
527
+ `${member?.firstName?.text ?? ""} ${member?.lastName?.text ?? ""}`
528
+ ),
529
+ from_me: fromMe(message.sender, inbox),
530
+ occurred_at: new Date(message.deliveredAt).toISOString(),
531
+ ...(topic ? { topic } : {}),
532
+ };
533
+ })
534
+ );
535
+ return messages.sort(
536
+ (a, b) =>
537
+ b.occurred_at.localeCompare(a.occurred_at) || a.id.localeCompare(b.id)
538
+ );
539
+ }
540
+ function cursorOf(raw, feed, inbox) {
541
+ if (!raw) return {};
542
+ if (typeof raw !== "string" || raw.length > 100000) fail("Invalid cursor");
543
+ const cursor = JSON.parse(raw);
544
+ if (
545
+ cursor.v !== 1 ||
546
+ cursor.feed !== feed ||
547
+ cursor.account !== inbox.mailbox ||
548
+ (cursor.member ?? cursor.account) !== inbox.member
549
+ )
550
+ fail("Cursor belongs to a different source or account");
551
+ return cursor;
552
+ }
553
+ // Resumes a source page after the cursor's last returned row.
554
+ function resume(rows, cursor, limit, source) {
555
+ const start = cursor.after
556
+ ? rows.findIndex((row) => row.id === cursor.after) + 1
557
+ : 0;
558
+ if (cursor.after && !start)
559
+ fail(`${source} cursor expired; restart the read`);
560
+ const page = rows.slice(start, start + limit);
561
+ return { rows: page, more: start + limit < rows.length };
562
+ }
563
+ async function readNotifications(cursor, limit) {
564
+ const source = await notificationsPage(cursor.page);
565
+ const { rows, more } = resume(source.rows, cursor, limit, "Notification");
566
+ const continuation = more
567
+ ? { page: cursor.page, after: rows.at(-1).id }
568
+ : source.next
569
+ ? { page: pagePayload(source.next) }
570
+ : null;
571
+ return { rows, continuation };
572
+ }
573
+ // Pages conversations, then each conversation's recent message page.
574
+ async function readMessages(cursor, limit, inbox) {
575
+ let threads = cursor.threads;
576
+ let groups = cursor.groups ?? [];
577
+ // Only a page inbox's cursor carries topics; a member cursor is unchanged.
578
+ let topics = cursor.topics;
579
+ let next = cursor.next;
580
+ if (!threads) {
581
+ const source = await conversationsPage(inbox.mailbox, cursor.page);
582
+ threads = source.elements.map((thread) => thread.entityUrn);
583
+ groups = source.elements.map(groupOf);
584
+ if (inbox.page)
585
+ topics = source.elements.map((thread) => topicOf(thread, inbox) ?? null);
586
+ next = source.metadata?.nextCursor;
587
+ }
588
+ if (
589
+ !Array.isArray(threads) ||
590
+ threads.length > 20 ||
591
+ !Array.isArray(groups) ||
592
+ (topics !== undefined && !Array.isArray(topics))
593
+ )
594
+ fail("Invalid message cursor");
595
+ const messages = threads.length
596
+ ? await messagesPage(
597
+ threads[0],
598
+ inbox,
599
+ groups[0] ?? null,
600
+ typeof topics?.[0] === "string" ? topics[0] : undefined
601
+ )
602
+ : [];
603
+ const { rows, more } = resume(messages, cursor, limit, "Message");
604
+ const continuation = more
605
+ ? { threads, groups, topics, next, after: rows.at(-1).id }
606
+ : threads.length > 1
607
+ ? {
608
+ threads: threads.slice(1),
609
+ groups: groups.slice(1),
610
+ topics: topics?.slice(1),
611
+ next,
612
+ }
613
+ : next
614
+ ? { page: next }
615
+ : null;
616
+ return { rows, continuation };
617
+ }
618
+ // Walks the inbox from the most recently active conversation, following
619
+ // LinkedIn's cursor to the end of the inbox, and returns the first non-null
620
+ // `visit` result. Catch-up can observe a thread on any page, so a lookup
621
+ // must reach it too: running out of time fails (the caller retries) rather
622
+ // than reporting the target absent.
623
+ async function searchConversations(mailbox, visit) {
624
+ const deadline = Date.now() + LOOKUP_DEADLINE_MS;
625
+ let cursor;
626
+ for (;;) {
627
+ if (Date.now() > deadline)
628
+ fail("The inbox search ran out of time before reaching the end; retry");
629
+ const source = await conversationsPage(mailbox, cursor);
630
+ for (const thread of source.elements) {
631
+ const found = await visit(thread);
632
+ if (found) return found;
633
+ }
634
+ cursor = source.metadata?.nextCursor;
635
+ if (typeof cursor !== "string" || !cursor || cursor.length > 4096)
636
+ return null;
637
+ }
638
+ }
639
+ // A message reference names no conversation, so `id:<message URN>` searches
640
+ // the inbox from the most recently active conversation: a new message's
641
+ // thread is near the top. Not found is an empty page; the caller retries.
642
+ async function findMessage(id, inbox) {
643
+ const row = await searchConversations(
644
+ inbox.mailbox,
645
+ async (thread) =>
646
+ (
647
+ await messagesPage(
648
+ thread.entityUrn,
649
+ inbox,
650
+ groupOf(thread),
651
+ topicOf(thread, inbox)
652
+ )
653
+ ).find((message) => message.id === id) ?? null
654
+ );
655
+ return { rows: row ? [row] : [], continuation: null };
656
+ }
657
+ async function read(input) {
658
+ const inbox = await inboxOf(
659
+ input.feed === "live_messages" ? input.inbox : undefined
660
+ );
661
+ const mailbox = inbox.mailbox;
662
+ const cursor = cursorOf(input.cursor, input.feed, inbox);
663
+ const limit = Math.max(1, Math.min(100, input.limit ?? 20));
664
+ const byId =
665
+ input.feed === "live_messages" &&
666
+ typeof input.query === "string" &&
667
+ input.query.startsWith("id:")
668
+ ? input.query.slice(3).trim()
669
+ : null;
670
+ if (byId !== null && (!byId.startsWith("urn:li:msg_message:") || input.cursor))
671
+ fail("Message lookup takes one id:<message URN> and no cursor");
672
+ const { rows, continuation } =
673
+ input.feed === "notifications"
674
+ ? await readNotifications(cursor, limit)
675
+ : byId
676
+ ? await findMessage(byId, inbox)
677
+ : input.feed === "live_messages"
678
+ ? await readMessages(cursor, limit, inbox)
679
+ : fail("Unknown source feed");
680
+ if ((await account()) !== inbox.member)
681
+ fail("LinkedIn account changed during the read");
682
+ return {
683
+ rows: await Promise.all(
684
+ rows.map(async (row) => ({
685
+ ...row,
686
+ source_revision:
687
+ row.source_revision ??
688
+ (await digest(
689
+ JSON.stringify([row.id, row.text, row.url, row.notification_type])
690
+ )),
691
+ }))
692
+ ),
693
+ hasMore: !!continuation,
694
+ ...(continuation
695
+ ? {
696
+ nextCursor: JSON.stringify({
697
+ v: 1,
698
+ feed: input.feed,
699
+ account: mailbox,
700
+ ...(inbox.page ? { member: inbox.member } : {}),
701
+ ...continuation,
702
+ }),
703
+ }
704
+ : {}),
705
+ };
706
+ }
707
+ async function digest(value) {
708
+ const bytes = await crypto.subtle.digest(
709
+ "SHA-256",
710
+ new TextEncoder().encode(value)
711
+ );
712
+ return [...new Uint8Array(bytes)]
713
+ .map((byte) => byte.toString(16).padStart(2, "0"))
714
+ .join("");
715
+ }
716
+ // One observation pass is bounded source work. Message catch-up resumes from
717
+ // its checkpoint; notifications reorder at the top and report a gap instead.
718
+ const NOTIFICATION_PAGES_PER_PASS = 10;
719
+ const CONVERSATION_PAGES_PER_PASS = 2;
720
+ // Lookups by id or conversation reach the 100 most recently active threads.
721
+ // Under the server's 60-second source read deadline.
722
+ const LOOKUP_DEADLINE_MS = 45000;
723
+ const RECENT_MESSAGE_PAGE = 20;
724
+ const SEEN_LIMIT = 256;
725
+ const BATCH_EVENTS = 500;
726
+ const BATCH_BYTES = 128 * 1024;
727
+ // Each observer returns its checkpoint position, plus `more` when the round
728
+ // continues on the next pass.
729
+ async function observeNotifications({ previous, observe, gap }) {
730
+ let payload;
731
+ for (let page = 1; ; page++) {
732
+ const { rows, next } = await notificationsPage(payload);
733
+ let anchored = false;
734
+ for (const row of rows) {
735
+ if (
736
+ await observe(
737
+ row,
738
+ "notification.changed",
739
+ "notification",
740
+ row.revision
741
+ )
742
+ )
743
+ anchored = true;
744
+ }
745
+ if (!previous || anchored || !next) break;
746
+ if (page === NOTIFICATION_PAGES_PER_PASS) {
747
+ await gap(
748
+ "notification",
749
+ "https://www.linkedin.com/notifications/",
750
+ rows.at(-1)?.id ?? page
751
+ );
752
+ break;
753
+ }
754
+ payload = next;
755
+ }
756
+ // `seen` is the whole position: an unchanged inbox repeats its checkpoint.
757
+ return {};
758
+ }
759
+ async function catchUpConversation(
760
+ { previous, observe, gap },
761
+ thread,
762
+ round,
763
+ inbox
764
+ ) {
765
+ const messages = await messagesPage(
766
+ thread.entityUrn,
767
+ inbox,
768
+ groupOf(thread),
769
+ topicOf(thread, inbox)
770
+ );
771
+ let reachedSeen = false;
772
+ for (const row of messages) {
773
+ if (Date.parse(row.occurred_at) < round.floor) continue;
774
+ if (await observe(row, "message.created", "message")) reachedSeen = true;
775
+ }
776
+ const oldest = messages.at(-1);
777
+ // A full recent page that neither reaches the floor nor a message already
778
+ // observed may hide older arrivals. LinkedIn offers no further page here,
779
+ // so report the gap and continue.
780
+ if (
781
+ previous &&
782
+ messages.length >= RECENT_MESSAGE_PAGE &&
783
+ !reachedSeen &&
784
+ Date.parse(oldest.occurred_at) >= round.floor
785
+ ) {
786
+ await gap(
787
+ "conversation",
788
+ thread.entityUrn,
789
+ oldest.id,
790
+ oldest.occurred_at
791
+ );
792
+ }
793
+ }
794
+ async function catchUpMessages(pass, inbox) {
795
+ const { previous, observedAt } = pass;
796
+ const startedAt = previous?.started_at ?? observedAt;
797
+ // A round reads threads active since `since` and their messages since
798
+ // `floor`. A round that spans passes keeps its lower bounds, and the next
799
+ // round keeps its floor: a thread that moved above the resume cursor is
800
+ // then read again from the top with the earlier floor.
801
+ const round = previous?.round ?? {
802
+ since: previous
803
+ ? Math.max(startedAt, previous.after - 60000)
804
+ : observedAt,
805
+ until: observedAt,
806
+ floor: previous?.floor ?? observedAt,
807
+ cursor: null,
808
+ };
809
+ round.floor = Math.min(round.floor, round.since);
810
+ let cursor = round.cursor;
811
+ for (let page = 1; ; page++) {
812
+ const result = await conversationsPage(inbox.mailbox, cursor);
813
+ const active = result.elements.filter((thread) => {
814
+ if (!Number.isFinite(thread.lastActivityAt))
815
+ fail("Conversation activity is unavailable");
816
+ return thread.lastActivityAt >= round.since;
817
+ });
818
+ for (const thread of active)
819
+ await catchUpConversation(pass, thread, round, inbox);
820
+ const next =
821
+ active.length === result.elements.length
822
+ ? (result.metadata?.nextCursor ?? null)
823
+ : null;
824
+ if (next !== null && (typeof next !== "string" || next.length > 4096))
825
+ fail("Invalid conversation cursor");
826
+ if (!previous || next === null) break;
827
+ cursor = next;
828
+ if (page === CONVERSATION_PAGES_PER_PASS) {
829
+ return {
830
+ started_at: startedAt,
831
+ after: previous.after,
832
+ floor: previous.floor,
833
+ round: { ...round, cursor },
834
+ more: true,
835
+ };
836
+ }
837
+ }
838
+ return {
839
+ started_at: startedAt,
840
+ after: round.until,
841
+ floor: previous?.round ? round.floor : round.since,
842
+ };
843
+ }
844
+ async function snapshot(feed, previous, inbox) {
845
+ const observedAt = Date.now();
846
+ const observed = new Map();
847
+ const events = [];
848
+ // Returns whether the previous checkpoint already held this identity.
849
+ async function observe(row, eventType, resourceType, revisionText) {
850
+ const identity = await digest(row.id);
851
+ const revision =
852
+ revisionText === undefined ? identity : await digest(revisionText);
853
+ const prior = previous?.seen[identity];
854
+ if (previous && prior !== revision && !observed.has(identity)) {
855
+ events.push({
856
+ id: `${identity}:${revision}`,
857
+ event_type: eventType,
858
+ resource_type: resourceType,
859
+ resource_ref: row.id,
860
+ occurred_at: row.occurred_at ?? new Date(observedAt).toISOString(),
861
+ });
862
+ }
863
+ observed.set(identity, revision);
864
+ return prior !== undefined;
865
+ }
866
+ // The provider cannot show what lies beyond this position. Report it once
867
+ // per position and advance, rather than retrying or claiming completeness.
868
+ async function gap(resourceType, resourceRef, beyond, occurredAt) {
869
+ events.push({
870
+ id: `gap:${await digest(JSON.stringify([resourceRef, beyond]))}`,
871
+ event_type: "source.gap",
872
+ resource_type: resourceType,
873
+ resource_ref: resourceRef,
874
+ occurred_at: occurredAt ?? new Date(observedAt).toISOString(),
875
+ });
876
+ }
877
+ const pass = { previous, observedAt, observe, gap };
878
+ const { more = false, ...position } =
879
+ feed === "notifications"
880
+ ? await observeNotifications(pass)
881
+ : await catchUpMessages(pass, inbox);
882
+ if ((await account()) !== inbox.member)
883
+ fail("LinkedIn account changed during observation");
884
+ const checkpoint = {
885
+ feed,
886
+ account: inbox.mailbox,
887
+ ...(inbox.page ? { member: inbox.member } : {}),
888
+ ...position,
889
+ // Keep this pass's identities first, in source order, then older ones.
890
+ seen: Object.fromEntries(
891
+ [
892
+ ...observed,
893
+ ...Object.entries(previous?.seen ?? {}).filter(
894
+ ([identity]) => !observed.has(identity)
895
+ ),
896
+ ].slice(0, SEEN_LIMIT)
897
+ ),
898
+ };
899
+ return { checkpoint, events, more };
900
+ }
901
+ // Ordered batches of at most 500 references and 128 KiB. Only the final
902
+ // batch carries the checkpoint, so an interruption cannot skip references.
903
+ async function batchesOf(feed, previous, result) {
904
+ const next = { linkedin_inbox: result.checkpoint };
905
+ const { events } = result;
906
+ const base = `${feed}:${await digest(JSON.stringify([previous, next, events]))}`;
907
+ const size = (batch) =>
908
+ new TextEncoder().encode(JSON.stringify(batch)).length;
909
+ const batches = [];
910
+ for (let offset = 0; ; ) {
911
+ const through = (end) => ({
912
+ id: `${base}:${offset}`,
913
+ events: events.slice(offset, end),
914
+ ...(end === events.length
915
+ ? { checkpoint: { previous, next }, more: result.more }
916
+ : {}),
917
+ });
918
+ let end = Math.min(offset + BATCH_EVENTS, events.length);
919
+ let batch = through(end);
920
+ while (size(batch) > BATCH_BYTES && end - offset > 1) {
921
+ end = offset + Math.floor((end - offset) / 2);
922
+ batch = through(end);
923
+ }
924
+ if (size(batch) > BATCH_BYTES)
925
+ fail("Source reference batch exceeds the browser record limit");
926
+ batches.push(batch);
927
+ if (end === events.length) return batches;
928
+ offset = end;
929
+ }
930
+ }
931
+ const active = (listener) => listeners.get(listener.id) === listener;
932
+ function post(listener, record) {
933
+ window.postMessage(
934
+ {
935
+ type: "lobu-feed-record",
936
+ token: listener.token,
937
+ sequence: ++listener.sequence,
938
+ record,
939
+ },
940
+ location.origin
941
+ );
942
+ }
943
+ // The one way a listener ends. A reason asks the bridge to reattach from the
944
+ // durable checkpoint; only an explicit stop or a same-binding relisten is silent.
945
+ function stop(listener, reason) {
946
+ if (!active(listener)) return;
947
+ clearTimeout(listener.timer);
948
+ window.removeEventListener("message", listener.onReply);
949
+ listeners.delete(listener.id);
950
+ if (reason)
951
+ post(listener, {
952
+ id: `linkedin:${listener.feed}:source-observation-error`,
953
+ source_error: reason,
954
+ });
955
+ }
956
+ // Called by a replacing program version: its listeners cannot inherit this
957
+ // one's undelivered batches, so each reattaches instead of going silent.
958
+ function detach() {
959
+ for (const listener of [...listeners.values()])
960
+ stop(
961
+ listener,
962
+ "LinkedIn source program was replaced; reattach from the durable checkpoint"
963
+ );
964
+ }
965
+ // Unacknowledged batches are reposted unchanged on the next tick.
966
+ async function poll(listener) {
967
+ if (!active(listener)) return;
968
+ try {
969
+ if (!listener.batches.length) {
970
+ const { feed, checkpoint, inbox } = listener;
971
+ if ((await account()) !== inbox.member)
972
+ fail("LinkedIn account changed; reconnect this source");
973
+ // A checkpoint of another inbox (the feed's inbox setting changed)
974
+ // restarts from a fresh baseline; the batch still names it as the
975
+ // previous checkpoint it replaces.
976
+ const prior = checkpoint?.linkedin_inbox;
977
+ const result = await snapshot(
978
+ feed,
979
+ prior?.account === inbox.mailbox ? prior : undefined,
980
+ inbox
981
+ );
982
+ listener.batches = await batchesOf(feed, checkpoint, result);
983
+ }
984
+ if (active(listener)) post(listener, listener.batches[0]);
985
+ } catch {
986
+ stop(
987
+ listener,
988
+ "LinkedIn source observation failed; reconnect to recover without skipping changes"
989
+ );
990
+ }
991
+ if (active(listener))
992
+ listener.timer = setTimeout(() => poll(listener), 60000);
993
+ }
994
+ function receive(listener, event) {
995
+ if (
996
+ event.source !== window ||
997
+ event.origin !== location.origin ||
998
+ event.data?.token !== listener.token
999
+ )
1000
+ return;
1001
+ if (event.data.type === "lobu-feed-record:stop") return stop(listener);
1002
+ if (
1003
+ event.data.type !== "lobu-feed-record:ack" ||
1004
+ event.data.sequence !== listener.sequence
1005
+ )
1006
+ return;
1007
+ if (event.data.ok === false)
1008
+ return stop(
1009
+ listener,
1010
+ "LinkedIn source delivery was rejected; reattach from the durable checkpoint"
1011
+ );
1012
+ if (event.data.ok && listener.batches.length) {
1013
+ // Receipt means the browser durably buffered the batch. Only the server
1014
+ // commits the final batch's checkpoint; a reattach starts from that value.
1015
+ const done = listener.batches.shift();
1016
+ if (done.checkpoint) listener.checkpoint = done.checkpoint.next;
1017
+ else post(listener, listener.batches[0]);
1018
+ }
1019
+ }
1020
+ // Direct send, approved ONLY for replying to direct messages on accounts the
1021
+ // owner operates. One reply per idempotency key: the key becomes LinkedIn's
1022
+ // client origin token, so a retry finds the first attempt instead of sending
1023
+ // again. Group or unknown conversations are refused.
1024
+ const SEND_RECONFIRM_ATTEMPTS = 5;
1025
+ async function originTokenOf(mailbox, conversation, idempotencyKey) {
1026
+ const hex = await digest(
1027
+ JSON.stringify([mailbox, conversation, idempotencyKey])
1028
+ );
1029
+ // UUID-shaped (version 4 / variant bits set), like LinkedIn's own tokens.
1030
+ return [
1031
+ hex.slice(0, 8),
1032
+ hex.slice(8, 12),
1033
+ `4${hex.slice(13, 16)}`,
1034
+ `${((Number.parseInt(hex[16], 16) & 3) | 8).toString(16)}${hex.slice(17, 20)}`,
1035
+ hex.slice(20, 32),
1036
+ ].join("-");
1037
+ }
1038
+ function trackingId() {
1039
+ // 64 symbols, so masking a random byte to 6 bits is unbiased.
1040
+ const alphabet =
1041
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1042
+ return [...crypto.getRandomValues(new Uint8Array(16))]
1043
+ .map((byte) => alphabet[byte & 63])
1044
+ .join("");
1045
+ }
1046
+ // `conversation_id` is a thread id of the member's own inbox, or a full
1047
+ // conversation URN whose mailbox names the inbox the reply leaves from: the
1048
+ // member's own or a page the member administers.
1049
+ async function sendTarget(given) {
1050
+ if (typeof given === "string" && /^[A-Za-z0-9_-]+=*$/.test(given)) {
1051
+ const member = await account();
1052
+ return { inbox: { mailbox: member, member, page: false }, thread: given };
1053
+ }
1054
+ const match =
1055
+ typeof given === "string" &&
1056
+ given.match(
1057
+ /^urn:li:msg_conversation:\((urn:li:fsd_profile:[A-Za-z0-9_-]+|urn:li:fsd_pageMailbox:[0-9]+),([A-Za-z0-9_-]+=*)\)$/
1058
+ );
1059
+ if (!match)
1060
+ fail(
1061
+ "conversation_id must be a LinkedIn conversation thread id or conversation URN"
1062
+ );
1063
+ if (PAGE_MAILBOX.test(match[1]))
1064
+ return { inbox: await inboxOf(match[1]), thread: match[2] };
1065
+ const member = await account();
1066
+ if (match[1] !== member)
1067
+ fail("The conversation belongs to another LinkedIn account; not sending");
1068
+ return { inbox: { mailbox: member, member, page: false }, thread: match[2] };
1069
+ }
1070
+ async function send(input) {
1071
+ const { inbox, thread } = await sendTarget(input.conversation_id);
1072
+ const mailbox = inbox.mailbox;
1073
+ const text = typeof input.text === "string" ? input.text.trim() : "";
1074
+ if (!text || text.length > 3000)
1075
+ fail("text must contain 1-3000 characters");
1076
+ const idempotencyKey = input.idempotency_key;
1077
+ if (typeof idempotencyKey !== "string" || !idempotencyKey)
1078
+ fail("idempotency_key is required");
1079
+ const conversation = `urn:li:msg_conversation:(${mailbox},${thread})`;
1080
+ const recent = await searchConversations(
1081
+ mailbox,
1082
+ async (element) => (element.entityUrn === conversation ? element : null)
1083
+ );
1084
+ if (!recent)
1085
+ fail("The conversation is not in the inbox; not sending");
1086
+ if (groupOf(recent) !== false)
1087
+ fail("send_message only answers direct messages; this conversation is a group or its membership is unknown");
1088
+ const originToken = await originTokenOf(mailbox, conversation, idempotencyKey);
1089
+ const sent = (message) => ({
1090
+ sent: true,
1091
+ message_id: message.entityUrn,
1092
+ conversation_id: input.conversation_id,
1093
+ delivered_at: Number.isFinite(message.deliveredAt)
1094
+ ? new Date(message.deliveredAt).toISOString()
1095
+ : null,
1096
+ });
1097
+ const prior = (await messageElements(conversation)).find(
1098
+ (message) =>
1099
+ fromMe(message.sender, inbox) === true &&
1100
+ message.originToken === originToken
1101
+ );
1102
+ if (prior) return { ...sent(prior), already_sent: true };
1103
+ if ((await account()) !== inbox.member)
1104
+ fail("LinkedIn account changed during conversation lookup; not sending");
1105
+ const response = await (
1106
+ await request(
1107
+ "/voyager/api/voyagerMessagingDashMessengerMessages?action=createMessage",
1108
+ {
1109
+ method: "POST",
1110
+ headers: {
1111
+ "content-type": "application/json",
1112
+ accept: "application/json",
1113
+ },
1114
+ body: JSON.stringify({
1115
+ message: {
1116
+ body: { attributes: [], text },
1117
+ renderContentUnions: [],
1118
+ conversationUrn: conversation,
1119
+ originToken,
1120
+ },
1121
+ mailboxUrn: mailbox,
1122
+ trackingId: trackingId(),
1123
+ // Reads can lag or omit origin tokens, so request provider-side
1124
+ // deduplication for retries and concurrent attempts too.
1125
+ dedupeByClientGeneratedToken: true,
1126
+ }),
1127
+ }
1128
+ )
1129
+ ).json();
1130
+ const messageId = response?.value?.entityUrn;
1131
+ // Confirm the message is in the conversation before reporting success.
1132
+ for (let attempt = 0; attempt < SEND_RECONFIRM_ATTEMPTS; attempt++) {
1133
+ const shown = (await messageElements(conversation)).find(
1134
+ (message) =>
1135
+ fromMe(message.sender, inbox) === true &&
1136
+ ((typeof messageId === "string" && message.entityUrn === messageId) ||
1137
+ message.originToken === originToken)
1138
+ );
1139
+ if (shown) return sent(shown);
1140
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1141
+ }
1142
+ fail("LinkedIn accepted the message but it did not appear in the conversation; retry with the same idempotency_key to reconcile");
1143
+ }
1144
+ async function listen(input) {
1145
+ if (!input.bridge_id || !input.token)
1146
+ fail("Source subscription binding is required");
1147
+ const inbox = await inboxOf(
1148
+ input.feed === "live_messages" ? input.inbox : undefined
1149
+ );
1150
+ const previous = input.checkpoint?.linkedin_inbox;
1151
+ // A mailbox change restarts the baseline, but never permits a changed sign-in.
1152
+ if (
1153
+ previous &&
1154
+ (previous.feed !== input.feed ||
1155
+ (previous.member ?? previous.account) !== inbox.member)
1156
+ )
1157
+ fail("Source checkpoint belongs to another account or feed");
1158
+ const prior = listeners.get(input.bridge_id);
1159
+ if (prior) stop(prior);
1160
+ const listener = {
1161
+ id: input.bridge_id,
1162
+ token: input.token,
1163
+ feed: input.feed,
1164
+ inbox,
1165
+ // The last posted record; only its receipt may advance delivery.
1166
+ sequence: 0,
1167
+ // The checkpoint the next snapshot starts from, set by the final batch's receipt.
1168
+ checkpoint: input.checkpoint ?? null,
1169
+ // Undelivered batches of the current snapshot, in order.
1170
+ batches: [],
1171
+ timer: null,
1172
+ };
1173
+ listener.onReply = (event) => receive(listener, event);
1174
+ listeners.set(listener.id, listener);
1175
+ window.addEventListener("message", listener.onReply);
1176
+ await poll(listener);
1177
+ if (!listeners.has(listener.id))
1178
+ fail("Unable to attach source subscription");
1179
+ return { listening: true };
1180
+ }
1181
+ globalThis[key] = { version, read, listen, send, detach };
1182
+ }