ilml-plugin-linkedin 1.2.2 → 1.3.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/CHANGELOG.md +11 -0
- package/README.md +70 -41
- package/dist/funnelRunner.mjs +20 -18
- package/dist/messageBot.mjs +101 -101
- package/dist/run.mjs +38 -38
- package/dist/scout.mjs +86 -86
- package/dist/src/saveLoginState.mjs +3 -3
- package/dist/syncAll.mjs +98 -98
- package/dist/viewers.mjs +85 -85
- package/dist/visit.mjs +85 -85
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.3.0
|
|
4
|
+
- **Behavior change — LinkedIn session cookies now live in the active ilml scope** instead of in the plugin install directory. New path: `<scope>/.ilivemylife/plugins-state/linkedin/cookies.json` (production) / `./cookies.json` next to `ilml-plugin.json` (dev mode, unchanged). This means:
|
|
5
|
+
- `ilml plugin update linkedin` no longer wipes your LinkedIn session — sessions survive plugin updates
|
|
6
|
+
- `ilml logout` correctly clears the LinkedIn session in that scope (alongside other user-tied data)
|
|
7
|
+
- Different ilml login scopes (e.g. global vs `--local` per project) hold separate LinkedIn sessions — useful for multiple LinkedIn accounts
|
|
8
|
+
- **One-time:** after upgrading to 1.3.0, run `ilml linkedin login` once. The old session was inside the install dir which got wiped by the upgrade
|
|
9
|
+
- README rewritten with marketing-first framing — leads with what users *get* (your LinkedIn data finally yours, AI-assisted messaging, terminal-first automation, Easy Apply that actually thinks) before diving into install/configure
|
|
10
|
+
- New section: **Save AI tokens — tune the node settings** — explains how to use `ilml editSettings` to set `intelligence: disabled` (cheaper model) and `rootAccess: disabled` (skip whole-graph context lookup) on the Easy Apply node to control token spend
|
|
11
|
+
- Improved **Where things live** table — clearer per-row "wiped on plugin update?" / "wiped on `ilml logout`?" columns; explicitly highlights that `DATA_DIR` survives both
|
|
12
|
+
- Internal: new `src/cookiesStore.mjs` is the single source of truth for cookie path resolution. All cookie readers/writers in published entries (`src/browser.mjs`, `src/saveLoginState.mjs`, `run.mjs`, `funnelRunner.mjs`) go through it. SDK and CLI APIs unchanged
|
|
13
|
+
|
|
3
14
|
## 1.2.2
|
|
4
15
|
- README polish based on real-user feedback:
|
|
5
16
|
- Cleaner top — removed the metadata bullet list (npm/tracker/license) that was the very first thing visitors saw on the npm page; now opens straight into "What it does"
|
package/README.md
CHANGED
|
@@ -1,27 +1,26 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Your LinkedIn — finally yours
|
|
2
2
|
|
|
3
|
-
LinkedIn
|
|
3
|
+
LinkedIn keeps your **connections, conversations, and the notes you write about people** locked inside their interface. You can't export message threads. You can't query an AI on your own contact history. You can't run batch operations from a script. You can't keep a personal database of who said what when.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
This plugin pulls all of that onto your machine and into your [iLiveMyLife](https://ilivemylife.io) knowledge graph — where it's searchable, syncable, AI-queryable, and yours to keep forever. Even if you uninstall the plugin or switch ilml accounts, **your accumulated data stays where you put it**.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
It also automates LinkedIn from the terminal — applying to jobs, drafting outreach, processing recruiter funnels — so you can script what LinkedIn's web UI makes you do one click at a time.
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
- **Inbox sync** — scans LinkedIn messages, detects changes, and mirrors threads into your graph.
|
|
11
|
-
- **Message bot** — draft → review → send batch messaging workflow (you approve before anything is sent).
|
|
12
|
-
- **Connection funnel** — process recruiter / founder / investor profiles in batches (connect, skip, message).
|
|
13
|
-
- **Scout** — find jobs without applying; reports back which match your filters.
|
|
14
|
-
- **Profile activity** — track who viewed your profile, who you visited, etc.
|
|
9
|
+
---
|
|
15
10
|
|
|
16
|
-
|
|
11
|
+
## What you get
|
|
17
12
|
|
|
18
|
-
|
|
13
|
+
- **A full local mirror of your LinkedIn graph.** Connections, conversation threads, message history, profile metadata, your private notes about people — synced into your iLiveMyLife graph and a local database. Nothing stays trapped in linkedin.com.
|
|
14
|
+
- **AI-assisted messaging.** [Lifebot](https://ilivemylife.io) reads the full context of each thread (history, your notes, tags) and helps you draft replies in your voice. No copy-pasting into ChatGPT, no losing context, no generic templates.
|
|
15
|
+
- **Terminal-first automation.** Batch operations — apply to dozens of jobs at once, draft 50 outreach messages then review them all in one pass, run a connection campaign on a schedule. Scriptable. Re-runnable. Logged.
|
|
16
|
+
- **Easy Apply that actually thinks.** Auto-fills LinkedIn job applications, with Lifebot answering custom questions ("Why are you interested in this role?") in your voice using context from your graph — not boilerplate.
|
|
17
|
+
- **Your data outlives the plugin.** The connection database, conversation history, and your notes live in a directory **you** choose (`DATA_DIR`). Plugin updates don't wipe them. Logging out of ilml doesn't wipe them. Uninstalling the plugin doesn't wipe them. Only **you** decide when they go.
|
|
19
18
|
|
|
20
|
-
|
|
19
|
+
---
|
|
21
20
|
|
|
22
21
|
## Prerequisites
|
|
23
22
|
|
|
24
|
-
- **Node.js 18+** — [download](https://nodejs.org/) (the
|
|
23
|
+
- **Node.js 18+** — [download](https://nodejs.org/) (the LTS version is fine).
|
|
25
24
|
- **iLiveMyLife account** — free signup at [iLiveMyLife.io](https://ilivemylife.io).
|
|
26
25
|
- **LinkedIn account** — your personal one.
|
|
27
26
|
|
|
@@ -42,9 +41,9 @@ ilml login
|
|
|
42
41
|
ilml plugin install linkedin
|
|
43
42
|
```
|
|
44
43
|
|
|
45
|
-
|
|
44
|
+
The bare-name `linkedin` resolves to `npm:ilml-plugin-linkedin` via the ilml plugin convention. The CLI downloads the latest version from npm, extracts it under `~/.ilivemylife/plugins/linkedin/`, and runs `npm install` for runtime dependencies (mainly Puppeteer's bundled Chromium — first install takes a couple of minutes).
|
|
46
45
|
|
|
47
|
-
Verify
|
|
46
|
+
Verify:
|
|
48
47
|
|
|
49
48
|
```bash
|
|
50
49
|
ilml plugin list
|
|
@@ -53,7 +52,7 @@ ilml linkedin
|
|
|
53
52
|
|
|
54
53
|
## Configure
|
|
55
54
|
|
|
56
|
-
The
|
|
55
|
+
The first time you run `ilml linkedin <command>`, the CLI will prompt for required fields. You can also pre-configure:
|
|
57
56
|
|
|
58
57
|
```bash
|
|
59
58
|
ilml plugin config linkedin set LINKEDIN_NAME "Your Full Name"
|
|
@@ -61,18 +60,16 @@ ilml plugin config linkedin set NODE_EASY_APPLY_MAIN <node-id>
|
|
|
61
60
|
ilml plugin config linkedin set NODE_EASY_APPLY_ERRORS <node-id>
|
|
62
61
|
```
|
|
63
62
|
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
Inspect (secrets masked):
|
|
66
64
|
```bash
|
|
67
65
|
ilml plugin config linkedin
|
|
68
66
|
```
|
|
69
67
|
|
|
70
|
-
|
|
71
|
-
|
|
68
|
+
Change later or wipe:
|
|
72
69
|
```bash
|
|
73
70
|
ilml plugin config linkedin set LINKEDIN_NAME "New Name"
|
|
74
71
|
ilml plugin config linkedin unset OPTIONAL_KEY
|
|
75
|
-
ilml plugin config linkedin reset
|
|
72
|
+
ilml plugin config linkedin reset # re-prompt on next run
|
|
76
73
|
```
|
|
77
74
|
|
|
78
75
|
### Configuration fields
|
|
@@ -80,15 +77,15 @@ ilml plugin config linkedin reset # wipe all; will re-promp
|
|
|
80
77
|
| Section | Field | Required | What it is |
|
|
81
78
|
|---|---|---|---|
|
|
82
79
|
| LinkedIn account | `LINKEDIN_NAME` | yes | Your full name **exactly** as it appears on LinkedIn (used to identify your own messages in threads). |
|
|
83
|
-
| | `LINKEDIN_LOGIN` | no | LinkedIn email — only used for auto-fill during one-time login. |
|
|
84
|
-
| | `LINKEDIN_PASS` | no, secret | LinkedIn password —
|
|
80
|
+
| | `LINKEDIN_LOGIN` | no | LinkedIn email — only used for auto-fill during one-time browser login. |
|
|
81
|
+
| | `LINKEDIN_PASS` | no, secret | LinkedIn password — auto-fill only. Stored locally on disk; never sent anywhere. |
|
|
85
82
|
| iLiveMyLife integration | `NODE_EASY_APPLY_MAIN` | yes | Node ID where job applications are tracked. See "Setting up your graph" below. |
|
|
86
83
|
| | `NODE_EASY_APPLY_ERRORS` | yes | Node ID where Easy Apply errors are logged. |
|
|
87
84
|
| | `NODE_RUN_REPORTS` | no | Node ID where end-of-session summaries are posted (enable notifications on it to get pings when long jobs finish). |
|
|
88
|
-
| Data storage | `DATA_DIR` | no | Absolute path to a directory for
|
|
85
|
+
| Data storage | `DATA_DIR` | no | Absolute path to a directory for your local databases (connections, conversations, profile cache). **Strongly recommended** — keeps your accumulated data outside the plugin install folder so it survives plugin updates, ilml logout, and reinstalls. |
|
|
89
86
|
| Apply bot | `City` | no | Default city for filters. Default: `Toronto`. |
|
|
90
87
|
| | `MAX_APPLY_FOR_RUN` | no | Stop after this many applications per run. Default: `50`. |
|
|
91
|
-
| | `LINKEDIN_SEARCH_URL` | no | Default LinkedIn jobs search URL
|
|
88
|
+
| | `LINKEDIN_SEARCH_URL` | no | Default LinkedIn jobs search URL. Open LinkedIn → Jobs, set your filters, make sure Easy Apply is on, copy the resulting URL from the address bar. |
|
|
92
89
|
| Scouting | `LINKEDIN_SCOUT_URLS` | no | Comma-separated job search URLs to scan without applying. |
|
|
93
90
|
| Resume / CV | `CV_TEXT`, `RESUME_PDF_URL`, `RESUME_FILENAME` | no | CV snippet, public PDF URL, suggested filename. Used in messages to recruiters. |
|
|
94
91
|
| Funnel | `FUNNEL_USE_CUSTOM_MESSAGE` | no | Send a custom note with connection requests. Default: `false`. |
|
|
@@ -123,9 +120,27 @@ The Easy Apply bot uses iLiveMyLife's AI assistant (**Lifebot**) to answer custo
|
|
|
123
120
|
|
|
124
121
|
7. Create a sibling node titled **"Easy Apply Errors"** (no AI needed). Copy its ID and set it: `ilml plugin config linkedin set NODE_EASY_APPLY_ERRORS <id>`.
|
|
125
122
|
|
|
123
|
+
### Save AI tokens — tune the node settings
|
|
124
|
+
|
|
125
|
+
Lifebot uses AI tokens for every form question it answers. Two settings on the Easy Apply node let you tune cost vs. quality without touching the plugin:
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
# Use a cheaper, faster AI model (good enough for filling forms):
|
|
129
|
+
ilml editSettings <NODE_EASY_APPLY_MAIN> --intelligence disabled
|
|
130
|
+
|
|
131
|
+
# Skip whole-graph context lookup — just use this node's description:
|
|
132
|
+
ilml editSettings <NODE_EASY_APPLY_MAIN> --rootAccess disabled
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`intelligence: disabled` switches Lifebot to a cheaper model (think GPT-3.5 / Claude Haiku tier instead of GPT-4 / Claude Opus). For application form filling, the cheap model is usually fine — questions are mechanical.
|
|
136
|
+
|
|
137
|
+
`rootAccess: disabled` stops Lifebot from searching your entire knowledge graph for context every time it answers. The Easy Apply node's description and child nodes already have everything Lifebot needs — extra context costs tokens for no benefit.
|
|
138
|
+
|
|
139
|
+
To switch back: pass `--intelligence enabled` or `--rootAccess enabled`. To reset to your account default: pass `null`.
|
|
140
|
+
|
|
126
141
|
## First-time LinkedIn login
|
|
127
142
|
|
|
128
|
-
LinkedIn requires an authenticated session, so a one-time
|
|
143
|
+
LinkedIn requires an authenticated browser session, so a one-time login is needed:
|
|
129
144
|
|
|
130
145
|
```bash
|
|
131
146
|
ilml linkedin login
|
|
@@ -133,6 +148,12 @@ ilml linkedin login
|
|
|
133
148
|
|
|
134
149
|
A real browser window opens. Sign in to LinkedIn (manually solve any captcha or 2FA). When you see your feed, close the window — your session cookies are saved locally for future runs.
|
|
135
150
|
|
|
151
|
+
Sessions live in your active ilml scope (`<scope>/.ilivemylife/plugins-state/linkedin/cookies.json`), so:
|
|
152
|
+
|
|
153
|
+
- Different ilml scopes (e.g. `ilml login` globally vs `ilml login --local` in a project folder) keep **separate** LinkedIn sessions — useful if you have multiple LinkedIn accounts.
|
|
154
|
+
- Plugin updates do **not** wipe your session — you don't need to re-login after `ilml plugin update linkedin`.
|
|
155
|
+
- `ilml logout` does wipe the session in that scope (alongside other user-tied data) — clean handoff between users on a shared machine.
|
|
156
|
+
|
|
136
157
|
## Daily commands
|
|
137
158
|
|
|
138
159
|
| Command | What it does |
|
|
@@ -150,11 +171,11 @@ A real browser window opens. Sign in to LinkedIn (manually solve any captcha or
|
|
|
150
171
|
| `ilml linkedin daily` | Compound routine combining several commands. |
|
|
151
172
|
| `ilml linkedin login` | Re-save LinkedIn cookies after a session expires. |
|
|
152
173
|
|
|
153
|
-
Run `ilml linkedin` (no subcommand) to see the list
|
|
174
|
+
Run `ilml linkedin` (no subcommand) any time to see the list.
|
|
154
175
|
|
|
155
176
|
## Updating
|
|
156
177
|
|
|
157
|
-
Updates ship via npm. The CLI checks the registry and only downloads when
|
|
178
|
+
Updates ship via npm. The CLI checks the registry and only downloads when a newer version is actually available:
|
|
158
179
|
|
|
159
180
|
```bash
|
|
160
181
|
ilml plugin update linkedin # check this plugin
|
|
@@ -163,20 +184,27 @@ ilml update # update the SDK and all plugins together
|
|
|
163
184
|
```
|
|
164
185
|
|
|
165
186
|
You'll see one of:
|
|
166
|
-
- `linkedin: already on latest version (1.
|
|
167
|
-
- `linkedin: 1.
|
|
187
|
+
- `linkedin: already on latest version (1.3.0)` — nothing downloaded
|
|
188
|
+
- `linkedin: 1.3.0 → 1.3.1` then re-install — newer version pulled
|
|
168
189
|
|
|
169
|
-
Your
|
|
190
|
+
**Your config and your data both survive updates.** Only the plugin code dir gets refreshed; everything user-tied lives elsewhere.
|
|
170
191
|
|
|
171
|
-
## Where
|
|
192
|
+
## Where things live
|
|
172
193
|
|
|
173
|
-
| Path | What's there |
|
|
194
|
+
| Path | What's there | Wiped on plugin update? | Wiped on `ilml logout`? |
|
|
174
195
|
|---|---|---|---|
|
|
175
|
-
| `~/.ilivemylife/plugins/linkedin/` | Plugin code (re-extracted
|
|
176
|
-
|
|
|
177
|
-
|
|
|
196
|
+
| `~/.ilivemylife/plugins/linkedin/` | Plugin code | yes (re-extracted) | no |
|
|
197
|
+
| `<scope>/.ilivemylife/plugins-state/linkedin.json` | Your configured values (LINKEDIN_NAME, node IDs, etc.) | no | yes (with that scope) |
|
|
198
|
+
| `<scope>/.ilivemylife/plugins-state/linkedin/cookies.json` | LinkedIn session cookies | no | yes (with that scope) |
|
|
199
|
+
| Directory you set as `DATA_DIR` | Local DBs, scraped profiles, message history, your notes | **no** | **no** |
|
|
178
200
|
|
|
179
|
-
If you didn't set `DATA_DIR`, data files default to inside the plugin's install dir — meaning a plugin reinstall wipes them
|
|
201
|
+
If you didn't set `DATA_DIR`, runtime data files default to inside the plugin's install dir — meaning a plugin reinstall **wipes them**. Setting `DATA_DIR` to a sibling folder like `~/linkedin-plugin-data/` is **strongly recommended**:
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
ilml plugin config linkedin set DATA_DIR /absolute/path/to/your/linkedin-data
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Once set, you can sync `DATA_DIR` to a backup drive, a cloud folder, or another machine — the data is plain SQLite-style JSON, fully portable.
|
|
180
208
|
|
|
181
209
|
## Removing the plugin
|
|
182
210
|
|
|
@@ -184,13 +212,14 @@ If you didn't set `DATA_DIR`, data files default to inside the plugin's install
|
|
|
184
212
|
ilml plugin remove linkedin
|
|
185
213
|
```
|
|
186
214
|
|
|
187
|
-
This wipes the install dir.
|
|
188
|
-
|
|
215
|
+
This wipes the install dir. Your config in the active scope:
|
|
189
216
|
```bash
|
|
190
217
|
ilml plugin config linkedin reset
|
|
191
218
|
```
|
|
192
219
|
|
|
193
|
-
|
|
220
|
+
The data in `DATA_DIR` is yours — delete the folder manually if you want it gone, or keep it.
|
|
221
|
+
|
|
222
|
+
---
|
|
194
223
|
|
|
195
224
|
## Feedback & support
|
|
196
225
|
|
package/dist/funnelRunner.mjs
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Nt=Object.defineProperty;var Je=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ve=(e,t)=>{for(var o in t)Nt(e,o,{get:t[o],enumerable:!0})};var dt={};Ve(dt,{addEncounter:()=>me,canSendConnection:()=>Se,commitDataSnapshot:()=>ut,default:()=>oo,getAllApplications:()=>lt,getPersonStatus:()=>pe,getQuestionStats:()=>at,getQuotaStatus:()=>ee,getRecentConnections:()=>ye,linkPersonToJob:()=>ot,loadApplicationQuestions:()=>Me,loadConversations:()=>Ze,loadJobs:()=>de,loadPeople:()=>L,loadQuota:()=>he,loadSyncState:()=>st,logApplicationQuestions:()=>ct,migrateFromDailyFiles:()=>nt,recordConnectionSent:()=>we,resetCaches:()=>Xt,saveConversations:()=>et,saveJobs:()=>fe,savePeople:()=>J,saveQuota:()=>Oe,saveSyncState:()=>rt,updateConnectionStatus:()=>ge,upsertJob:()=>tt,upsertPerson:()=>Ae});import"dotenv/config";import*as v from"fs";import*as k from"path";import{fileURLToPath as Qt}from"url";import{execSync as xe}from"child_process";function Xt(){H=null,G=null,F=null,U=null,z=null,q=null}function _(){v.existsSync(D)||v.mkdirSync(D,{recursive:!0})}function B(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";v.writeFileSync(r,o);for(let s=0;s<3;s++)try{v.renameSync(r,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Z(e,t){if(!v.existsSync(e))return null;try{let o=JSON.parse(v.readFileSync(e,"utf-8"));try{v.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${k.resolve(e)}`);let r=e+".backup";if(v.existsSync(r))try{let s=JSON.parse(v.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{v.copyFileSync(r,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{v.copyFileSync(e,e+".corrupted")}catch{}return null}}function Q(){return new Date().toISOString().split("T")[0]}function L(){return H||(_(),H=Z(De,"people.json")||{},H)}function J(e){_(),H=e;try{B(De,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${k.resolve(De)}`)}}function de(){return G||(_(),G=Z(_e,"jobs.json")||{},G)}function fe(e){_(),G=e;try{B(_e,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${k.resolve(_e)}`)}}function Ze(){return U||(_(),U=Z(ue,"conversations.json")||{},Zt(U),U)}function Zt(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let s=(o.messages||[]).find(i=>i.status==="draft");s&&o.draftStatus&&o.draftStatus!=="pending"&&(s.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{B(ue,e)}catch{}}}function et(e){_(),U=e;try{B(ue,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${k.resolve(ue)}`)}}function Ae(e,t={}){if(!e)return null;let o=L(),r=Q(),s=new Date().toISOString(),i=o[e];if(i){i.seenCount=(i.seenCount||1)+1,i.lastSeen=r,i.lastUpdated=s,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of Ee)t[l]!=null&&(i[l]=t[l])}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s};return J(o),o[e]}function tt(e,t={}){if(!e)return null;let o=de(),r=Q(),s=o[e];if(s){let i=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let l of i)t[l]!=null&&(s[l]=t[l])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return fe(o),o[e]}function ot(e,t){if(!e||!t)return;let o=L(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),J(o)))}function me(e,t){if(!e||!t)return;let o=L(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:Q(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!r.encounters.some(u=>u.date===i.date&&u.source===i.source&&u.action===i.action&&(u.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),J(o))}function pe(e){return e&&L()[e]?.connectionStatus||null}function ge(e,t,o={}){if(!e)return;let r=L(),s=r[e];if(s||(Ae(e,o.profileInfo||{}),s=r[e]),!!s){if(s.connectionStatus=t,s.connectionDate=Q(),s.connectionMethod=o.method||s.connectionMethod,s.messageSent=o.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),o.profileInfo)for(let i of Ee)o.profileInfo[i]!=null&&(s[i]=o.profileInfo[i]);J(r)}}function he(){return F||(_(),F=Z(Ke,"quota.json"),(!F||!F.connections)&&(F={connections:[]}),F)}function Oe(e){_(),F=e;try{B(Ke,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function we(e,t="unknown"){let o=he(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Oe(o)}function ye(){let e=he(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function Se(){let e=ye(),t=Q(),o=e.filter(n=>n.date===t).length,r=e.length,s=o>=K,i=r>=X,l=!s&&!i,u={allowed:l,daily:{sent:o,max:K},weekly:{sent:r,max:X}};return l||(u.reason=s?`Daily limit reached (${o}/${K})`:`Weekly limit reached (${r}/${X})`),u}function ee(){let e=ye(),t=Q(),o=e.filter(s=>s.date===t).length,r=e.length;return{daily:{sent:o,max:K,remaining:K-o},weekly:{sent:r,max:X,remaining:X-r}}}function eo(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function nt(){_();let e=v.readdirSync(D).filter(i=>i.endsWith(".json")&&i!=="people.json"&&i!=="jobs.json"&&i!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
2
2
|
Migrating from ${e.length} daily files...
|
|
3
|
-
`);let t=
|
|
4
|
-
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${s} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function st(){return
|
|
3
|
+
`);let t=L(),o=de(),r=0,s=0;e.sort();for(let i of e){let l=k.join(D,i),u;try{u=JSON.parse(v.readFileSync(l,"utf-8"))}catch(a){console.log(` Skipping ${i}: ${a.message}`);continue}let n=u.date||i.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,c=u.source||i.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!u.profiles||!Array.isArray(u.profiles)){console.log(` Skipping ${i}: no profiles array`);continue}console.log(` ${i}: ${u.profiles.length} profiles`);for(let a of u.profiles){let f=a.profileUrl;if(!f)continue;let d=t[f];if(d){d.seenCount=(d.seenCount||1)+1,n&&(!d.lastSeen||n>d.lastSeen)&&(d.lastSeen=n),n&&(!d.firstSeen||n<d.firstSeen)&&(d.firstSeen=n),c&&!d.sources?.includes(c)&&(d.sources=d.sources||[],d.sources.push(c));for(let m of Ee)a[m]!=null&&(d[m]=a[m]);a.status&&a.processed&&(d.connectionStatus=a.status,d.connectionDate=n,a.funnelResult&&(d.connectionMethod=a.funnelResult.method||d.connectionMethod,d.messageSent=a.funnelResult.message||d.messageSent)),d.lastUpdated=new Date().toISOString()}else t[f]={name:a.name||null,title:a.title||null,location:a.location||null,company:a.company||null,connectionDegree:a.connectionDegree||null,connectionsCount:a.connectionsCount||null,mutualConnections:a.mutualConnections||null,photoUrl:a.photoUrl||null,hasVerifiedBadge:a.hasVerifiedBadge||!1,firstSeen:n,lastSeen:n,seenCount:1,sources:c?[c]:[],connectionStatus:a.processed&&a.status||null,connectionDate:a.processed?n:null,connectionMethod:a.funnelResult?.method||null,messageSent:a.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(a.fromJob?.url){let m=eo(a.fromJob.url);m&&(t[f].jobIds||(t[f].jobIds=[]),t[f].jobIds.includes(m)||t[f].jobIds.push(m),o[m]?o[m].recruiterUrl||(o[m].recruiterUrl=f):(o[m]={title:a.fromJob.title||null,company:a.fromJob.company||null,location:null,salary:null,url:a.fromJob.url,applied:!0,appliedDate:n,recruiterUrl:f,firstSeen:n},s++))}}}return J(t),fe(o),console.log(`
|
|
4
|
+
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${s} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function st(){return z||(_(),z=Z(Xe,"sync-state.json")||{},z)}function rt(e){_(),z=e;try{B(Xe,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Me(){if(q)return q;_();try{v.existsSync(je)&&(q=JSON.parse(v.readFileSync(je,"utf-8")))}catch{}return q||(q={}),q}function it(e){return Array.isArray(e.applications)}function lt(){let e=Me();if(it(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function ct(e){if(!e||!e.questions||e.questions.length===0)return;let t=Me(),o=e.jobId||"unknown",s={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(i=>{let l={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=to?l.options=i.options:l.optionsOmitted=!0),i.page&&(l.page=i.page),i.wasPreFilled&&(l.wasPreFilled=!0),i.wasRetry&&(l.wasRetry=!0),l})};it(t)?(s.jobId=o,s.jobTitle=e.jobTitle||null,s.jobCompany=e.jobCompany||null,s.jobUrl=e.jobUrl||null,t.applications.push(s)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(s));try{B(je,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function at(){let e=lt(),t=new Map;for(let i of e)for(let l of i.questions||[]){let u=l.question.toLowerCase().trim();if(!u)continue;t.has(u)||t.set(u,{question:l.question,count:0,answers:new Map});let n=t.get(u);n.count++;let c=(l.answer||"").trim();n.answers.set(c,(n.answers.get(c)||0)+1)}let o=[...t.values()].sort((i,l)=>l.count-i.count),r=o.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((l,u)=>u[1]-l[1])[0]?.[0]||""})),s=o.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((l,u)=>u[1]-l[1]).map(([l,u])=>`${l} (${u}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:s}}function ut(e){if(v.existsSync(k.join(D,".git")))try{let t={cwd:D,stdio:"pipe",timeout:1e4};xe("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{xe("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');xe(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Yt,Kt,D,De,_e,Ke,ue,Xe,je,K,X,H,G,F,U,z,q,Ee,to,oo,Fe=Je(()=>{Yt=Qt(import.meta.url),Kt=k.dirname(k.dirname(Yt)),D=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"collected-profiles"):k.join(Kt,"collected-profiles"),De=k.join(D,"people.json"),_e=k.join(D,"jobs.json"),Ke=k.join(D,"quota.json"),ue=k.join(D,"conversations.json"),Xe=k.join(D,"sync-state.json"),je=k.join(D,"application-questions.json"),K=20,X=100,H=null,G=null,F=null,U=null,z=null,q=null;Ee=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];to=50;oo={loadPeople:L,savePeople:J,loadJobs:de,saveJobs:fe,loadConversations:Ze,saveConversations:et,upsertPerson:Ae,upsertJob:tt,linkPersonToJob:ot,addEncounter:me,getPersonStatus:pe,updateConnectionStatus:ge,migrateFromDailyFiles:nt,loadQuota:he,saveQuota:Oe,recordConnectionSent:we,canSendConnection:Se,getRecentConnections:ye,getQuotaStatus:ee,loadSyncState:st,saveSyncState:rt,commitDataSnapshot:ut,logApplicationQuestions:ct,getQuestionStats:at}});var xt={};Ve(xt,{getJobDecision:()=>So,getLastVisit:()=>ko,getScoutStats:()=>$o,loadCompanies:()=>It,loadDiscoveredPeople:()=>Ne,loadJobDecisions:()=>Re,loadScoutedJobs:()=>Le,loadVisitLog:()=>be,recordVisit:()=>vo,resetCaches:()=>ho,saveCompany:()=>Co,saveDiscoveredPerson:()=>bo,saveScoutedJob:()=>wo,setJobDecision:()=>yo});import"dotenv/config";import*as O from"fs";import*as j from"path";import{fileURLToPath as mo}from"url";function le(){O.existsSync(W)||O.mkdirSync(W,{recursive:!0})}function ce(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";O.writeFileSync(r,o);for(let s=0;s<3;s++)try{O.renameSync(r,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function ae(e){try{if(O.existsSync(e))return JSON.parse(O.readFileSync(e,"utf-8"))}catch{}return null}function ho(){ne=null,se=null,re=null,ie=null,V=null}function Le(){return ne||(ne=ae(bt)||{},ne)}function wo(e,t){if(!e)return;le();let o=Le(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[s,i]of Object.entries(t))i!=null&&(o[e][s]=i);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{ce(bt,o)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function Re(){return se||(se=ae($t)||{},se)}function yo(e,t,o={}){if(!e||!t)return;le();let r=Re(),s=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=s,o.reason&&(r[e].reason=o.reason),o.score!=null&&(r[e].score=o.score),o.source&&(r[e].source=o.source)):r[e]={status:t,decidedAt:s,updatedAt:s,reason:o.reason||null,score:o.score??null,source:o.source||null};try{ce($t,r)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function So(e){return Re()[e]||null}function Ne(){return re||(re=ae(Ct)||{},re)}function bo(e,t){if(!e)return;le();let o=Ne(),r=new Date().toISOString().slice(0,10);if(o[e]){let s=o[e];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[e]={name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{ce(Ct,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function It(){return ie||(ie=ae(kt)||{},ie)}function Co(e,t){if(!e)return;le();let o=It(),r=new Date().toISOString().slice(0,10);if(o[e]){let s=o[e];t.name&&(s.name=t.name),t.about&&(s.about=t.about),t.size&&(s.size=t.size),t.industries&&(s.industries=t.industries),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),t.recruiterUrl&&(s.recruiterUrls||(s.recruiterUrls=[]),s.recruiterUrls.includes(t.recruiterUrl)||s.recruiterUrls.push(t.recruiterUrl)),s.lastSeen=r,s.jobCount=s.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{ce(kt,o)}catch(s){console.error(`[!] Failed to save companies.json: ${s.message}`)}}function be(){return V||(V=ae(vt)||{visits:[]},Array.isArray(V.visits)||(V.visits=[]),V)}function vo(e,t={}){if(!e)return;le();let o=be();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let r=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(s=>new Date(s.date).getTime()>r);try{ce(vt,o)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function ko(e){let t=be();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function $o(){let e=Le(),t=Ne(),o=Object.values(e),r=Object.values(t),s={};for(let d of o)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),l={};for(let d of o)for(let m of d.techStack||[])l[m]=(l[m]||0)+1;let u=Object.entries(l).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),n=be(),c=new Date().toISOString().slice(0,10),a=n.visits.filter(d=>d.date.startsWith(c)).length,f=new Set(n.visits.map(d=>d.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:u,totalVisited:f,todayVisited:a,lastScoutDate:o.length>0?o.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var po,go,W,bt,Ct,vt,kt,$t,ne,se,re,ie,V,Dt=Je(()=>{po=mo(import.meta.url),go=j.dirname(j.dirname(po)),W=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"market-research"):j.join(go,"market-research"),bt=j.join(W,"scouted-jobs.json"),Ct=j.join(W,"discovered-people.json"),vt=j.join(W,"visit-log.json"),kt=j.join(W,"companies.json"),$t=j.join(W,"job-decisions.json");ne=null;se=null;re=null;ie=null;V=null});import Mo from"puppeteer";import"dotenv/config";import*as A from"fs";import*as P from"path";import{fileURLToPath as Wt}from"url";import"dotenv/config";import{createGraphClient as qt,resolveToken as Ut}from"@ilivemylife/graph-sdk";import{config as Bt}from"dotenv";Bt();var We=Ut()||process.env.TOKEN;We||(console.error(`
|
|
5
5
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
6
6
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
7
7
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
8
|
-
`),process.exit(1));var He=qt({token:We});function
|
|
8
|
+
`),process.exit(1));var He=qt({token:We});function Jt(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),r=t%60;return r?`${o}m ${r}s`:`${o}m`}function Vt({scriptName:e,mode:t,status:o,error:r,duration:s}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),u=s?` ${Jt(s)}`:"",n=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${c} \u2014 ${n} \u2014 ${l}${u}`}async function Ge({scriptName:e,mode:t,status:o,summaryLines:r,error:s,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let n=`**${Vt({scriptName:e,mode:t,status:o,error:s,duration:i})}**
|
|
9
9
|
|
|
10
10
|
${r.join(`
|
|
11
|
-
`)}`;try{await He.addMessage(l,n)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Wt=Vt(import.meta.url),Ht=L.dirname(L.dirname(Wt)),$e=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"collected-profiles"):L.join(Ht,"collected-profiles"),ke=L.join($e,"run-log.json");function zt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";A.writeFileSync(r,o);for(let s=0;s<3;s++)try{A.renameSync(r,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Ge(){try{if(!A.existsSync(ke))return{runs:[]};let e=JSON.parse(A.readFileSync(ke,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Qe(e){A.existsSync($e)||A.mkdirSync($e,{recursive:!0});try{zt(ke,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ye(e,t="default"){let o=Ge();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let r=new Date,s={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>i),Qe(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Ie(e,t,o=null,r=null){if(!e)return;let s=null;try{let l=Ge(),u=l.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=o,u.error=r,s=u.duration;else{let n=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());n&&(n.status=t,n.result=t,n.duration=Date.now()-e.startTime,n.stats=o,n.error=r,s=n.duration)}Qe(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";ze({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:r,duration:s??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}async function g(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}async function q(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let s=r.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),l=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),u=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||l||u){let n=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(n)return n.click(),{dismissed:!0,matched:s.substring(0,80)};let c=r.querySelectorAll("button");for(let a of c){let f=a.innerText?.trim().toLowerCase()||"",d=a.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return a.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}Fe();async function ft(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function oo(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function no(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(2e3+Math.random()*2e3),await q(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await ft(e,t));let r=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim()||null,i=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,u=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,c=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,f=document.querySelector(".dist-value")?.textContent?.trim()||null,p=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,y=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),w=y?parseInt(y[1],10):null,b=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,v=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:s,title:i,location:l,about:u,company:c,connectionDegree:f,connectionsCount:p,mutualConnections:w,photoUrl:b,hasVerifiedBadge:v}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}return null}}async function te(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(o).map(n=>n.getAttribute("aria-label")),s=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:r,hasMessageBtn:!!s,hasConnectBtn:!!i};return o.length>0?{status:"pending",debug:l}:s&&!i?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Te(e){let t=null,o=await e.evaluate(()=>{let n=document.querySelector("h1")?.textContent?.trim();if(n&&!n.includes("notification"))return n;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(n=c.textContent?.trim(),n&&!n.includes("notification")))return n;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let n=await e.evaluate(()=>{let a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});n.count>0&&console.log(` S0: ${n.count} custom-invite links: ${JSON.stringify(n.labels)}`),t=await e.evaluateHandle(a=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=a.toLowerCase().split(" ")[0],p=null,h=null;for(let m of f){let y=m.getBoundingClientRect();if(y.width===0||y.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(d)){p=m;break}h||(h=m)}return p||h||null},o);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(o){let n=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${n}"`);let c=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let y=m.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&d.test(y)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},n);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of d){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},n);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(c)&&(console.log(` Skipping primary button: wrong person (${n})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let s=o?o.split(" ")[0].toLowerCase():"",i=null;for(let n of r){let c=await e.evaluate((a,f)=>{let d=a.className.includes("muted"),p=a.className.includes("sticky-header")||a.className.includes("sticky"),h=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(a.getAttribute("aria-label")||"").toLowerCase(),y=m.includes("invite"),w=f?m.includes(f):!0;return{isMuted:d,isStickyHeader:p,inRecommendations:h,hasInvite:y,matchesName:w,ariaLabel:m}},n,s);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}i=n;break}}for(let n of r)n!==i&&await n.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let n of u){let c=await e.evaluate(a=>{let f=a.getBoundingClientRect(),d=f.width>0&&f.height>0,p=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:p,top:f.top}},n);if(c.isVisible&&!c.isInStickyHeader){l=n,console.log(" Found More button by ID pattern (main)");break}}for(let n of u)n!==l&&await n.dispose().catch(()=>{});if(!l&&u.length>0&&(l=u[u.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let n=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(d=>{let p=d.innerText?.trim(),h=d.getAttribute("aria-label")||"",m=d.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!a)return null;let f=a.parentElement;for(let d=0;d<8&&f;d++){for(let p of f.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==a)return p;f=f.parentElement}return null});l=n?.asElement?.()||null,l||await n?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(a=>a.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let a=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let p=d.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});c=a?.asElement?.()||null,c||await a?.dispose?.().catch(()=>{})}if(!c){let a=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let p of f)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&d.push(m)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(n){console.log(" More dropdown click failed:",n.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(c)&&(console.log(` Skipping generic button: wrong person (${n})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function so(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(500);let o=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV";if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(a=>a.click(),t)]),await g(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await g(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await g(3e3)):(await e.evaluate(c=>c.click(),t),await g(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let u=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),n=e.url();return console.log(u?` \u2713 Connect sent \u2014 ${n}`:` \u26A0 No modal after connect click \u2014 ${n}`),"success"}async function ro(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await g(1500);let o=await Te(e);if(o){await e.evaluate(s=>s.click(),o),await g(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function io(e,t,o={}){let{message:r=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:u=[]}=o,n={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
12
|
-
--- Connecting: ${c} ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await q(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await ft(e,t),await g(2e3)),n.profileInfo=await e.evaluate(()=>{let w=document.querySelector("h1")?.textContent?.trim()||null,S=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,b=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,k=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,R=document.querySelector(".dist-value")?.textContent?.trim()||null,Ft=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,Be=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),Tt=Be?parseInt(Be[1],10):null,Lt=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,Pt=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:w,title:S,location:b,company:k,connectionDegree:R,connectionsCount:Ft,mutualConnections:Tt,photoUrl:Lt,hasVerifiedBadge:Pt}}),u.length>0&&oo(n.profileInfo?.location,u))return console.log(` \u26A0 Excluded location: ${n.profileInfo.location}`),n.reason="excluded_location",n;let f=await te(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),n.reason="pending",n;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),n.reason="connected",n;await q(e);let d=await Te(e);if(!d&&(await q(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),d=await Te(e)),!d))return console.log(" \u2717 Connect not found"),n.reason="button_not_found",n;if(n.method=d.method,await so(e,d.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let w=await te(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await q(e),await g(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),S),await g(500),await S.click().catch(()=>e.evaluate(v=>v.click(),S)),await g(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(b){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(M=>M.click(),b),await g(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),n.reason="premium_required",n;if(await te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.method="more_dropdown",n.withCustomMessage=!1,n;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await g(500),n.reason="premium_required",n}catch(b){return console.log(" More dropdown failed:",b.message),await e.keyboard.press("Escape").catch(()=>{}),n.reason="premium_required",n}else return console.log(" \u2717 No More button found \u2014 Premium required"),n.reason="premium_required",n}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await g(500),n.reason="email_required",n}let m=await e.$('button[aria-label="Add a note"]'),y=await e.$('button[aria-label="Send without a note"]');if(!m&&!y){let w=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let b=S.querySelector('button[aria-label="Add a note"]'),v=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!b,sendWithout:!!v}});if(w.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=S?.asElement?.()||null,m||await S.dispose().catch(()=>{})}if(w.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));y=S?.asElement?.()||null,y||await S.dispose().catch(()=>{})}}if(s){if(m&&r){if(console.log(" Adding personalized note..."),await m.click(),await g(1500),await e.$("div.modal-upsell")){let b=await ro(e);return n.success=b,n.connectionSent=b,n.reason=b?"sent_without_note_upsell":"upsell_failed",n.withCustomMessage=!1,n}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let b=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),v=r.replace("{name}",b);await S.type(v,{delay:20}),await g(500);let k=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(k){try{await k.evaluate(M=>M.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (with note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_with_note",n.withCustomMessage=!0,n.messageSent=v,n}}}else if(y){console.log(" Sending without note...");try{await y.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}else if(m&&!r){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}}else{console.log(" Sending without note (custom messages disabled)...");let w=y;if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3)),await q(e),await g(500);let S=await e.$$('button[id*="profile-overflow-action"]'),b=null;for(let v of S){let k=await e.evaluate(M=>{let R=M.getBoundingClientRect();return{visible:R.width>0&&R.height>0,inSticky:!!M.closest('.sticky-header, [class*="sticky"]')}},v);if(k.visible&&!k.inSticky){b=v;break}}!b&&S.length>0&&(b=S[S.length-1]);for(let v of S)v!==b&&await v.dispose().catch(()=>{});if(b)try{await e.evaluate(k=>k.scrollIntoView({behavior:"smooth",block:"center"}),b),await g(500),await b.click().catch(()=>e.evaluate(k=>k.click(),b)),await g(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(v){console.log(" Found Connect in More dropdown, clicking..."),n.method="more_dropdown",await e.evaluate(Y=>Y.click(),v),await g(3e3);let k=e.url();if(k.includes("/premium/")||k.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await te(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n):(n.reason="premium_required",n);if(await te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;let R=await e.$('button[aria-label="Send without a note"]');if(R){console.log(" Modal appeared via More dropdown, sending without note...");try{await R.evaluate(Y=>Y.click())}catch{}return await g(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(v){console.log(" More dropdown fallback failed:",v.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),n.reason="modal_failed",n}catch(c){console.error(` \u2717 Error: ${c.message}`),n.reason="error",n.error=c.message;let a=c.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return n.fatal=!0,n;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{n.fatal=!0}return n}}async function pt(e,t,o={}){let{message:r=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:n=null,excludeLocations:c=[],source:a="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
13
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!l){let
|
|
11
|
+
`)}`;try{await He.addMessage(l,n)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Ht=Wt(import.meta.url),Gt=P.dirname(P.dirname(Ht)),ke=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"collected-profiles"):P.join(Gt,"collected-profiles"),$e=P.join(ke,"run-log.json");function zt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";A.writeFileSync(r,o);for(let s=0;s<3;s++)try{A.renameSync(r,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function ze(){try{if(!A.existsSync($e))return{runs:[]};let e=JSON.parse(A.readFileSync($e,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Qe(e){A.existsSync(ke)||A.mkdirSync(ke,{recursive:!0});try{zt($e,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ye(e,t="default"){let o=ze();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let r=new Date,s={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>i),Qe(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Ie(e,t,o=null,r=null){if(!e)return;let s=null;try{let l=ze(),u=l.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=o,u.error=r,s=u.duration;else{let n=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());n&&(n.status=t,n.result=t,n.duration=Date.now()-e.startTime,n.stats=o,n.error=r,s=n.duration)}Qe(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Ge({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:r,duration:s??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}async function g(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}async function N(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let s=r.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),l=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),u=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||l||u){let n=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(n)return n.click(),{dismissed:!0,matched:s.substring(0,80)};let c=r.querySelectorAll("button");for(let a of c){let f=a.innerText?.trim().toLowerCase()||"",d=a.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return a.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}Fe();async function ft(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function no(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function so(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(2e3+Math.random()*2e3),await N(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await ft(e,t));let r=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim()||null,i=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,u=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,c=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,f=document.querySelector(".dist-value")?.textContent?.trim()||null,m=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,y=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),w=y?parseInt(y[1],10):null,b=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,C=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:s,title:i,location:l,about:u,company:c,connectionDegree:f,connectionsCount:m,mutualConnections:w,photoUrl:b,hasVerifiedBadge:C}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}return null}}async function te(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(o).map(n=>n.getAttribute("aria-label")),s=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:r,hasMessageBtn:!!s,hasConnectBtn:!!i};return o.length>0?{status:"pending",debug:l}:s&&!i?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Te(e){let t=null,o=await e.evaluate(()=>{let n=document.querySelector("h1")?.textContent?.trim();if(n&&!n.includes("notification"))return n;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(n=c.textContent?.trim(),n&&!n.includes("notification")))return n;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let n=await e.evaluate(()=>{let a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});n.count>0&&console.log(` S0: ${n.count} custom-invite links: ${JSON.stringify(n.labels)}`),t=await e.evaluateHandle(a=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=a.toLowerCase().split(" ")[0],m=null,h=null;for(let p of f){let y=p.getBoundingClientRect();if(y.width===0||y.height===0)continue;if((p.getAttribute("aria-label")||"").toLowerCase().includes(d)){m=p;break}h||(h=p)}return m||h||null},o);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(o){let n=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${n}"`);let c=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(p=>{let y=p.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&d.test(y)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},n);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of d){let p=h.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p))return h}return null},n);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(c)&&(console.log(` Skipping primary button: wrong person (${n})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let s=o?o.split(" ")[0].toLowerCase():"",i=null;for(let n of r){let c=await e.evaluate((a,f)=>{let d=a.className.includes("muted"),m=a.className.includes("sticky-header")||a.className.includes("sticky"),h=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(a.getAttribute("aria-label")||"").toLowerCase(),y=p.includes("invite"),w=f?p.includes(f):!0;return{isMuted:d,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:w,ariaLabel:p}},n,s);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}i=n;break}}for(let n of r)n!==i&&await n.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let n of u){let c=await e.evaluate(a=>{let f=a.getBoundingClientRect(),d=f.width>0&&f.height>0,m=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:m,top:f.top}},n);if(c.isVisible&&!c.isInStickyHeader){l=n,console.log(" Found More button by ID pattern (main)");break}}for(let n of u)n!==l&&await n.dispose().catch(()=>{});if(!l&&u.length>0&&(l=u[u.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let n=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(d=>{let m=d.innerText?.trim(),h=d.getAttribute("aria-label")||"",p=d.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!a)return null;let f=a.parentElement;for(let d=0;d<8&&f;d++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==a)return m;f=f.parentElement}return null});l=n?.asElement?.()||null,l||await n?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(a=>a.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let a=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let m=d.querySelector('a[href*="custom-invite"]');if(m)return m;for(let h of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});c=a?.asElement?.()||null,c||await a?.dispose?.().catch(()=>{})}if(!c){let a=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let m of f)for(let h of m.querySelectorAll('[role="menuitem"], a, div')){let p=h.innerText?.trim();p&&p.length<40&&d.push(p)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(n){console.log(" More dropdown click failed:",n.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(c)&&(console.log(` Skipping generic button: wrong person (${n})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function ro(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(500);let o=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV";if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(a=>a.click(),t)]),await g(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await g(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await g(3e3)):(await e.evaluate(c=>c.click(),t),await g(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let u=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),n=e.url();return console.log(u?` \u2713 Connect sent \u2014 ${n}`:` \u26A0 No modal after connect click \u2014 ${n}`),"success"}async function io(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await g(1500);let o=await Te(e);if(o){await e.evaluate(s=>s.click(),o),await g(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function lo(e,t,o={}){let{message:r=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:u=[]}=o,n={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
12
|
+
--- Connecting: ${c} ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await N(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await ft(e,t),await g(2e3)),n.profileInfo=await e.evaluate(()=>{let w=document.querySelector("h1")?.textContent?.trim()||null,S=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,b=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,$=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,R=document.querySelector(".dist-value")?.textContent?.trim()||null,Tt=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,Be=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),Pt=Be?parseInt(Be[1],10):null,Lt=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,Rt=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:w,title:S,location:b,company:$,connectionDegree:R,connectionsCount:Tt,mutualConnections:Pt,photoUrl:Lt,hasVerifiedBadge:Rt}}),u.length>0&&no(n.profileInfo?.location,u))return console.log(` \u26A0 Excluded location: ${n.profileInfo.location}`),n.reason="excluded_location",n;let f=await te(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),n.reason="pending",n;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),n.reason="connected",n;await N(e);let d=await Te(e);if(!d&&(await N(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),d=await Te(e)),!d))return console.log(" \u2717 Connect not found"),n.reason="button_not_found",n;if(n.method=d.method,await ro(e,d.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let w=await te(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await N(e),await g(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),S),await g(500),await S.click().catch(()=>e.evaluate(C=>C.click(),S)),await g(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(b){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(M=>M.click(),b),await g(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),n.reason="premium_required",n;if(await te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.method="more_dropdown",n.withCustomMessage=!1,n;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await g(500),n.reason="premium_required",n}catch(b){return console.log(" More dropdown failed:",b.message),await e.keyboard.press("Escape").catch(()=>{}),n.reason="premium_required",n}else return console.log(" \u2717 No More button found \u2014 Premium required"),n.reason="premium_required",n}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await g(500),n.reason="email_required",n}let p=await e.$('button[aria-label="Add a note"]'),y=await e.$('button[aria-label="Send without a note"]');if(!p&&!y){let w=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let b=S.querySelector('button[aria-label="Add a note"]'),C=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!b,sendWithout:!!C}});if(w.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=S?.asElement?.()||null,p||await S.dispose().catch(()=>{})}if(w.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));y=S?.asElement?.()||null,y||await S.dispose().catch(()=>{})}}if(s){if(p&&r){if(console.log(" Adding personalized note..."),await p.click(),await g(1500),await e.$("div.modal-upsell")){let b=await io(e);return n.success=b,n.connectionSent=b,n.reason=b?"sent_without_note_upsell":"upsell_failed",n.withCustomMessage=!1,n}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let b=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=r.replace("{name}",b);await S.type(C,{delay:20}),await g(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(M=>M.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (with note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_with_note",n.withCustomMessage=!0,n.messageSent=C,n}}}else if(y){console.log(" Sending without note...");try{await y.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}else if(p&&!r){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}}else{console.log(" Sending without note (custom messages disabled)...");let w=y;if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3)),await N(e),await g(500);let S=await e.$$('button[id*="profile-overflow-action"]'),b=null;for(let C of S){let $=await e.evaluate(M=>{let R=M.getBoundingClientRect();return{visible:R.width>0&&R.height>0,inSticky:!!M.closest('.sticky-header, [class*="sticky"]')}},C);if($.visible&&!$.inSticky){b=C;break}}!b&&S.length>0&&(b=S[S.length-1]);for(let C of S)C!==b&&await C.dispose().catch(()=>{});if(b)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),b),await g(500),await b.click().catch(()=>e.evaluate($=>$.click(),b)),await g(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(C){console.log(" Found Connect in More dropdown, clicking..."),n.method="more_dropdown",await e.evaluate(Y=>Y.click(),C),await g(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await te(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n):(n.reason="premium_required",n);if(await te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;let R=await e.$('button[aria-label="Send without a note"]');if(R){console.log(" Modal appeared via More dropdown, sending without note...");try{await R.evaluate(Y=>Y.click())}catch{}return await g(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),n.reason="modal_failed",n}catch(c){console.error(` \u2717 Error: ${c.message}`),n.reason="error",n.error=c.message;let a=c.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return n.fatal=!0,n;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{n.fatal=!0}return n}}async function mt(e,t,o={}){let{message:r=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:n=null,excludeLocations:c=[],source:a="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
13
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!l){let m=ee();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let h=t[m];try{if(e.isClosed()){console.log(`
|
|
14
14
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
15
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${
|
|
15
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let p=pe(h.profileUrl);if(p==="pending"||p==="connected"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${p})`),p==="pending"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,n&&await n(h,f,{success:!1,reason:p,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${h.name||h.profileUrl}`);let y=null;if(l){let w=await so(e,h.profileUrl);w?(f.viewed++,y={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w}):(f.errors++,y={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=Se();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(y=await lo(e,h.profileUrl,{message:r,useCustomMessage:s,excludeLocations:c}),y.success)f.connectionsSent++,y.connectionSent&&we(h.profileUrl,a);else switch(y.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(y?.fatal){console.log(`
|
|
16
16
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(y?.reason==="error"){if(d++,d>=3){console.log(`
|
|
17
|
-
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(y&&y.reason&&(ge(h.profileUrl,y.reason,{method:y.method,messageSent:y.messageSent,profileInfo:y.profileInfo}),
|
|
18
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!l){let
|
|
19
|
-
\u{1F4E6} Schema migration: v${o} \u2192 v${
|
|
20
|
-
Running migration v${String(s.version).padStart(3,"0")}...`),_t(
|
|
17
|
+
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(y&&y.reason&&(ge(h.profileUrl,y.reason,{method:y.method,messageSent:y.messageSent,profileInfo:y.profileInfo}),me(h.profileUrl,{source:a||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:y.reason})),n&&await n(h,f,y),m<t.length-1){let w=u+Math.random()*2e3;await g(w)}}if(console.log(`
|
|
18
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!l){let m=ee();console.log(` Quota remaining: today ${m.daily.remaining}/${m.daily.max} | week ${m.weekly.remaining}/${m.weekly.max}`)}return f}import"dotenv/config";import*as x from"fs";import*as T from"path";import{fileURLToPath as co}from"url";var ao=co(import.meta.url),uo=T.dirname(T.dirname(ao)),oe=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"collected-profiles"):T.join(uo,"collected-profiles");function Pe(){x.existsSync(oe)||x.mkdirSync(oe,{recursive:!0})}function fo(){return new Date().toISOString().split("T")[0]}function pt(e,t=null){let o=t||fo();return T.join(oe,`${e}-${o}.json`)}function gt(e,t=null){Pe();let o=pt(e,t);try{if(x.existsSync(o)){let r=x.readFileSync(o,"utf-8"),s=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${s.profiles.length} profiles from ${o}`),s.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function ht(e,t=null){return gt(e,t).filter(r=>!r.processed)}function wt(e,t,o,r=null){Pe();let s=pt(e,r);try{if(!x.existsSync(s))return;let i=JSON.parse(x.readFileSync(s,"utf-8")),l=i.profiles.find(u=>u.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let u=o.profileInfo;u.name&&(l.name=u.name),u.title&&(l.title=u.title),u.location&&(l.location=u.location),u.company&&(l.company=u.company),u.connectionDegree&&(l.connectionDegree=u.connectionDegree),u.connectionsCount&&(l.connectionsCount=u.connectionsCount),u.mutualConnections&&(l.mutualConnections=u.mutualConnections),u.photoUrl&&(l.photoUrl=u.photoUrl),u.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=u.hasVerifiedBadge)}l.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),x.writeFileSync(s,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function yt(e){let t=gt(e),o=t.filter(s=>s.processed),r=t.filter(s=>!s.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((s,i)=>(s[i.status]=(s[i.status]||0)+1,s),{})}}function St(){Pe();try{return x.readdirSync(oe).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let s=JSON.parse(x.readFileSync(T.join(oe,t),"utf-8"));return{file:t,source:o,date:r,count:s.profiles?.length||0,unprocessed:s.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as E from"fs";import*as I from"path";import{fileURLToPath as Io}from"url";var xo=Io(import.meta.url),Do=I.dirname(xo),Et=I.dirname(I.dirname(Do)),Ce=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"collected-profiles"):I.join(Et,"collected-profiles"),ve=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"market-research"):I.join(Et,"market-research"),qe=1,_o=[{version:1,file:"./v001-normalize-jobs-and-questions.mjs"}];function At(e){return I.join(e,".schema-version")}function Ue(e){let t=At(e);if(!E.existsSync(t))return{version:0,migrations:[]};try{return JSON.parse(E.readFileSync(t,"utf-8"))}catch{return{version:0,migrations:[]}}}function jo(e,t){E.writeFileSync(At(e),JSON.stringify(t,null,2))}function _t(e,t){if(!E.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=E.readdirSync(e).filter(s=>s.endsWith(".json")&&!s.includes(".backup"));for(let s of r){let i=I.join(e,s),l=I.join(e,s+o);try{E.copyFileSync(i,l)}catch(u){console.error(` [!] Failed to backup ${s}: ${u.message}`)}}r.length>0&&console.log(` Backed up ${r.length} files in ${I.basename(e)}/ (${o})`)}var jt=!1;async function Ot(){if(jt)return;jt=!0;let e=Ue(Ce),t=Ue(ve),o=Math.min(e.version,t.version);if(o>=qe)return;console.log(`
|
|
19
|
+
\u{1F4E6} Schema migration: v${o} \u2192 v${qe}`);let r=_o.filter(s=>s.version>o);for(let s of r){console.log(`
|
|
20
|
+
Running migration v${String(s.version).padStart(3,"0")}...`),_t(Ce,s.version),_t(ve,s.version);let i=await import(s.file);try{await i.up(Ce,ve)}catch(n){console.error(`
|
|
21
21
|
[FATAL] Migration v${s.version} failed: ${n.message}`),console.error(` Backups are in collected-profiles/ and market-research/ (.pre-v${String(s.version).padStart(3,"0")}.backup)`),console.error(` Fix the issue and restart.
|
|
22
|
-
`),process.exit(1)}let l=new Date().toISOString(),u={version:s.version,name:i.NAME||`v${String(s.version).padStart(3,"0")}`,appliedAt:l};for(let n of[ve
|
|
23
|
-
\u2713 Schema is now at v${
|
|
24
|
-
`)}await Ot();function
|
|
22
|
+
`),process.exit(1)}let l=new Date().toISOString(),u={version:s.version,name:i.NAME||`v${String(s.version).padStart(3,"0")}`,appliedAt:l};for(let n of[Ce,ve]){if(!E.existsSync(n))continue;let c=Ue(n);c.version=s.version,c.migratedAt=l,c.migrations.push(u),jo(n,c)}console.log(` \u2713 Migration v${String(s.version).padStart(3,"0")} complete`)}try{let{resetCaches:s}=await Promise.resolve().then(()=>(Fe(),dt));s()}catch{}try{let{resetCaches:s}=await Promise.resolve().then(()=>(Dt(),xt));s()}catch{}console.log(`
|
|
23
|
+
\u2713 Schema is now at v${qe}
|
|
24
|
+
`)}import Mt from"fs";import Eo from"path";var Ao="cookies.json";function Oo(){let e=process.env.ILML_SCOPE_DIR;return e?Eo.join(e,"plugins-state","linkedin","cookies.json"):Ao}function Ft(){let e=Oo();if(!Mt.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Mt.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}await Ot();function Fo(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(o=>o.trim()).filter(Boolean));return e}async function To(){let e=Fo();if(e.list){console.log(`
|
|
25
25
|
\u{1F4C2} Available profile files:
|
|
26
26
|
`);let n=St();if(n.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let c of n)console.log(` ${c.file}`),console.log(` Total: ${c.count}, Unprocessed: ${c.unprocessed}`);console.log(""),process.exit(0)}console.log(`
|
|
27
27
|
========================================`),console.log("Profile Funnel Runner"),console.log(`========================================
|
|
@@ -31,8 +31,10 @@ Profiles to process: ${t.length}`),t.length===0&&(console.log(`
|
|
|
31
31
|
Profiles:`),t.slice(0,10).forEach((n,c)=>{console.log(` ${c+1}. ${n.name||"Unknown"} - ${n.fromJob?.company||"N/A"}`)}),t.length>10&&console.log(` ... and ${t.length-10} more`),console.log(`
|
|
32
32
|
Press Enter to start, or Ctrl+C to cancel...`),await new Promise(n=>{process.stdin.once("data",()=>n())}),console.log(`
|
|
33
33
|
\u{1F680} Starting browser...
|
|
34
|
-
`);let o=await
|
|
35
|
-
`)}catch
|
|
34
|
+
`);let o=await Mo.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),r=await o.newPage();try{let n=Ft();await r.setCookie(...n),console.log(`\u2713 Cookies loaded
|
|
35
|
+
`)}catch(n){console.error(`
|
|
36
|
+
[!] ${n.message}
|
|
37
|
+
`),await o.close(),process.exit(1)}let s=e.viewOnly?"view-only":"connect",i=Ye("funnel",s),l=await mt(r,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(n,c,a)=>{wt(e.source,n.profileUrl,{status:a.reason,connectionSent:a.connectionSent,withCustomMessage:a.withCustomMessage,message:a.messageSent,method:a.method,reason:a.reason,error:a.error,profileInfo:a.profileInfo})}});console.log(`
|
|
36
38
|
========================================`),console.log("Funnel Complete!"),console.log(`========================================
|
|
37
39
|
`);let u=yt(e.source);if(console.log(`Processed: ${u.processed}/${u.total}`),console.log(`Remaining: ${u.unprocessed}`),Object.keys(u.statuses).length>0){console.log(`
|
|
38
|
-
Status breakdown:`);for(let[n,c]of Object.entries(u.statuses))console.log(` ${n}: ${c}`)}Ie(i,"success",{sent:l.connectionsSent,viewed:l.viewed,errors:l.errors,skippedPending:l.skipped?.pending||0,skippedConnected:l.skipped?.connected||0}),await o.close(),process.exit(0)}
|
|
40
|
+
Status breakdown:`);for(let[n,c]of Object.entries(u.statuses))console.log(` ${n}: ${c}`)}Ie(i,"success",{sent:l.connectionsSent,viewed:l.viewed,errors:l.errors,skippedPending:l.skipped?.pending||0,skippedConnected:l.skipped?.connected||0}),await o.close(),process.exit(0)}To().catch(e=>{console.error("Funnel failed:",e);try{Ie(null,"error",null,e.message)}catch{}process.exit(1)});
|