ilml-plugin-linkedin 1.3.0 → 1.4.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 +15 -0
- package/README.md +49 -12
- package/dist/run.mjs +37 -35
- package/dist/warmScan.mjs +5 -0
- package/ilml-plugin.json +2 -1
- package/package.json +11 -4
- package/target-companies.json +58 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.4.0
|
|
4
|
+
- **Apply phase no longer crashes on Puppeteer hangs.** When Chrome's CDP (DevTools Protocol) channel goes dead — the most common failure mode on long sessions, where `Runtime.callFunctionOn timed out` previously aborted the run with `Apply phase crashed: ... Increase the 'protocolTimeout' setting` — the runner now detects it via a fast liveness probe and transparently recovers. Recovery escalates: close the dead page and open a fresh one (cookies preserved, navigates back to the search URL, continues applying) → if that keeps failing, full browser restart → if even that fails, exit with a clear actionable error. Jobs in the queue aren't lost; the run keeps going.
|
|
5
|
+
- **Clearer error messages when authentication expires.** Two distinct, easy-to-confuse expiries are now detected separately and printed with the *correct* command:
|
|
6
|
+
- LinkedIn cookies expired → `Run: ilml linkedin login`
|
|
7
|
+
- iLiveMyLife platform token expired (~once a month) → `Run: ilml login` (different layer)
|
|
8
|
+
- **Recruiter funnel no longer runs on a dead browser.** If apply ended due to an unrecoverable CDP failure, funnel is skipped with a clear log line and the recruiter list is preserved on disk for the next run, instead of throwing a stack trace at the user.
|
|
9
|
+
- **Session summary** now reports recovery activity when it kicks in: `Page recoveries (CDP): N`, `Browser restarts: M`. Lines only appear when nonzero, so healthy runs are unchanged.
|
|
10
|
+
- Internal: new `src/cdpRecovery.mjs` (`livenessProbe`, `livenessProbeStrict`, `browserAlive`, `recoverPage`, `relaunchBrowser`, `isCdpDeadError`, `withTimeout`). Two-strike liveness probe (3s × 2 with 5s gap) keeps false positives near zero — healthy LinkedIn pages answer `evaluate(()=>1)` in <50 ms even when network is slow or spinners are running. Recovery limits: 3 consecutive page recoveries, then escalates to browser restart (cap 2). Browser-level liveness check before page recovery skips the 5-minute `newPage()` hang when the whole Chrome process is gone.
|
|
11
|
+
- Internal: `ERROR_RULES` in `run.mjs` simplified — CDP-class errors (`ProtocolError`, `Target closed`, `Runtime.callFunctionOn timed out`, etc.) are now intercepted before `classifyError` and re-thrown to `iterateAllPages` for centralized page recovery. No more `closeJobApplicationPopup`-on-a-dead-page hangs that themselves cost another `protocolTimeout`. Queue mode (`--job-urls`) gets the same recovery path
|
|
12
|
+
|
|
13
|
+
## 1.3.1
|
|
14
|
+
- **`ilml linkedin warm-scan` now actually works** — `warmScan.mjs` was previously only reachable through `npm run warm-scan` in the dev repo. Wired through to the published plugin: added `warm-scan` to `ilml-plugin.json` commands, `warmScan.mjs` to the build entry points, and `target-companies.json` to the npm tarball. The script now finds `target-companies.json` in three locations, in order: `<DATA_DIR>/target-companies.json` (user override), `<package-root>/target-companies.json` (shipped default for prod), source dir (dev mode)
|
|
15
|
+
- README polish — leads with the killer differentiators that were buried before: AI drafts that go through user review with re-check on push, auto-triaged inbox classification, `--skip-unread` sync that preserves LinkedIn unread badges. Daily-commands table descriptions tightened (especially `today`, `enrich`, `daily`, which were vague or wrong); added `apply-queue` and `warm-scan` rows; new "Common routines" section with morning-triage / active-search / passive-pipeline / targeted-networking patterns
|
|
16
|
+
- `package.json` — new npm `description` (one line that says what the plugin does, not just a list of subcommands), expanded `keywords` for npm discovery (`linkedin-bot`, `linkedin-automation`, `easy-apply`, `job-search`, `inbox-sync`, `recruiter-outreach`, `ai-messaging`)
|
|
17
|
+
|
|
3
18
|
## 1.3.0
|
|
4
19
|
- **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
20
|
- `ilml plugin update linkedin` no longer wipes your LinkedIn session — sessions survive plugin updates
|
package/README.md
CHANGED
|
@@ -11,7 +11,9 @@ It also automates LinkedIn from the terminal — applying to jobs, drafting outr
|
|
|
11
11
|
## What you get
|
|
12
12
|
|
|
13
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
|
|
14
|
+
- **AI-assisted messaging — drafts go through you.** [Lifebot](https://ilivemylife.io) reads the full context of each thread (history, your notes, tags) and drafts replies in your voice. You review the batch in one pass and push approved drafts as a group. On push, the bot re-scans every thread first — if a new incoming message arrived since you reviewed, it pauses that draft and flags it for re-review instead of sending blind. Never autopilot.
|
|
15
|
+
- **An auto-triaged inbox.** Every conversation gets classified (recruiter / hiring manager / founder / investor / spam / event), tagged, prioritized, and stamped with a suggested next action. `ilml linkedin today` prints a no-browser daily plan: who to reply to, what to do, in priority order — before you've even opened LinkedIn.
|
|
16
|
+
- **Inbox sync that doesn't break your workflow.** A `--skip-unread` mode pulls the conversation list and metadata without "opening" unread threads — LinkedIn keeps showing the unread badges until *you* read them in the UI. Use the bot as an analyst without losing your own attention markers.
|
|
15
17
|
- **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
18
|
- **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
19
|
- **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.
|
|
@@ -158,21 +160,56 @@ Sessions live in your active ilml scope (`<scope>/.ilivemylife/plugins-state/lin
|
|
|
158
160
|
|
|
159
161
|
| Command | What it does |
|
|
160
162
|
|---|---|
|
|
161
|
-
| `ilml linkedin apply` | Auto-apply to LinkedIn Easy Apply jobs
|
|
162
|
-
| `ilml linkedin sync
|
|
163
|
-
| `ilml linkedin today` |
|
|
164
|
-
| `ilml linkedin enrich` |
|
|
165
|
-
| `ilml linkedin report` |
|
|
166
|
-
| `ilml linkedin scout` | Scan jobs
|
|
167
|
-
| `ilml linkedin
|
|
168
|
-
| `ilml linkedin
|
|
169
|
-
| `ilml linkedin
|
|
170
|
-
| `ilml linkedin
|
|
171
|
-
| `ilml linkedin
|
|
163
|
+
| `ilml linkedin apply` | Auto-apply to LinkedIn Easy Apply jobs from `LINKEDIN_SEARCH_URL`. Stops after `MAX_APPLY_FOR_RUN`. |
|
|
164
|
+
| `ilml linkedin sync-all` | Pull the LinkedIn inbox into the local DB and the graph. Add `--skip-unread` to scan without opening unread threads (preserves LinkedIn's unread badges). `--full` for a full re-scan, `--report` for stats only with no browser. |
|
|
165
|
+
| `ilml linkedin today` | No-browser daily plan: who to reply to, what to do, in priority order. Reads already-synced data — doesn't open LinkedIn. |
|
|
166
|
+
| `ilml linkedin enrich` | Re-classify every conversation (recruiter / hiring manager / founder / investor / spam / event) and rebuild priorities, summaries, and suggested actions. Offline, no browser. |
|
|
167
|
+
| `ilml linkedin report` | Print the summary of the latest session. |
|
|
168
|
+
| `ilml linkedin scout` | Scan jobs from `LINKEDIN_SCOUT_URLS` and score them — without applying. Builds a queue for `apply-queue`. |
|
|
169
|
+
| `ilml linkedin apply-queue` | Apply to the top-scored jobs from the latest `scout` run. |
|
|
170
|
+
| `ilml linkedin messages` | Batch messaging — draft, review, then push. Nothing sends without your approval. Common forms: `messages --review-drafts` (review pending drafts) and `messages --push-drafts` (push approved). |
|
|
171
|
+
| `ilml linkedin funnel` | Run the recruiter / founder / investor connection-request queue. |
|
|
172
|
+
| `ilml linkedin visit` | Visit recruiter / target profiles so they see you in "who viewed your profile". |
|
|
173
|
+
| `ilml linkedin viewers` | Pull the "who viewed your profile" list. |
|
|
174
|
+
| `ilml linkedin warm-scan` | Find 1st-degree connections at target companies (offline, no browser). Reads your already-synced people / conversations and groups them by company so you know who you can message directly versus where you need cold outreach. Override the company list via `--companies="Anthropic,OpenAI"` or pick a named group with `--group=topPaying`. |
|
|
175
|
+
| `ilml linkedin daily` | Full pipeline in one command: `sync-all` → `apply` → `scout` → `funnel` → `visit` → `viewers` → run report. |
|
|
172
176
|
| `ilml linkedin login` | Re-save LinkedIn cookies after a session expires. |
|
|
173
177
|
|
|
174
178
|
Run `ilml linkedin` (no subcommand) any time to see the list.
|
|
175
179
|
|
|
180
|
+
## Common routines
|
|
181
|
+
|
|
182
|
+
A few patterns that string the daily commands together. Outgoing messages always require your explicit approval (via `messages --push-drafts`); commands like `apply` and `funnel` do submit Easy Apply forms and connection requests on their own, scoped by `MAX_APPLY_FOR_RUN` and `FUNNEL_MAX_CONNECTIONS`.
|
|
183
|
+
|
|
184
|
+
**Morning triage** — see what needs attention before opening LinkedIn:
|
|
185
|
+
```bash
|
|
186
|
+
ilml linkedin sync-all --skip-unread # pull new messages without losing unread badges
|
|
187
|
+
ilml linkedin today # print prioritized day plan
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
**Active job search** — apply, scout, network on autopilot; you stay in the loop on outgoing messages:
|
|
191
|
+
```bash
|
|
192
|
+
ilml linkedin daily # apply + scout + funnel + visit + viewers + report
|
|
193
|
+
ilml linkedin messages --review-drafts # later: review the AI's drafted replies
|
|
194
|
+
ilml linkedin messages --push-drafts # push the ones you approved
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
**Passive pipeline** — keep the inbox synced and triaged without touching outgoing channels:
|
|
198
|
+
```bash
|
|
199
|
+
ilml linkedin sync-all --skip-unread
|
|
200
|
+
ilml linkedin enrich
|
|
201
|
+
ilml linkedin today
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
**Targeted networking** — figure out which target companies you can reach via existing connections before sending any cold outreach:
|
|
205
|
+
```bash
|
|
206
|
+
ilml linkedin warm-scan # default group
|
|
207
|
+
ilml linkedin warm-scan --group=topPaying # broader (FAANG + tier-1 + high-comp)
|
|
208
|
+
ilml linkedin warm-scan --companies="Anthropic,OpenAI" # one-off override
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Compose your own from the commands above — each one is a standalone script.
|
|
212
|
+
|
|
176
213
|
## Updating
|
|
177
214
|
|
|
178
215
|
Updates ship via npm. The CLI checks the registry and only downloads when a newer version is actually available:
|
package/dist/run.mjs
CHANGED
|
@@ -1,50 +1,52 @@
|
|
|
1
|
-
var Bo=Object.defineProperty;var st=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>{for(var n in t)Bo(e,n,{get:t[n],enumerable:!0})};var Gt={};it(Gt,{default:()=>zo,getAllUnprocessedProfiles:()=>Ne,getSummary:()=>ue,getUnprocessedProfiles:()=>Me,listFiles:()=>Jt,loadProfiles:()=>Fe,markProfileProcessed:()=>Bt,saveProfile:()=>we,saveProfiles:()=>Ut});import"dotenv/config";import*as A from"fs";import*as B from"path";import{fileURLToPath as Vo}from"url";function ge(){A.existsSync(V)||A.mkdirSync(V,{recursive:!0})}function Qo(e,t){try{let n=`${e}-${at()}.json`,r=A.readdirSync(V).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==n),o=0;for(let s of r)JSON.parse(A.readFileSync(B.join(V,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&o++;return o}catch{return 0}}function at(){return new Date().toISOString().split("T")[0]}function ct(e,t=null){let n=t||at();return B.join(V,`${e}-${n}.json`)}function Fe(e,t=null){ge();let n=ct(e,t);try{if(A.existsSync(n)){let r=A.readFileSync(n,"utf-8"),o=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${o.profiles.length} profiles from ${n}`),o.profiles}}catch(r){console.error(`Error loading profiles from ${n}:`,r.message)}return[]}function we(e,t){ge();let n=ct(e),r={source:e,date:at(),lastUpdated:new Date().toISOString(),profiles:[]};try{A.existsSync(n)&&(r=JSON.parse(A.readFileSync(n,"utf-8")))}catch(l){console.error(`Error reading ${n}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===t.profileUrl))return!1;let s=Qo(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{A.writeFileSync(n,JSON.stringify(r,null,2));let l=s>0?` (seen ${s} day${s>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${n}:`,l.message),!1}}function Ut(e,t){let n=0;for(let r of t)we(e,r)&&n++;return n}function Me(e,t=null){return Fe(e,t).filter(r=>!r.processed)}function Bt(e,t,n,r=null){ge();let o=ct(e,r);try{if(!A.existsSync(o))return;let s=JSON.parse(A.readFileSync(o,"utf-8")),l=s.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let a=n.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}s.lastUpdated=new Date().toISOString(),A.writeFileSync(o,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function ue(e){let t=Fe(e),n=t.filter(o=>o.processed),r=t.filter(o=>!o.processed);return{total:t.length,processed:n.length,unprocessed:r.length,statuses:n.reduce((o,s)=>(o[s.status]=(o[s.status]||0)+1,o),{})}}function Jt(){ge();try{return A.readdirSync(V).filter(t=>t.endsWith(".json")).map(t=>{let[n,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let o=JSON.parse(A.readFileSync(B.join(V,t),"utf-8"));return{file:t,source:n,date:r,count:o.profiles?.length||0,unprocessed:o.profiles?.filter(s=>!s.processed).length||0}}catch{return{file:t,source:n,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function Ne(e){ge();let t=[];try{let o=A.readdirSync(V).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of o)try{let l=JSON.parse(A.readFileSync(B.join(V,s),"utf-8"));l.profiles&&t.push({file:s,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let n=new Set,r=[];for(let{date:o,profiles:s}of t)for(let l of s)!l.processed&&l.profileUrl&&!n.has(l.profileUrl)&&(n.add(l.profileUrl),r.push({...l,_fromDate:o}));return r}var Wo,Yo,V,zo,ut=st(()=>{Wo=Vo(import.meta.url),Yo=B.dirname(B.dirname(Wo)),V=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Yo,"collected-profiles");zo={loadProfiles:Fe,saveProfile:we,saveProfiles:Ut,getUnprocessedProfiles:Me,getAllUnprocessedProfiles:Ne,markProfileProcessed:Bt,getSummary:ue,listFiles:Jt}});var gt={};it(gt,{addEncounter:()=>ye,canSendConnection:()=>Qe,commitDataSnapshot:()=>to,default:()=>rn,getAllApplications:()=>Zt,getPersonStatus:()=>Ge,getQuestionStats:()=>eo,getQuotaStatus:()=>Ce,getRecentConnections:()=>Ye,linkPersonToJob:()=>Je,loadApplicationQuestions:()=>bt,loadConversations:()=>Wt,loadJobs:()=>Oe,loadPeople:()=>Q,loadQuota:()=>Ve,loadSyncState:()=>zt,logApplicationQuestions:()=>he,migrateFromDailyFiles:()=>Qt,recordConnectionSent:()=>We,resetCaches:()=>en,saveConversations:()=>Yt,saveJobs:()=>Ue,savePeople:()=>ne,saveQuota:()=>ht,saveSyncState:()=>Kt,updateConnectionStatus:()=>He,upsertJob:()=>Be,upsertPerson:()=>xe});import"dotenv/config";import*as E from"fs";import*as j from"path";import{fileURLToPath as Ko}from"url";import{execSync as dt}from"child_process";function en(){de=null,pe=null,W=null,te=null,fe=null,ee=null}function N(){E.existsSync(M)||E.mkdirSync(M,{recursive:!0})}function oe(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";E.writeFileSync(r,n);for(let o=0;o<3;o++)try{E.renameSync(r,e);return}catch(s){if(o<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function ve(e,t){if(!E.existsSync(e))return null;try{let n=JSON.parse(E.readFileSync(e,"utf-8"));try{E.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${j.resolve(e)}`);let r=e+".backup";if(E.existsSync(r))try{let o=JSON.parse(E.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{E.copyFileSync(r,e)}catch{}return o}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{E.copyFileSync(e,e+".corrupted")}catch{}return null}}function me(){return new Date().toISOString().split("T")[0]}function Q(){return de||(N(),de=ve(pt,"people.json")||{},de)}function ne(e){N(),de=e;try{oe(pt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${j.resolve(pt)}`)}}function Oe(){return pe||(N(),pe=ve(ft,"jobs.json")||{},pe)}function Ue(e){N(),pe=e;try{oe(ft,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${j.resolve(ft)}`)}}function Wt(){return te||(N(),te=ve(Pe,"conversations.json")||{},tn(te),te)}function tn(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let o=(n.messages||[]).find(s=>s.status==="draft");o&&n.draftStatus&&n.draftStatus!=="pending"&&(o.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{oe(Pe,e)}catch{}}}function Yt(e){N(),te=e;try{oe(Pe,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${j.resolve(Pe)}`)}}function xe(e,t={}){if(!e)return null;let n=Q(),r=me(),o=new Date().toISOString(),s=n[e];if(s){s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=o,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of yt)t[l]!=null&&(s[l]=t[l])}else n[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:o};return ne(n),n[e]}function Be(e,t={}){if(!e)return null;let n=Oe(),r=me(),o=n[e];if(o){let s=["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 s)t[l]!=null&&(o[l]=t[l])}else n[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 Ue(n),n[e]}function Je(e,t){if(!e||!t)return;let n=Q(),r=n[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),ne(n)))}function ye(e,t){if(!e||!t)return;let n=Q(),r=n[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:me(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(s.jobId=String(t.jobId)),t.jobTitle&&(s.jobTitle=t.jobTitle),t.jobCompany&&(s.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===s.date&&a.source===s.source&&a.action===s.action&&(a.jobId||"")===(s.jobId||""))&&(r.encounters.push(s),r.lastUpdated=new Date().toISOString(),ne(n))}function Ge(e){return e&&Q()[e]?.connectionStatus||null}function He(e,t,n={}){if(!e)return;let r=Q(),o=r[e];if(o||(xe(e,n.profileInfo||{}),o=r[e]),!!o){if(o.connectionStatus=t,o.connectionDate=me(),o.connectionMethod=n.method||o.connectionMethod,o.messageSent=n.messageSent||o.messageSent,o.lastUpdated=new Date().toISOString(),n.profileInfo)for(let s of yt)n.profileInfo[s]!=null&&(o[s]=n.profileInfo[s]);ne(r)}}function Ve(){return W||(N(),W=ve(Ht,"quota.json"),(!W||!W.connections)&&(W={connections:[]}),W)}function ht(e){N(),W=e;try{oe(Ht,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function We(e,t="unknown"){let n=Ve(),r=new Date;n.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),ht(n)}function Ye(){let e=Ve(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=n)}function Qe(){let e=Ye(),t=me(),n=e.filter(i=>i.date===t).length,r=e.length,o=n>=Se,s=r>=ke,l=!o&&!s,a={allowed:l,daily:{sent:n,max:Se},weekly:{sent:r,max:ke}};return l||(a.reason=o?`Daily limit reached (${n}/${Se})`:`Weekly limit reached (${r}/${ke})`),a}function Ce(){let e=Ye(),t=me(),n=e.filter(o=>o.date===t).length,r=e.length;return{daily:{sent:n,max:Se,remaining:Se-n},weekly:{sent:r,max:ke,remaining:ke-r}}}function on(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function Qt(){N();let e=E.readdirSync(M).filter(s=>s.endsWith(".json")&&s!=="people.json"&&s!=="jobs.json"&&s!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
1
|
+
var en=Object.defineProperty;var pt=(e,t)=>()=>(e&&(t=e(e=0)),t);var ft=(e,t)=>{for(var n in t)en(e,n,{get:t[n],enumerable:!0})};var Kt={};ft(Kt,{default:()=>cn,getAllUnprocessedProfiles:()=>Ge,getSummary:()=>de,getUnprocessedProfiles:()=>Je,listFiles:()=>zt,loadProfiles:()=>Be,markProfileProcessed:()=>Qt,saveProfile:()=>Ce,saveProfiles:()=>Yt});import"dotenv/config";import*as T from"fs";import*as J from"path";import{fileURLToPath as rn}from"url";function xe(){T.existsSync(Q)||T.mkdirSync(Q,{recursive:!0})}function an(e,t){try{let n=`${e}-${yt()}.json`,r=T.readdirSync(Q).filter(i=>i.startsWith(e)&&i.endsWith(".json")&&i!==n),o=0;for(let i of r)JSON.parse(T.readFileSync(J.join(Q,i),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&o++;return o}catch{return 0}}function yt(){return new Date().toISOString().split("T")[0]}function ht(e,t=null){let n=t||yt();return J.join(Q,`${e}-${n}.json`)}function Be(e,t=null){xe();let n=ht(e,t);try{if(T.existsSync(n)){let r=T.readFileSync(n,"utf-8"),o=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${o.profiles.length} profiles from ${n}`),o.profiles}}catch(r){console.error(`Error loading profiles from ${n}:`,r.message)}return[]}function Ce(e,t){xe();let n=ht(e),r={source:e,date:yt(),lastUpdated:new Date().toISOString(),profiles:[]};try{T.existsSync(n)&&(r=JSON.parse(T.readFileSync(n,"utf-8")))}catch(l){console.error(`Error reading ${n}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===t.profileUrl))return!1;let i=an(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:i}),r.lastUpdated=new Date().toISOString();try{T.writeFileSync(n,JSON.stringify(r,null,2));let l=i>0?` (seen ${i} day${i>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${n}:`,l.message),!1}}function Yt(e,t){let n=0;for(let r of t)Ce(e,r)&&n++;return n}function Je(e,t=null){return Be(e,t).filter(r=>!r.processed)}function Qt(e,t,n,r=null){xe();let o=ht(e,r);try{if(!T.existsSync(o))return;let i=JSON.parse(T.readFileSync(o,"utf-8")),l=i.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let a=n.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),T.writeFileSync(o,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function de(e){let t=Be(e),n=t.filter(o=>o.processed),r=t.filter(o=>!o.processed);return{total:t.length,processed:n.length,unprocessed:r.length,statuses:n.reduce((o,i)=>(o[i.status]=(o[i.status]||0)+1,o),{})}}function zt(){xe();try{return T.readdirSync(Q).filter(t=>t.endsWith(".json")).map(t=>{let[n,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let o=JSON.parse(T.readFileSync(J.join(Q,t),"utf-8"));return{file:t,source:n,date:r,count:o.profiles?.length||0,unprocessed:o.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function Ge(e){xe();let t=[];try{let o=T.readdirSync(Q).filter(i=>i.startsWith(e+"-")&&i.endsWith(".json")).sort().reverse();for(let i of o)try{let l=JSON.parse(T.readFileSync(J.join(Q,i),"utf-8"));l.profiles&&t.push({file:i,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let n=new Set,r=[];for(let{date:o,profiles:i}of t)for(let l of i)!l.processed&&l.profileUrl&&!n.has(l.profileUrl)&&(n.add(l.profileUrl),r.push({...l,_fromDate:o}));return r}var sn,ln,Q,cn,bt=pt(()=>{sn=rn(import.meta.url),ln=J.dirname(J.dirname(sn)),Q=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"collected-profiles"):J.join(ln,"collected-profiles");cn={loadProfiles:Be,saveProfile:Ce,saveProfiles:Yt,getUnprocessedProfiles:Je,getAllUnprocessedProfiles:Ge,markProfileProcessed:Qt,getSummary:de,listFiles:zt}});var $t={};ft($t,{addEncounter:()=>he,canSendConnection:()=>tt,commitDataSnapshot:()=>ao,default:()=>bn,getAllApplications:()=>io,getPersonStatus:()=>ze,getQuestionStats:()=>lo,getQuotaStatus:()=>Te,getRecentConnections:()=>et,linkPersonToJob:()=>Qe,loadApplicationQuestions:()=>Ct,loadConversations:()=>eo,loadJobs:()=>Ve,loadPeople:()=>K,loadQuota:()=>Xe,loadSyncState:()=>no,logApplicationQuestions:()=>be,migrateFromDailyFiles:()=>oo,recordConnectionSent:()=>Ze,resetCaches:()=>fn,saveConversations:()=>to,saveJobs:()=>We,savePeople:()=>se,saveQuota:()=>xt,saveSyncState:()=>ro,updateConnectionStatus:()=>Ke,upsertJob:()=>Ye,upsertPerson:()=>Ae});import"dotenv/config";import*as E from"fs";import*as j from"path";import{fileURLToPath as un}from"url";import{execSync as gt}from"child_process";function fn(){pe=null,fe=null,z=null,ne=null,me=null,oe=null}function M(){E.existsSync(F)||E.mkdirSync(F,{recursive:!0})}function re(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";E.writeFileSync(r,n);for(let o=0;o<3;o++)try{E.renameSync(r,e);return}catch(i){if(o<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Ee(e,t){if(!E.existsSync(e))return null;try{let n=JSON.parse(E.readFileSync(e,"utf-8"));try{E.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${j.resolve(e)}`);let r=e+".backup";if(E.existsSync(r))try{let o=JSON.parse(E.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{E.copyFileSync(r,e)}catch{}return o}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{E.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}function K(){return pe||(M(),pe=Ee(wt,"people.json")||{},pe)}function se(e){M(),pe=e;try{re(wt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${j.resolve(wt)}`)}}function Ve(){return fe||(M(),fe=Ee(St,"jobs.json")||{},fe)}function We(e){M(),fe=e;try{re(St,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${j.resolve(St)}`)}}function eo(){return ne||(M(),ne=Ee(He,"conversations.json")||{},mn(ne),ne)}function mn(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let o=(n.messages||[]).find(i=>i.status==="draft");o&&n.draftStatus&&n.draftStatus!=="pending"&&(o.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{re(He,e)}catch{}}}function to(e){M(),ne=e;try{re(He,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${j.resolve(He)}`)}}function Ae(e,t={}){if(!e)return null;let n=K(),r=ye(),o=new Date().toISOString(),i=n[e];if(i){i.seenCount=(i.seenCount||1)+1,i.lastSeen=r,i.lastUpdated=o,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of kt)t[l]!=null&&(i[l]=t[l])}else n[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:o};return se(n),n[e]}function Ye(e,t={}){if(!e)return null;let n=Ve(),r=ye(),o=n[e];if(o){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&&(o[l]=t[l])}else n[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 We(n),n[e]}function Qe(e,t){if(!e||!t)return;let n=K(),r=n[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),se(n)))}function he(e,t){if(!e||!t)return;let n=K(),r=n[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:ye(),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(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),se(n))}function ze(e){return e&&K()[e]?.connectionStatus||null}function Ke(e,t,n={}){if(!e)return;let r=K(),o=r[e];if(o||(Ae(e,n.profileInfo||{}),o=r[e]),!!o){if(o.connectionStatus=t,o.connectionDate=ye(),o.connectionMethod=n.method||o.connectionMethod,o.messageSent=n.messageSent||o.messageSent,o.lastUpdated=new Date().toISOString(),n.profileInfo)for(let i of kt)n.profileInfo[i]!=null&&(o[i]=n.profileInfo[i]);se(r)}}function Xe(){return z||(M(),z=Ee(Xt,"quota.json"),(!z||!z.connections)&&(z={connections:[]}),z)}function xt(e){M(),z=e;try{re(Xt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Ze(e,t="unknown"){let n=Xe(),r=new Date;n.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),xt(n)}function et(){let e=Xe(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=n)}function tt(){let e=et(),t=ye(),n=e.filter(s=>s.date===t).length,r=e.length,o=n>=$e,i=r>=_e,l=!o&&!i,a={allowed:l,daily:{sent:n,max:$e},weekly:{sent:r,max:_e}};return l||(a.reason=o?`Daily limit reached (${n}/${$e})`:`Weekly limit reached (${r}/${_e})`),a}function Te(){let e=et(),t=ye(),n=e.filter(o=>o.date===t).length,r=e.length;return{daily:{sent:n,max:$e,remaining:$e-n},weekly:{sent:r,max:_e,remaining:_e-r}}}function yn(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function oo(){M();let e=E.readdirSync(F).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(n).length} total (${o} new)`),{people:Object.keys(t).length,jobs:Object.keys(n).length}}function zt(){return fe||(N(),fe=ve(Vt,"sync-state.json")||{},fe)}function Kt(e){N(),fe=e;try{oe(Vt,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function bt(){if(ee)return ee;N();try{E.existsSync(mt)&&(ee=JSON.parse(E.readFileSync(mt,"utf-8")))}catch{}return ee||(ee={}),ee}function Xt(e){return Array.isArray(e.applications)}function Zt(){let e=bt();if(Xt(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function he(e){if(!e||!e.questions||e.questions.length===0)return;let t=bt(),n=e.jobId||"unknown",o={applicationId:`${n}_${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(s=>{let l={type:s.type||"input",question:s.labelText||s.question||"",answer:s.answer||""};return s.options&&(s.options.length<=nn?l.options=s.options:l.optionsOmitted=!0),s.page&&(l.page=s.page),s.wasPreFilled&&(l.wasPreFilled=!0),s.wasRetry&&(l.wasRetry=!0),l})};Xt(t)?(o.jobId=n,o.jobTitle=e.jobTitle||null,o.jobCompany=e.jobCompany||null,o.jobUrl=e.jobUrl||null,t.applications.push(o)):(t[n]||(t[n]={applications:[]}),t[n].applications.push(o));try{oe(mt,t)}catch(s){console.error(`[!] Failed to save application-questions.json: ${s.message}`)}}function eo(){let e=Zt(),t=new Map;for(let s of e)for(let l of s.questions||[]){let a=l.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:l.question,count:0,answers:new Map});let i=t.get(a);i.count++;let u=(l.answer||"").trim();i.answers.set(u,(i.answers.get(u)||0)+1)}let n=[...t.values()].sort((s,l)=>l.count-s.count),r=n.slice(0,15).map(s=>({question:s.question,count:s.count,topAnswer:[...s.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),o=n.filter(s=>s.answers.size>1&&s.count>=3).map(s=>({question:s.question,count:s.count,answers:[...s.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:o}}function to(e){if(E.existsSync(j.join(M,".git")))try{let t={cwd:M,stdio:"pipe",timeout:1e4};dt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{dt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');dt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Xo,Zo,M,pt,ft,Ht,Pe,Vt,mt,Se,ke,de,pe,W,te,fe,ee,yt,nn,rn,_e=st(()=>{Xo=Ko(import.meta.url),Zo=j.dirname(j.dirname(Xo)),M=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"collected-profiles"):j.join(Zo,"collected-profiles"),pt=j.join(M,"people.json"),ft=j.join(M,"jobs.json"),Ht=j.join(M,"quota.json"),Pe=j.join(M,"conversations.json"),Vt=j.join(M,"sync-state.json"),mt=j.join(M,"application-questions.json"),Se=20,ke=100,de=null,pe=null,W=null,te=null,fe=null,ee=null;yt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];nn=50;rn={loadPeople:Q,savePeople:ne,loadJobs:Oe,saveJobs:Ue,loadConversations:Wt,saveConversations:Yt,upsertPerson:xe,upsertJob:Be,linkPersonToJob:Je,addEncounter:ye,getPersonStatus:Ge,updateConnectionStatus:He,migrateFromDailyFiles:Qt,loadQuota:Ve,saveQuota:ht,recordConnectionSent:We,canSendConnection:Qe,getRecentConnections:Ye,getQuotaStatus:Ce,loadSyncState:zt,saveSyncState:Kt,commitDataSnapshot:to,logApplicationQuestions:he,getQuestionStats:eo}});var ho={};it(ho,{getJobDecision:()=>_t,getLastVisit:()=>bn,getScoutStats:()=>gn,loadCompanies:()=>yo,loadDiscoveredPeople:()=>$t,loadJobDecisions:()=>Ct,loadScoutedJobs:()=>vt,loadVisitLog:()=>Ke,recordVisit:()=>hn,resetCaches:()=>mn,saveCompany:()=>ze,saveDiscoveredPerson:()=>yn,saveScoutedJob:()=>xt,setJobDecision:()=>ie});import"dotenv/config";import*as J from"fs";import*as P from"path";import{fileURLToPath as dn}from"url";function Ie(){J.existsSync(se)||J.mkdirSync(se,{recursive:!0})}function qe(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";J.writeFileSync(r,n);for(let o=0;o<3;o++)try{J.renameSync(r,e);return}catch(s){if(o<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function De(e){try{if(J.existsSync(e))return JSON.parse(J.readFileSync(e,"utf-8"))}catch{}return null}function mn(){Ee=null,Ae=null,Te=null,je=null,re=null}function vt(){return Ee||(Ee=De(co)||{},Ee)}function xt(e,t){if(!e)return;Ie();let n=vt(),r=new Date().toISOString().slice(0,10);if(n[e]){for(let[o,s]of Object.entries(t))s!=null&&(n[e][o]=s);n[e].lastSeen=r}else n[e]={...t,scoutedAt:r,lastSeen:r};try{qe(co,n)}catch(o){console.error(`[!] Failed to save scouted-jobs.json: ${o.message}`)}}function Ct(){return Ae||(Ae=De(mo)||{},Ae)}function ie(e,t,n={}){if(!e||!t)return;Ie();let r=Ct(),o=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=o,n.reason&&(r[e].reason=n.reason),n.score!=null&&(r[e].score=n.score),n.source&&(r[e].source=n.source)):r[e]={status:t,decidedAt:o,updatedAt:o,reason:n.reason||null,score:n.score??null,source:n.source||null};try{qe(mo,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function _t(e){return Ct()[e]||null}function $t(){return Te||(Te=De(uo)||{},Te)}function yn(e,t){if(!e)return;Ie();let n=$t(),r=new Date().toISOString().slice(0,10);if(n[e]){let o=n[e];t.name&&(o.name=t.name),t.title&&(o.title=t.title),t.company&&(o.company=t.company),t.location&&(o.location=t.location),t.role&&(o.role=t.role),t.isConnected!=null&&(o.isConnected=t.isConnected),t.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(t.jobId)||o.jobIds.push(t.jobId)),o.lastSeen=r,o.seenCount=(o.seenCount||1)+1}else n[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{qe(uo,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function yo(){return je||(je=De(fo)||{},je)}function ze(e,t){if(!e)return;Ie();let n=yo(),r=new Date().toISOString().slice(0,10);if(n[e]){let o=n[e];t.name&&(o.name=t.name),t.about&&(o.about=t.about),t.size&&(o.size=t.size),t.industries&&(o.industries=t.industries),t.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(t.jobId)||o.jobIds.push(t.jobId)),t.recruiterUrl&&(o.recruiterUrls||(o.recruiterUrls=[]),o.recruiterUrls.includes(t.recruiterUrl)||o.recruiterUrls.push(t.recruiterUrl)),o.lastSeen=r,o.jobCount=o.jobIds?.length||0}else n[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{qe(fo,n)}catch(o){console.error(`[!] Failed to save companies.json: ${o.message}`)}}function Ke(){return re||(re=De(po)||{visits:[]},Array.isArray(re.visits)||(re.visits=[]),re)}function hn(e,t={}){if(!e)return;Ie();let n=Ke();n.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;n.visits=n.visits.filter(o=>new Date(o.date).getTime()>r);try{qe(po,n)}catch(o){console.error(`[!] Failed to save visit-log.json: ${o.message}`)}}function bn(e){let t=Ke();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function gn(){let e=vt(),t=$t(),n=Object.values(e),r=Object.values(t),o={};for(let c of n)c.company&&(o[c.company]=(o[c.company]||0)+1);let s=Object.entries(o).sort((c,d)=>d[1]-c[1]).slice(0,5).map(([c,d])=>`${c} (${d})`),l={};for(let c of n)for(let d of c.techStack||[])l[d]=(l[d]||0)+1;let a=Object.entries(l).sort((c,d)=>d[1]-c[1]).slice(0,8).map(([c,d])=>`${c} (${d})`),i=Ke(),u=new Date().toISOString().slice(0,10),p=i.visits.filter(c=>c.date.startsWith(u)).length,f=new Set(i.visits.map(c=>c.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:r.length,topCompanies:s,topTech:a,totalVisited:f,todayVisited:p,lastScoutDate:n.length>0?n.sort((c,d)=>(d.scoutedAt||"").localeCompare(c.scoutedAt||""))[0]?.scoutedAt:null}}var pn,fn,se,co,uo,po,fo,mo,Ee,Ae,Te,je,re,Et=st(()=>{pn=dn(import.meta.url),fn=P.dirname(P.dirname(pn)),se=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"market-research"):P.join(fn,"market-research"),co=P.join(se,"scouted-jobs.json"),uo=P.join(se,"discovered-people.json"),po=P.join(se,"visit-log.json"),fo=P.join(se,"companies.json"),mo=P.join(se,"job-decisions.json");Ee=null;Ae=null;Te=null;je=null;re=null});import Dn from"puppeteer";import*as No from"fs";async function b(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(r=>setTimeout(r,n))}function Nt(e){return parseInt(e,10)||0}async function U(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let o=r.innerText||"",s=o.includes("Premium")||o.includes("premium")||o.includes("Upgrade")||o.includes("upgrade"),l=o.includes("Try for")||o.includes("free trial")||o.includes("/month")||o.includes("per month")||o.includes("Start my")||o.includes("Subscribe"),a=o.includes("Get hired faster")||o.includes("Get hired 2x");if(s||l||a){let i=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:o.substring(0,80)};let u=r.querySelectorAll("button");for(let p of u){let f=p.innerText?.trim().toLowerCase()||"",c=p.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||c.includes("dismiss"))return p.click(),{dismissed:!0,matched:o.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let r=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import{createGraphClient as Jo,resolveToken as Go}from"@ilivemylife/graph-sdk";import{config as Ho}from"dotenv";Ho();var Pt=Go()||process.env.TOKEN;Pt||(console.error(`
|
|
3
|
+
`);let t=K(),n=Ve(),r=0,o=0;e.sort();for(let i of e){let l=j.join(F,i),a;try{a=JSON.parse(E.readFileSync(l,"utf-8"))}catch(p){console.log(` Skipping ${i}: ${p.message}`);continue}let s=a.date||i.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,c=a.source||i.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${i}: no profiles array`);continue}console.log(` ${i}: ${a.profiles.length} profiles`);for(let p of a.profiles){let f=p.profileUrl;if(!f)continue;let u=t[f];if(u){u.seenCount=(u.seenCount||1)+1,s&&(!u.lastSeen||s>u.lastSeen)&&(u.lastSeen=s),s&&(!u.firstSeen||s<u.firstSeen)&&(u.firstSeen=s),c&&!u.sources?.includes(c)&&(u.sources=u.sources||[],u.sources.push(c));for(let d of kt)p[d]!=null&&(u[d]=p[d]);p.status&&p.processed&&(u.connectionStatus=p.status,u.connectionDate=s,p.funnelResult&&(u.connectionMethod=p.funnelResult.method||u.connectionMethod,u.messageSent=p.funnelResult.message||u.messageSent)),u.lastUpdated=new Date().toISOString()}else t[f]={name:p.name||null,title:p.title||null,location:p.location||null,company:p.company||null,connectionDegree:p.connectionDegree||null,connectionsCount:p.connectionsCount||null,mutualConnections:p.mutualConnections||null,photoUrl:p.photoUrl||null,hasVerifiedBadge:p.hasVerifiedBadge||!1,firstSeen:s,lastSeen:s,seenCount:1,sources:c?[c]:[],connectionStatus:p.processed&&p.status||null,connectionDate:p.processed?s:null,connectionMethod:p.funnelResult?.method||null,messageSent:p.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(p.fromJob?.url){let d=yn(p.fromJob.url);d&&(t[f].jobIds||(t[f].jobIds=[]),t[f].jobIds.includes(d)||t[f].jobIds.push(d),n[d]?n[d].recruiterUrl||(n[d].recruiterUrl=f):(n[d]={title:p.fromJob.title||null,company:p.fromJob.company||null,location:null,salary:null,url:p.fromJob.url,applied:!0,appliedDate:s,recruiterUrl:f,firstSeen:s},o++))}}}return se(t),We(n),console.log(`
|
|
4
|
+
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(n).length} total (${o} new)`),{people:Object.keys(t).length,jobs:Object.keys(n).length}}function no(){return me||(M(),me=Ee(Zt,"sync-state.json")||{},me)}function ro(e){M(),me=e;try{re(Zt,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Ct(){if(oe)return oe;M();try{E.existsSync(vt)&&(oe=JSON.parse(E.readFileSync(vt,"utf-8")))}catch{}return oe||(oe={}),oe}function so(e){return Array.isArray(e.applications)}function io(){let e=Ct();if(so(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function be(e){if(!e||!e.questions||e.questions.length===0)return;let t=Ct(),n=e.jobId||"unknown",o={applicationId:`${n}_${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<=hn?l.options=i.options:l.optionsOmitted=!0),i.page&&(l.page=i.page),i.wasPreFilled&&(l.wasPreFilled=!0),i.wasRetry&&(l.wasRetry=!0),l})};so(t)?(o.jobId=n,o.jobTitle=e.jobTitle||null,o.jobCompany=e.jobCompany||null,o.jobUrl=e.jobUrl||null,t.applications.push(o)):(t[n]||(t[n]={applications:[]}),t[n].applications.push(o));try{re(vt,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function lo(){let e=io(),t=new Map;for(let i of e)for(let l of i.questions||[]){let a=l.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:l.question,count:0,answers:new Map});let s=t.get(a);s.count++;let c=(l.answer||"").trim();s.answers.set(c,(s.answers.get(c)||0)+1)}let n=[...t.values()].sort((i,l)=>l.count-i.count),r=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),o=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:o}}function ao(e){if(E.existsSync(j.join(F,".git")))try{let t={cwd:F,stdio:"pipe",timeout:1e4};gt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{gt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');gt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var dn,pn,F,wt,St,Xt,He,Zt,vt,$e,_e,pe,fe,z,ne,me,oe,kt,hn,bn,je=pt(()=>{dn=un(import.meta.url),pn=j.dirname(j.dirname(dn)),F=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"collected-profiles"):j.join(pn,"collected-profiles"),wt=j.join(F,"people.json"),St=j.join(F,"jobs.json"),Xt=j.join(F,"quota.json"),He=j.join(F,"conversations.json"),Zt=j.join(F,"sync-state.json"),vt=j.join(F,"application-questions.json"),$e=20,_e=100,pe=null,fe=null,z=null,ne=null,me=null,oe=null;kt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];hn=50;bn={loadPeople:K,savePeople:se,loadJobs:Ve,saveJobs:We,loadConversations:eo,saveConversations:to,upsertPerson:Ae,upsertJob:Ye,linkPersonToJob:Qe,addEncounter:he,getPersonStatus:ze,updateConnectionStatus:Ke,migrateFromDailyFiles:oo,loadQuota:Xe,saveQuota:xt,recordConnectionSent:Ze,canSendConnection:tt,getRecentConnections:et,getQuotaStatus:Te,loadSyncState:no,saveSyncState:ro,commitDataSnapshot:ao,logApplicationQuestions:be,getQuestionStats:lo}});var xo={};ft(xo,{getJobDecision:()=>Dt,getLastVisit:()=>Tn,getScoutStats:()=>jn,loadCompanies:()=>ko,loadDiscoveredPeople:()=>qt,loadJobDecisions:()=>It,loadScoutedJobs:()=>Tt,loadVisitLog:()=>nt,recordVisit:()=>An,resetCaches:()=>_n,saveCompany:()=>ot,saveDiscoveredPerson:()=>En,saveScoutedJob:()=>jt,setJobDecision:()=>ae});import"dotenv/config";import*as G from"fs";import*as N from"path";import{fileURLToPath as xn}from"url";function Pe(){G.existsSync(le)||G.mkdirSync(le,{recursive:!0})}function Fe(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";G.writeFileSync(r,n);for(let o=0;o<3;o++)try{G.renameSync(r,e);return}catch(i){if(o<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Me(e){try{if(G.existsSync(e))return JSON.parse(G.readFileSync(e,"utf-8"))}catch{}return null}function _n(){De=null,qe=null,Le=null,Re=null,ie=null}function Tt(){return De||(De=Me(bo)||{},De)}function jt(e,t){if(!e)return;Pe();let n=Tt(),r=new Date().toISOString().slice(0,10);if(n[e]){for(let[o,i]of Object.entries(t))i!=null&&(n[e][o]=i);n[e].lastSeen=r}else n[e]={...t,scoutedAt:r,lastSeen:r};try{Fe(bo,n)}catch(o){console.error(`[!] Failed to save scouted-jobs.json: ${o.message}`)}}function It(){return qe||(qe=Me(vo)||{},qe)}function ae(e,t,n={}){if(!e||!t)return;Pe();let r=It(),o=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=o,n.reason&&(r[e].reason=n.reason),n.score!=null&&(r[e].score=n.score),n.source&&(r[e].source=n.source)):r[e]={status:t,decidedAt:o,updatedAt:o,reason:n.reason||null,score:n.score??null,source:n.source||null};try{Fe(vo,r)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Dt(e){return It()[e]||null}function qt(){return Le||(Le=Me(go)||{},Le)}function En(e,t){if(!e)return;Pe();let n=qt(),r=new Date().toISOString().slice(0,10);if(n[e]){let o=n[e];t.name&&(o.name=t.name),t.title&&(o.title=t.title),t.company&&(o.company=t.company),t.location&&(o.location=t.location),t.role&&(o.role=t.role),t.isConnected!=null&&(o.isConnected=t.isConnected),t.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(t.jobId)||o.jobIds.push(t.jobId)),o.lastSeen=r,o.seenCount=(o.seenCount||1)+1}else n[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{Fe(go,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function ko(){return Re||(Re=Me(So)||{},Re)}function ot(e,t){if(!e)return;Pe();let n=ko(),r=new Date().toISOString().slice(0,10);if(n[e]){let o=n[e];t.name&&(o.name=t.name),t.about&&(o.about=t.about),t.size&&(o.size=t.size),t.industries&&(o.industries=t.industries),t.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(t.jobId)||o.jobIds.push(t.jobId)),t.recruiterUrl&&(o.recruiterUrls||(o.recruiterUrls=[]),o.recruiterUrls.includes(t.recruiterUrl)||o.recruiterUrls.push(t.recruiterUrl)),o.lastSeen=r,o.jobCount=o.jobIds?.length||0}else n[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{Fe(So,n)}catch(o){console.error(`[!] Failed to save companies.json: ${o.message}`)}}function nt(){return ie||(ie=Me(wo)||{visits:[]},Array.isArray(ie.visits)||(ie.visits=[]),ie)}function An(e,t={}){if(!e)return;Pe();let n=nt();n.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;n.visits=n.visits.filter(o=>new Date(o.date).getTime()>r);try{Fe(wo,n)}catch(o){console.error(`[!] Failed to save visit-log.json: ${o.message}`)}}function Tn(e){let t=nt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function jn(){let e=Tt(),t=qt(),n=Object.values(e),r=Object.values(t),o={};for(let u of n)u.company&&(o[u.company]=(o[u.company]||0)+1);let i=Object.entries(o).sort((u,d)=>d[1]-u[1]).slice(0,5).map(([u,d])=>`${u} (${d})`),l={};for(let u of n)for(let d of u.techStack||[])l[d]=(l[d]||0)+1;let a=Object.entries(l).sort((u,d)=>d[1]-u[1]).slice(0,8).map(([u,d])=>`${u} (${d})`),s=nt(),c=new Date().toISOString().slice(0,10),p=s.visits.filter(u=>u.date.startsWith(c)).length,f=new Set(s.visits.map(u=>u.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:r.length,topCompanies:i,topTech:a,totalVisited:f,todayVisited:p,lastScoutDate:n.length>0?n.sort((u,d)=>(d.scoutedAt||"").localeCompare(u.scoutedAt||""))[0]?.scoutedAt:null}}var Cn,$n,le,bo,go,wo,So,vo,De,qe,Le,Re,ie,Lt=pt(()=>{Cn=xn(import.meta.url),$n=N.dirname(N.dirname(Cn)),le=process.env.DATA_DIR?N.resolve(process.env.DATA_DIR,"market-research"):N.join($n,"market-research"),bo=N.join(le,"scouted-jobs.json"),go=N.join(le,"discovered-people.json"),wo=N.join(le,"visit-log.json"),So=N.join(le,"companies.json"),vo=N.join(le,"job-decisions.json");De=null;qe=null;Le=null;Re=null;ie=null});import Hn from"puppeteer";import*as Qo from"fs";async function b(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(r=>setTimeout(r,n))}function Ht(e){return parseInt(e,10)||0}async function B(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let o=r.innerText||"",i=o.includes("Premium")||o.includes("premium")||o.includes("Upgrade")||o.includes("upgrade"),l=o.includes("Try for")||o.includes("free trial")||o.includes("/month")||o.includes("per month")||o.includes("Start my")||o.includes("Subscribe"),a=o.includes("Get hired faster")||o.includes("Get hired 2x");if(i||l||a){let s=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:o.substring(0,80)};let c=r.querySelectorAll("button");for(let p of c){let f=p.innerText?.trim().toLowerCase()||"",u=p.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||u.includes("dismiss"))return p.click(),{dismissed:!0,matched:o.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let r=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import{createGraphClient as tn,resolveToken as on}from"@ilivemylife/graph-sdk";import{config as nn}from"dotenv";nn();var Vt=on()||process.env.TOKEN;Vt||(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 Z=Jo({token:Pt});var ae=12e4;async function ce(e,{retries:t=2}={}){let n=process.env.NODE_EASY_APPLY_MAIN;if(!n||n.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let o=await Z.askLifebot(n,e,{timeout:ae});return ae=Math.max(12e4,ae*.9),o.content}catch(o){if(o.constructor.name==="LifebotTimeoutError"&&r<t){ae=Math.min(ae*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(ae/1e3)}s...`);continue}throw o}}async function Ot(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let n=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),n+=`Additional info: ${t}`),await ce(n)}async function lt(e,t){let n=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ce(n)}async function Re(e,t){let n=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ce(n)}ut();import{LIFEBOT_MESSAGE_TYPES as To}from"@ilivemylife/graph-sdk";_e();async function oo(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function sn(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(r=>n.includes(r.toLowerCase()))}async function ln(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(2e3+Math.random()*2e3),await U(e)&&(console.log(" Dismissed Premium overlay"),await b(1500),await oo(e,t));let r=await e.evaluate(()=>{let o=document.querySelector("h1")?.textContent?.trim()||null,s=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,a=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,u=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,f=document.querySelector(".dist-value")?.textContent?.trim()||null,d=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,g=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),h=g?parseInt(g[1],10):null,k=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,w=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:o,title:s,location:l,about:a,company:u,connectionDegree:f,connectionsCount:d,mutualConnections:h,photoUrl:k,hasVerifiedBadge:w}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(n){console.error(`Error viewing profile ${t}:`,n.message);try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{}return null}}async function $e(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(n).map(i=>i.getAttribute("aria-label")),o=document.querySelector('button[aria-label*="Message"]'),s=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:n.length,pendingLabels:r,hasMessageBtn:!!o,hasConnectBtn:!!s};return n.length>0?{status:"pending",debug:l}:o&&!s?{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 wt(e){let t=null,n=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(i=u.textContent?.trim(),i&&!i.includes("notification")))return i;let p=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(p)return p.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let i=await e.evaluate(()=>{let p=document.querySelectorAll('a[href*="custom-invite"]');return{count:p.length,labels:Array.from(p).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(p=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),c=p.toLowerCase().split(" ")[0],d=null,m=null;for(let y of f){let g=y.getBoundingClientRect();if(g.width===0||g.height===0)continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(c)){d=y;break}m||(m=y)}return d||m||null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let i=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let u=await e.evaluate(f=>{let c=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),d=document.querySelectorAll("button[aria-label]");return Array.from(d).filter(y=>{let g=y.getAttribute("aria-label")||"";return(g.toLowerCase().includes("invite")||g.toLowerCase().includes("connect"))&&c.test(g)}).map(y=>y.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let c=document.querySelectorAll("button[aria-label]"),d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let m of c){let y=m.getAttribute("aria-label")||"";if((y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&d.test(y))return m}return null},i);let p=t?.asElement?.()||null;if(p||await t?.dispose?.().catch(()=>{}),p)return console.log(" Found: button matching profile name"),{button:p,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let i=await e.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping primary button: wrong person (${i})`),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 o=n?n.split(" ")[0].toLowerCase():"",s=null;for(let i of r){let u=await e.evaluate((p,f)=>{let c=p.className.includes("muted"),d=p.className.includes("sticky-header")||p.className.includes("sticky"),m=p.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,y=(p.getAttribute("aria-label")||"").toLowerCase(),g=y.includes("invite"),h=f?y.includes(f):!0;return{isMuted:c,isStickyHeader:d,inRecommendations:m,hasInvite:g,matchesName:h,ariaLabel:y}},i,o);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}s=i;break}}for(let i of r)i!==s&&await i.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,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,a=await e.$$('button[id*="profile-overflow-action"]');for(let i of a){let u=await e.evaluate(p=>{let f=p.getBoundingClientRect(),c=f.width>0&&f.height>0,d=p.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:c,isInStickyHeader:d,top:f.top}},i);if(u.isVisible&&!u.isInStickyHeader){l=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of a)i!==l&&await i.dispose().catch(()=>{});if(!l&&a.length>0&&(l=a[a.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 i=await e.evaluateHandle(()=>{let p=Array.from(document.querySelectorAll("button, a")).find(c=>{let d=c.innerText?.trim(),m=c.getAttribute("aria-label")||"",y=c.getBoundingClientRect();return y.top<100||y.top>600||y.width===0?!1:d==="Follow"||d==="Message"||d==="Connect"||m.includes("Follow")||m.includes("Message")||m.includes("Invite")});if(!p)return null;let f=p.parentElement;for(let c=0;c<8&&f;c++){for(let d of f.querySelectorAll("button"))if(d.innerText?.trim()==="More"&&d!==p)return d;f=f.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),l),await b(500),await e.evaluate(p=>p.click(),l),await b(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let p=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let c of f){let d=c.querySelector('a[href*="custom-invite"]');if(d)return d;for(let m of c.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(m.innerText?.trim()==="Connect")return m}return null});u=p?.asElement?.()||null,u||await p?.dispose?.().catch(()=>{})}if(!u){let p=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),c=[];for(let d of f)for(let m of d.querySelectorAll('[role="menuitem"], a, div')){let y=m.innerText?.trim();y&&y.length<40&&c.push(y)}return[...new Set(c)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(p)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let i=await e.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping generic button: wrong person (${i})`),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 an(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await b(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),o=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),s=n.tag==="DIV";if(o){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(p=>p.click(),t)]),await b(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await b(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await b(3e3)):(await e.evaluate(u=>u.click(),t),await b(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 a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),i=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${i}`:` \u26A0 No modal after connect click \u2014 ${i}`),"success"}async function cn(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 b(1500);let n=await wt(e);if(n){await e.evaluate(o=>o.click(),n),await b(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(o=>o.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function un(e,t,n={}){let{message:r=null,useCustomMessage:o=!0,skipIfPending:s=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=n,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
9
|
-
--- Connecting: ${u} ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(5e3),await U(e)&&(console.log(" Dismissed Premium overlay"),await b(2e3),await oo(e,t),await b(2e3)),i.profileInfo=await e.evaluate(()=>{let h=document.querySelector("h1")?.textContent?.trim()||null,S=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,k=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,x=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,T=document.querySelector(".dist-value")?.textContent?.trim()||null,L=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,K=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),be=K?parseInt(K[1],10):null,le=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,Y=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:h,title:S,location:k,company:x,connectionDegree:T,connectionsCount:L,mutualConnections:be,photoUrl:le,hasVerifiedBadge:Y}}),a.length>0&&sn(i.profileInfo?.location,a))return console.log(` \u26A0 Excluded location: ${i.profileInfo.location}`),i.reason="excluded_location",i;let f=await $e(e);if(f==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await U(e);let c=await wt(e);if(!c&&(await U(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await b(2e3),c=await wt(e)),!c))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=c.method,await an(e,c.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(4e3);let h=await $e(e);if(h==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${h} \u2014 trying More dropdown...`),await U(e),await b(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),S),await b(500),await S.click().catch(()=>e.evaluate(w=>w.click(),S)),await b(2e3);let k=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(k){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(I=>I.click(),k),await b(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),i.reason="premium_required",i;if(await $e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await b(500),i.reason="premium_required",i}catch(k){return console.log(" More dropdown failed:",k.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let h=await e.$('button[aria-label="Dismiss"]');return h&&await h.click(),await b(500),i.reason="email_required",i}let y=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!y&&!g){let h=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let k=S.querySelector('button[aria-label="Add a note"]'),w=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!w}});if(h.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=S?.asElement?.()||null,y||await S.dispose().catch(()=>{})}if(h.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}}if(o){if(y&&r){if(console.log(" Adding personalized note..."),await y.click(),await b(1500),await e.$("div.modal-upsell")){let k=await cn(e);return i.success=k,i.connectionSent=k,i.reason=k?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",k);await S.type(w,{delay:20}),await b(500);let x=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(x){try{await x.evaluate(I=>I.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=w,i}}}else if(g){console.log(" Sending without note...");try{await g.evaluate(h=>h.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(y&&!r){console.log(" No message provided, sending without note...");let h=await e.$('button[aria-label="Send without a note"]');if(h){try{await h.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let h=g;if(h){try{await h.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(c.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 b(4e3)),await U(e),await b(500);let S=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let w of S){let x=await e.evaluate(I=>{let T=I.getBoundingClientRect();return{visible:T.width>0&&T.height>0,inSticky:!!I.closest('.sticky-header, [class*="sticky"]')}},w);if(x.visible&&!x.inSticky){k=w;break}}!k&&S.length>0&&(k=S[S.length-1]);for(let w of S)w!==k&&await w.dispose().catch(()=>{});if(k)try{await e.evaluate(x=>x.scrollIntoView({behavior:"smooth",block:"center"}),k),await b(500),await k.click().catch(()=>e.evaluate(x=>x.click(),k)),await b(2e3);let w=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(w){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(C=>C.click(),w),await b(3e3);let x=e.url();if(x.includes("/premium/")||x.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await $e(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await $e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let T=await e.$('button[aria-label="Send without a note"]');if(T){console.log(" Modal appeared via More dropdown, sending without note...");try{await T.evaluate(C=>C.click())}catch{}return await b(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(u){console.error(` \u2717 Error: ${u.message}`),i.reason="error",i.error=u.message;let p=u.message.toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("browser has disconnected")||p.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{i.fatal=!0}return i}}async function St(e,t,n={}){let{message:r=null,useCustomMessage:o=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:p="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
10
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${
|
|
8
|
+
`),process.exit(1));var te=tn({token:Vt});var ce=12e4;async function ue(e,{retries:t=2}={}){let n=process.env.NODE_EASY_APPLY_MAIN;if(!n||n.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let o=await te.askLifebot(n,e,{timeout:ce});return ce=Math.max(12e4,ce*.9),o.content}catch(o){if(o.constructor.name==="LifebotTimeoutError"&&r<t){ce=Math.min(ce*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(ce/1e3)}s...`);continue}throw o}}async function Wt(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let n=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),n+=`Additional info: ${t}`),await ue(n)}async function mt(e,t){let n=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ue(n)}async function Ue(e,t){let n=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ue(n)}bt();import{LIFEBOT_MESSAGE_TYPES as Oo}from"@ilivemylife/graph-sdk";je();async function co(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function gn(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(r=>n.includes(r.toLowerCase()))}async function wn(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(2e3+Math.random()*2e3),await B(e)&&(console.log(" Dismissed Premium overlay"),await b(1500),await co(e,t));let r=await e.evaluate(()=>{let o=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,a=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,d=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,g=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),h=g?parseInt(g[1],10):null,k=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,w=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:o,title:i,location:l,about:a,company:c,connectionDegree:f,connectionsCount:d,mutualConnections:h,photoUrl:k,hasVerifiedBadge:w}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(n){console.error(`Error viewing profile ${t}:`,n.message);try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{}return null}}async function Ie(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(n).map(s=>s.getAttribute("aria-label")),o=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:n.length,pendingLabels:r,hasMessageBtn:!!o,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:l}:o&&!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 _t(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(s=c.textContent?.trim(),s&&!s.includes("notification")))return s;let p=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(p)return p.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let p=document.querySelectorAll('a[href*="custom-invite"]');return{count:p.length,labels:Array.from(p).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(p=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),u=p.toLowerCase().split(" ")[0],d=null,m=null;for(let y of f){let g=y.getBoundingClientRect();if(g.width===0||g.height===0)continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(u)){d=y;break}m||(m=y)}return d||m||null},n);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(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let c=await e.evaluate(f=>{let u=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),d=document.querySelectorAll("button[aria-label]");return Array.from(d).filter(y=>{let g=y.getAttribute("aria-label")||"";return(g.toLowerCase().includes("invite")||g.toLowerCase().includes("connect"))&&u.test(g)}).map(y=>y.getAttribute("aria-label")?.slice(0,50))},s);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(f=>{let u=document.querySelectorAll("button[aria-label]"),d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let m of u){let y=m.getAttribute("aria-label")||"";if((y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&d.test(y))return m}return null},s);let p=t?.asElement?.()||null;if(p||await t?.dispose?.().catch(()=>{}),p)return console.log(" Found: button matching profile name"),{button:p,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let s=await e.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),t),c=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(c)&&(console.log(` Skipping primary button: wrong person (${s})`),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 o=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of r){let c=await e.evaluate((p,f)=>{let u=p.className.includes("muted"),d=p.className.includes("sticky-header")||p.className.includes("sticky"),m=p.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,y=(p.getAttribute("aria-label")||"").toLowerCase(),g=y.includes("invite"),h=f?y.includes(f):!0;return{isMuted:u,isStickyHeader:d,inRecommendations:m,hasInvite:g,matchesName:h,ariaLabel:y}},s,o);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}i=s;break}}for(let s of r)s!==i&&await s.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,a=await e.$$('button[id*="profile-overflow-action"]');for(let s of a){let c=await e.evaluate(p=>{let f=p.getBoundingClientRect(),u=f.width>0&&f.height>0,d=p.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:u,isInStickyHeader:d,top:f.top}},s);if(c.isVisible&&!c.isInStickyHeader){l=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of a)s!==l&&await s.dispose().catch(()=>{});if(!l&&a.length>0&&(l=a[a.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 s=await e.evaluateHandle(()=>{let p=Array.from(document.querySelectorAll("button, a")).find(u=>{let d=u.innerText?.trim(),m=u.getAttribute("aria-label")||"",y=u.getBoundingClientRect();return y.top<100||y.top>600||y.width===0?!1:d==="Follow"||d==="Message"||d==="Connect"||m.includes("Follow")||m.includes("Message")||m.includes("Invite")});if(!p)return null;let f=p.parentElement;for(let u=0;u<8&&f;u++){for(let d of f.querySelectorAll("button"))if(d.innerText?.trim()==="More"&&d!==p)return d;f=f.parentElement}return null});l=s?.asElement?.()||null,l||await s?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),l),await b(500),await e.evaluate(p=>p.click(),l),await b(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 p=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let u of f){let d=u.querySelector('a[href*="custom-invite"]');if(d)return d;for(let m of u.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(m.innerText?.trim()==="Connect")return m}return null});c=p?.asElement?.()||null,c||await p?.dispose?.().catch(()=>{})}if(!c){let p=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),u=[];for(let d of f)for(let m of d.querySelectorAll('[role="menuitem"], a, div')){let y=m.innerText?.trim();y&&y.length<40&&u.push(y)}return[...new Set(u)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(p)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),t),c=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(c)&&(console.log(` Skipping generic button: wrong person (${s})`),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 Sn(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await b(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),o=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV";if(o){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(p=>p.click(),t)]),await b(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 b(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await b(3e3)):(await e.evaluate(c=>c.click(),t),await b(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 a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),s=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${s}`:` \u26A0 No modal after connect click \u2014 ${s}`),"success"}async function vn(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 b(1500);let n=await _t(e);if(n){await e.evaluate(o=>o.click(),n),await b(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(o=>o.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function kn(e,t,n={}){let{message:r=null,useCustomMessage:o=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=n,s={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(`
|
|
9
|
+
--- Connecting: ${c} ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(5e3),await B(e)&&(console.log(" Dismissed Premium overlay"),await b(2e3),await co(e,t),await b(2e3)),s.profileInfo=await e.evaluate(()=>{let h=document.querySelector("h1")?.textContent?.trim()||null,v=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,k=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,x=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,L=document.querySelector(".dist-value")?.textContent?.trim()||null,we=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,Z=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),Oe=Z?parseInt(Z[1],10):null,C=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,D=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:h,title:v,location:k,company:x,connectionDegree:L,connectionsCount:we,mutualConnections:Oe,photoUrl:C,hasVerifiedBadge:D}}),a.length>0&&gn(s.profileInfo?.location,a))return console.log(` \u26A0 Excluded location: ${s.profileInfo.location}`),s.reason="excluded_location",s;let f=await Ie(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await B(e);let u=await _t(e);if(!u&&(await B(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await b(2e3),u=await _t(e)),!u))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;if(s.method=u.method,await Sn(e,u.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(4e3);let h=await Ie(e);if(h==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${h} \u2014 trying More dropdown...`),await B(e),await b(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),v),await b(500),await v.click().catch(()=>e.evaluate(w=>w.click(),v)),await b(2e3);let k=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(k){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(I=>I.click(),k),await b(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),s.reason="premium_required",s;if(await Ie(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await b(500),s.reason="premium_required",s}catch(k){return console.log(" More dropdown failed:",k.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let h=await e.$('button[aria-label="Dismiss"]');return h&&await h.click(),await b(500),s.reason="email_required",s}let y=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!y&&!g){let h=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let k=v.querySelector('button[aria-label="Add a note"]'),w=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!w}});if(h.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=v?.asElement?.()||null,y||await v.dispose().catch(()=>{})}if(h.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=v?.asElement?.()||null,g||await v.dispose().catch(()=>{})}}if(o){if(y&&r){if(console.log(" Adding personalized note..."),await y.click(),await b(1500),await e.$("div.modal-upsell")){let k=await vn(e);return s.success=k,s.connectionSent=k,s.reason=k?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",k);await v.type(w,{delay:20}),await b(500);let x=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(x){try{await x.evaluate(I=>I.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=w,s}}}else if(g){console.log(" Sending without note...");try{await g.evaluate(h=>h.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(y&&!r){console.log(" No message provided, sending without note...");let h=await e.$('button[aria-label="Send without a note"]');if(h){try{await h.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let h=g;if(h){try{await h.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(u.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 b(4e3)),await B(e),await b(500);let v=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let w of v){let x=await e.evaluate(I=>{let L=I.getBoundingClientRect();return{visible:L.width>0&&L.height>0,inSticky:!!I.closest('.sticky-header, [class*="sticky"]')}},w);if(x.visible&&!x.inSticky){k=w;break}}!k&&v.length>0&&(k=v[v.length-1]);for(let w of v)w!==k&&await w.dispose().catch(()=>{});if(k)try{await e.evaluate(x=>x.scrollIntoView({behavior:"smooth",block:"center"}),k),await b(500),await k.click().catch(()=>e.evaluate(x=>x.click(),k)),await b(2e3);let w=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(w){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(V=>V.click(),w),await b(3e3);let x=e.url();if(x.includes("/premium/")||x.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await Ie(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await Ie(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let L=await e.$('button[aria-label="Send without a note"]');if(L){console.log(" Modal appeared via More dropdown, sending without note...");try{await L.evaluate(V=>V.click())}catch{}return await b(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(c){console.error(` \u2717 Error: ${c.message}`),s.reason="error",s.error=c.message;let p=c.message.toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("browser has disconnected")||p.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{s.fatal=!0}return s}}async function Et(e,t,n={}){let{message:r=null,useCustomMessage:o=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:s=null,excludeLocations:c=[],source:p="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
10
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${o?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!l){let d=Te();console.log(`Quota: today ${d.daily.sent}/${d.daily.max} | week ${d.weekly.sent}/${d.weekly.max}`)}console.log("");let u=0;for(let d=0;d<t.length;d++){let m=t[d];try{if(e.isClosed()){console.log(`
|
|
11
11
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
12
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${d+1}/${t.length}] Skipping - no URL`);continue}let y=
|
|
13
|
-
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(
|
|
14
|
-
\u26A0 ${
|
|
15
|
-
=== 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 d=Ce();console.log(` Quota remaining: today ${d.daily.remaining}/${d.daily.max} | week ${d.weekly.remaining}/${d.weekly.max}`)}return f}_e();async function no(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let o=null,s=null;for(let f of r)if(o=document.querySelector(f),o){s=f;break}if(!o){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let c=f.parentElement;for(;c&&c!==document.body;){if(c.scrollHeight>c.clientHeight){o=c,s="parent of li.scaffold-layout__list-item";break}c=c.parentElement}}}if(!o)return{found:!1,triedSelectors:r};let l=o.scrollTop,a=300,i=300,u=50,p=0;for(;p<u&&(o.scrollBy(0,a),await new Promise(f=>setTimeout(f,i)),!(o.scrollTop+o.clientHeight>=o.scrollHeight));)p++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:o.scrollTop,scrollHeight:o.scrollHeight,attempts:p}},t)}async function ro(e,{easyApplyOnly:t=!0}={}){let n=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(o=>{let l=(o.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=o.querySelector("a.job-card-container__link");if(a){let i=a.getAttribute("href").split("?")[0],u=o.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),p=o.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=o.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),c=o.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:i,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${i}`,jobTitle:u,companyName:p,location:f,salary:c||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return t?n.filter(r=>r.isEasyApply&&r.href):n.filter(r=>r.href)}async function so(e){let t=await e.evaluate(()=>{let n=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(n&&!n.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return n.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await b(2e3),t.success}async function kt(e,t){let n=e.url();if(n.includes("/jobs/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let o=e.url();if(!o.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${o.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function io(e,t,n,r){for(let o of t){await kt(e,r)&&(await U(e),await b(2e3));let l=await e.$(`a[data-control-id="${o.dataId}"]`),a="dataId";if(!l){let i=o.id?.match(/\d+/)?.[0];i&&(l=await e.$(`a[href*="/jobs/view/${i}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${o.jobTitle}`);let i=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(c=>c.scrollIntoView({block:"center"}),l),await b(300),await l.click(),await b(1500);let u=!1;for(let c=0;c<8;c++){let d=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(d&&d!==i){u=!0;break}await b(500)}if(!u){await e.evaluate(c=>c.click(),l),await b(1500);for(let c=0;c<6;c++){let d=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(d&&d!==i){u=!0;break}await b(500)}u||console.log(` \u26A0 Panel did not update after retry click for: ${o.jobTitle}`)}let p=await e.evaluate(()=>{let c=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let d of c)for(let m of d.querySelectorAll("button")){let y=m.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return m.click(),y}return null});p&&console.log(` Dismissed popup before processing (${p})`);let{keepGoing:f}=await n(e,o);if(!f)return{keepGoing:!1}}else{let i=o.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${o.jobTitle||o.id} (dataId=${o.dataId}, jobId=${i})`)}}return{keepGoing:!0}}async function lo(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,n=t.querySelector(".hirer-card__hirer-information");if(n){let l=n.querySelector('a[href*="/in/"]'),a=n.querySelector(".jobs-poster__name")||n.querySelector("strong")||n.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"poster_name"}}let o=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(o){let l=o.querySelector('a[href*="/in/"]');if(l)return{name:(o.querySelector(".jobs-poster__name")||o.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let s=t.querySelectorAll('a[href*="/in/"]');for(let l of s){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function ao(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",o={},s=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let X of s){let rt=X.querySelector(".job-criteria__subheader")?.textContent?.trim(),Mt=X.querySelector(".job-criteria__text")?.textContent?.trim();rt&&Mt&&(o[rt.toLowerCase()]=Mt)}let l=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let X of l)new RegExp("\\b"+X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(X.replace(/\\\+/g,"+"));let u=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,c=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),d=c?.innerText?.trim()||null,y=(c?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,h=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",k=h.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=h.match(/(\d[\d,]*)\s+applicant/i),x=w?parseInt(w[1].replace(/,/g,"")):null,I=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),T=Array.from(I).map(X=>X.innerText?.trim()?.replace(/\s+/g," ")),L=T.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,$=T.join(" ")+" "+h,R=/\bremote\b/i.test($)?"remote":/\bhybrid\b/i.test($)?"hybrid":/\bon-?site\b/i.test($)?"onsite":null,K=/\bcontract\b/i.test($)?"contract":/\bfull-?time\b/i.test($)?"full-time":/\bpart-?time\b/i.test($)?"part-time":/\bfreelance\b/i.test($)?"freelance":/\btemporary\b/i.test($)?"temporary":null,H=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",Y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",D=(H+" "+r+" "+Y).toLowerCase(),F=H.toLowerCase(),_=[];/\bremote\b/.test(D)&&_.push("remote"),/\bhybrid\b/.test(D)&&_.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(D)&&_.push("onsite"),(_.length===0||!_.includes("remote")&&!_.includes("hybrid")&&!_.includes("onsite"))&&/remote/i.test(Y)&&_.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(F)&&_.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(F)&&_.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(F)&&!_.includes("managerial")&&_.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(F)?_.push("junior"):/\b(senior|sr\.?)\b/i.test(F)?_.push("senior"):/\b(staff|principal|distinguished)\b/i.test(F)?_.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(F)?_.push("executive"):/\b(lead|team lead)\b/i.test(F)&&_.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(D)&&_.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(D)&&_.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(D)&&_.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(D)&&_.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(D)&&_.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(D)&&_.push("mobile"),/\b(architect)\b/i.test(F)&&_.push("architect"),/\b(consultant|consulting)\b/i.test(F)&&_.push("consultant");let Ft=(o["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(Ft)||/\bcontract\b/i.test(D))&&_.push("contract"),/full.?time|permanent/i.test(Ft)&&_.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(Y)&&_.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(Y)&&_.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&_.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:d,companyUrl:y?y.startsWith("/")?"https://www.linkedin.com"+y:y:null,aboutCompany:u,seniority:o["seniority level"]||null,employmentType:o["employment type"]||null,industries:o.industries||null,jobFunction:o["job function"]||null,postedTime:k,applicantCount:x,companySize:L,workplaceType:R,contractType:K,techStack:[...new Set(a)],jobTags:[...new Set(_)]}})}Et();import"dotenv/config";import*as O from"fs";import*as q from"path";import{fileURLToPath as wn}from"url";var Sn=wn(import.meta.url),kn=q.dirname(Sn),wo=q.dirname(q.dirname(kn)),Xe=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"collected-profiles"):q.join(wo,"collected-profiles"),Ze=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"market-research"):q.join(wo,"market-research"),At=1,vn=[{version:1,file:"./v001-normalize-jobs-and-questions.mjs"}];function So(e){return q.join(e,".schema-version")}function Tt(e){let t=So(e);if(!O.existsSync(t))return{version:0,migrations:[]};try{return JSON.parse(O.readFileSync(t,"utf-8"))}catch{return{version:0,migrations:[]}}}function xn(e,t){O.writeFileSync(So(e),JSON.stringify(t,null,2))}function bo(e,t){if(!O.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,r=O.readdirSync(e).filter(o=>o.endsWith(".json")&&!o.includes(".backup"));for(let o of r){let s=q.join(e,o),l=q.join(e,o+n);try{O.copyFileSync(s,l)}catch(a){console.error(` [!] Failed to backup ${o}: ${a.message}`)}}r.length>0&&console.log(` Backed up ${r.length} files in ${q.basename(e)}/ (${n})`)}var go=!1;async function ko(){if(go)return;go=!0;let e=Tt(Xe),t=Tt(Ze),n=Math.min(e.version,t.version);if(n>=At)return;console.log(`
|
|
16
|
-
\u{1F4E6} Schema migration: v${n} \u2192 v${
|
|
17
|
-
Running migration v${String(o.version).padStart(3,"0")}...`),
|
|
18
|
-
[FATAL] Migration v${o.version} failed: ${
|
|
19
|
-
`),process.exit(1)}let l=new Date().toISOString(),a={version:o.version,name:
|
|
20
|
-
\u2713 Schema is now at v${
|
|
21
|
-
`)}import"dotenv/config";import*as
|
|
12
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${d+1}/${t.length}] Skipping - no URL`);continue}let y=ze(m.profileUrl);if(y==="pending"||y==="connected"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"){console.log(`[${d+1}/${t.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${y})`),y==="pending"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,s&&await s(m,f,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${d+1}/${t.length}] ${m.name||m.profileUrl}`);let g=null;if(l){let h=await wn(e,m.profileUrl);h?(f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:h}):(f.errors++,g={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let h=tt();if(!h.allowed){console.log(` \u26A0 Global quota exhausted: ${h.reason}`);break}if(g=await kn(e,m.profileUrl,{message:r,useCustomMessage:o,excludeLocations:c}),g.success)f.connectionsSent++,g.connectionSent&&Ze(m.profileUrl,p);else switch(g.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(g?.fatal){console.log(`
|
|
13
|
+
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(u++,u>=3){console.log(`
|
|
14
|
+
\u26A0 ${u} consecutive errors \u2014 aborting funnel`);break}}else u=0;if(g&&g.reason&&(Ke(m.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),he(m.profileUrl,{source:p||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:g.reason})),s&&await s(m,f,g),d<t.length-1){let h=a+Math.random()*2e3;await b(h)}}if(console.log(`
|
|
15
|
+
=== 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 d=Te();console.log(` Quota remaining: today ${d.daily.remaining}/${d.daily.max} | week ${d.weekly.remaining}/${d.weekly.max}`)}return f}je();async function uo(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let o=null,i=null;for(let f of r)if(o=document.querySelector(f),o){i=f;break}if(!o){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let u=f.parentElement;for(;u&&u!==document.body;){if(u.scrollHeight>u.clientHeight){o=u,i="parent of li.scaffold-layout__list-item";break}u=u.parentElement}}}if(!o)return{found:!1,triedSelectors:r};let l=o.scrollTop,a=300,s=300,c=50,p=0;for(;p<c&&(o.scrollBy(0,a),await new Promise(f=>setTimeout(f,s)),!(o.scrollTop+o.clientHeight>=o.scrollHeight));)p++;return{found:!0,usedSelector:i,initialScroll:l,finalScroll:o.scrollTop,scrollHeight:o.scrollHeight,attempts:p}},t)}async function po(e,{easyApplyOnly:t=!0}={}){let n=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(o=>{let l=(o.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=o.querySelector("a.job-card-container__link");if(a){let s=a.getAttribute("href").split("?")[0],c=o.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),p=o.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=o.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),u=o.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:s,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${s}`,jobTitle:c,companyName:p,location:f,salary:u||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return t?n.filter(r=>r.isEasyApply&&r.href):n.filter(r=>r.href)}async function fo(e){let t=await e.evaluate(()=>{let n=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(n&&!n.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return n.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await b(2e3),t.success}async function At(e,t){let n=e.url();if(n.includes("/jobs/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let o=e.url();if(!o.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${o.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function mo(e,t,n,r){for(let o of t){await At(e,r)&&(await B(e),await b(2e3));let l=await e.$(`a[data-control-id="${o.dataId}"]`),a="dataId";if(!l){let s=o.id?.match(/\d+/)?.[0];s&&(l=await e.$(`a[href*="/jobs/view/${s}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${o.jobTitle}`);let s=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(u=>u.scrollIntoView({block:"center"}),l),await b(300),await l.click(),await b(1500);let c=!1;for(let u=0;u<8;u++){let d=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(d&&d!==s){c=!0;break}await b(500)}if(!c){await e.evaluate(u=>u.click(),l),await b(1500);for(let u=0;u<6;u++){let d=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(d&&d!==s){c=!0;break}await b(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${o.jobTitle}`)}let p=await e.evaluate(()=>{let u=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let d of u)for(let m of d.querySelectorAll("button")){let y=m.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return m.click(),y}return null});p&&console.log(` Dismissed popup before processing (${p})`);let{keepGoing:f}=await n(e,o);if(!f)return{keepGoing:!1}}else{let s=o.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${o.jobTitle||o.id} (dataId=${o.dataId}, jobId=${s})`)}}return{keepGoing:!0}}async function yo(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,n=t.querySelector(".hirer-card__hirer-information");if(n){let l=n.querySelector('a[href*="/in/"]'),a=n.querySelector(".jobs-poster__name")||n.querySelector("strong")||n.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"poster_name"}}let o=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(o){let l=o.querySelector('a[href*="/in/"]');if(l)return{name:(o.querySelector(".jobs-poster__name")||o.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let l of i){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function ho(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",o={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let Y of i){let ee=Y.querySelector(".job-criteria__subheader")?.textContent?.trim(),ke=Y.querySelector(".job-criteria__text")?.textContent?.trim();ee&&ke&&(o[ee.toLowerCase()]=ke)}let l=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let Y of l)new RegExp("\\b"+Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(Y.replace(/\\\+/g,"+"));let c=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,u=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),d=u?.innerText?.trim()||null,y=(u?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,h=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",k=h.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=h.match(/(\d[\d,]*)\s+applicant/i),x=w?parseInt(w[1].replace(/,/g,"")):null,I=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),L=Array.from(I).map(Y=>Y.innerText?.trim()?.replace(/\s+/g," ")),we=L.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,U=L.join(" ")+" "+h,Se=/\bremote\b/i.test(U)?"remote":/\bhybrid\b/i.test(U)?"hybrid":/\bon-?site\b/i.test(U)?"onsite":null,Z=/\bcontract\b/i.test(U)?"contract":/\bfull-?time\b/i.test(U)?"full-time":/\bpart-?time\b/i.test(U)?"part-time":/\bfreelance\b/i.test(U)?"freelance":/\btemporary\b/i.test(U)?"temporary":null,P=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",D=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",_=(P+" "+r+" "+D).toLowerCase(),A=P.toLowerCase(),$=[];/\bremote\b/.test(_)&&$.push("remote"),/\bhybrid\b/.test(_)&&$.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(_)&&$.push("onsite"),($.length===0||!$.includes("remote")&&!$.includes("hybrid")&&!$.includes("onsite"))&&/remote/i.test(D)&&$.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(A)&&$.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(A)&&$.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(A)&&!$.includes("managerial")&&$.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(A)?$.push("junior"):/\b(senior|sr\.?)\b/i.test(A)?$.push("senior"):/\b(staff|principal|distinguished)\b/i.test(A)?$.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(A)?$.push("executive"):/\b(lead|team lead)\b/i.test(A)&&$.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(_)&&$.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(_)&&$.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(_)&&$.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(_)&&$.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(_)&&$.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(_)&&$.push("mobile"),/\b(architect)\b/i.test(A)&&$.push("architect"),/\b(consultant|consulting)\b/i.test(A)&&$.push("consultant");let ve=(o["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(ve)||/\bcontract\b/i.test(_))&&$.push("contract"),/full.?time|permanent/i.test(ve)&&$.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(D)&&$.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(D)&&$.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&$.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:d,companyUrl:y?y.startsWith("/")?"https://www.linkedin.com"+y:y:null,aboutCompany:c,seniority:o["seniority level"]||null,employmentType:o["employment type"]||null,industries:o.industries||null,jobFunction:o["job function"]||null,postedTime:k,applicantCount:x,companySize:we,workplaceType:Se,contractType:Z,techStack:[...new Set(a)],jobTags:[...new Set($)]}})}Lt();import"dotenv/config";import*as O from"fs";import*as q from"path";import{fileURLToPath as In}from"url";var Dn=In(import.meta.url),qn=q.dirname(Dn),_o=q.dirname(q.dirname(qn)),rt=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"collected-profiles"):q.join(_o,"collected-profiles"),st=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"market-research"):q.join(_o,"market-research"),Rt=1,Ln=[{version:1,file:"./v001-normalize-jobs-and-questions.mjs"}];function Eo(e){return q.join(e,".schema-version")}function Pt(e){let t=Eo(e);if(!O.existsSync(t))return{version:0,migrations:[]};try{return JSON.parse(O.readFileSync(t,"utf-8"))}catch{return{version:0,migrations:[]}}}function Rn(e,t){O.writeFileSync(Eo(e),JSON.stringify(t,null,2))}function Co(e,t){if(!O.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,r=O.readdirSync(e).filter(o=>o.endsWith(".json")&&!o.includes(".backup"));for(let o of r){let i=q.join(e,o),l=q.join(e,o+n);try{O.copyFileSync(i,l)}catch(a){console.error(` [!] Failed to backup ${o}: ${a.message}`)}}r.length>0&&console.log(` Backed up ${r.length} files in ${q.basename(e)}/ (${n})`)}var $o=!1;async function Ao(){if($o)return;$o=!0;let e=Pt(rt),t=Pt(st),n=Math.min(e.version,t.version);if(n>=Rt)return;console.log(`
|
|
16
|
+
\u{1F4E6} Schema migration: v${n} \u2192 v${Rt}`);let r=Ln.filter(o=>o.version>n);for(let o of r){console.log(`
|
|
17
|
+
Running migration v${String(o.version).padStart(3,"0")}...`),Co(rt,o.version),Co(st,o.version);let i=await import(o.file);try{await i.up(rt,st)}catch(s){console.error(`
|
|
18
|
+
[FATAL] Migration v${o.version} failed: ${s.message}`),console.error(` Backups are in collected-profiles/ and market-research/ (.pre-v${String(o.version).padStart(3,"0")}.backup)`),console.error(` Fix the issue and restart.
|
|
19
|
+
`),process.exit(1)}let l=new Date().toISOString(),a={version:o.version,name:i.NAME||`v${String(o.version).padStart(3,"0")}`,appliedAt:l};for(let s of[rt,st]){if(!O.existsSync(s))continue;let c=Pt(s);c.version=o.version,c.migratedAt=l,c.migrations.push(a),Rn(s,c)}console.log(` \u2713 Migration v${String(o.version).padStart(3,"0")} complete`)}try{let{resetCaches:o}=await Promise.resolve().then(()=>(je(),$t));o()}catch{}try{let{resetCaches:o}=await Promise.resolve().then(()=>(Lt(),xo));o()}catch{}console.log(`
|
|
20
|
+
\u2713 Schema is now at v${Rt}
|
|
21
|
+
`)}import"dotenv/config";import*as H from"fs";import*as X from"path";import{fileURLToPath as Mn}from"url";import"dotenv/config";function Pn(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r?`${n}m ${r}s`:`${n}m`}function Fn({scriptName:e,mode:t,status:n,error:r,duration:o}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),a=o?` ${Pn(o)}`:"",s=n==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${c} \u2014 ${s} \u2014 ${l}${a}`}async function To({scriptName:e,mode:t,status:n,summaryLines:r,error:o,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let s=`**${Fn({scriptName:e,mode:t,status:n,error:o,duration:i})}**
|
|
22
22
|
|
|
23
23
|
${r.join(`
|
|
24
|
-
`)}`;try{await
|
|
25
|
-
--- Pass ${r}/${n}: re-checking for new jobs ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3));let o=v.submitted,s=!0,l=!0;for(;s&&l;){await Rt(e,t);let a=await or(e,Uo,Bn);l=a.keepGoing;let i=a.jobsDone;if(console.log("keepGoing",l),console.log("pageDone"),console.log(i.length),!l)break;s=await Gn(e)}if(console.log(`Scraping pass ${r} complete.`),!l)break;if(v.submitted===o){console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${v.submitted-o} new jobs in pass ${r}.`)}}async function Io(e,t,n){let r=process.env.LINKEDIN_SEARCH_URL;return io(e,t,n,r)}async function qo(e,t){let n=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${n}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${n} from list`)):console.log(` Dismiss button not found for ${n}`)}async function Vn(e,t){try{let n=await lo(e);if(n&&n.profileUrl){n.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},we("recruiters-from-jobs",n)?(nt++,console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F3AF} RECRUITER FOUND \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Name: ${n.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${n.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(nt).padEnd(23)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")):console.log(` \u2139 Recruiter already saved: ${n.name}`),xe(n.profileUrl,{name:n.name,source:"recruiters-from-jobs"});let o=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(o){Je(n.profileUrl,o),ye(n.profileUrl,{source:"job-apply",jobId:o,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=n.fromJob?.companyUrl;s&&ze(s,{recruiterUrl:n.profileUrl,jobId:o})}return n}else console.log(" \u26AA No recruiter found on this job page");return null}catch(n){return console.error("Error extracting recruiter:",n.message),null}}async function ot(e){return await e.evaluate(()=>{let t=document.body.innerText||"",n=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+n;return r.includes("We limit daily submissions")||r.includes("We limit Easy Apply submissions")||r.includes("Easy Apply limit")||r.includes("reached today")||r.includes("apply tomorrow")})}async function Oo(e){try{let t=await e.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let o of n){let s=o.querySelectorAll("button");for(let l of s){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function Do(e){await e.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let i of a.querySelectorAll("button")){let u=i.innerText?.trim();if(u==="Continue applying"||u==="Got it"||u==="Dismiss"){i.click();return}}});let t=Date.now(),n=3e3,r=null;for(;!r&&Date.now()-t<n;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let l=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let i of a){let u=i.innerText?.trim();if(u==="Easy Apply"||u==="Apply")return i}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let o=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${o>400?` (waited ${o}ms)`:""}`),r){if(await e.evaluate(u=>u.disabled,r))return await ot(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(u=>u.tagName==="A",r)){await e.evaluate(u=>u.click(),r),await b(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await b(2e3)}}else await r.click(),await b(1500);return await ot(e)?(await Oo(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await ot(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Wn(e){return await e.evaluate(async()=>{function t(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let u=document.querySelector("#interop-outlet")?.shadowRoot;return u&&(i=u.querySelectorAll(".artdeco-inline-feedback__message")),i}let n=3e3,r=t();if(r?.length===0&&(await new Promise(i=>setTimeout(i,n)),r=t()),r?.length===0)return null;let o=r[0];console.log("errorMsg"),console.log(o);let s=o?.textContent.trim(),l=o.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=o.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(l),a||l){console.log("parentElement"),console.log(a);let i=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),u=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),p=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),c=o.parentElement.parentElement.querySelector('input[type="file"]'),d=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(c),i&&u)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&p.length){let m=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,y=Array.from(p).map(h=>{let k=(document.querySelector(`label[for="${h.id}"]`)||h.nextElementSibling)?.textContent?.trim();return{value:h.value,label:k||h.value}}),g=y.map(h=>h.label);return{type:"radio",labelText:m,errorMsgText:s,options:g,optionsData:y}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),y=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(h=>h.value).filter(h=>h!=="Select an option");return{type:"select",labelText:y,errorMsgText:s,options:g}}else if(c){let m=o.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:m}}else{if(d)return{type:"datePicker",errorMsgText:s};{let m=i?i.querySelector("span:nth-of-type(2)")?.textContent.trim():null,y=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(y.length>0){let g=Array.from(y).map(h=>h.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:s,options:g}}else return null}}}return null})}async function Yn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));i.value=o;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(i)}}return null},t,n)}async function Qn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('input[type="radio"]'),u=o;if(r.optionsData){let p=r.optionsData.find(f=>f.label.toLowerCase()===o.toLowerCase());p&&(u=p.value,console.log(`Radio: matched label "${o}" to value "${u}"`))}for(let p of i){let c=(document.querySelector(`label[for="${p.id}"]`)||p.nextElementSibling)?.textContent?.trim()||"";if(p.value.toLowerCase()===u.toLowerCase()||c.toLowerCase()===o.toLowerCase()){p.checked=!0;let d=new Event("change",{bubbles:!0});p.dispatchEvent(d),console.log(`Radio selected: value="${p.value}", label="${c}"`);break}}}return null},t,n)}async function zn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector("select[data-test-text-entity-list-form-select]");if(!i)return null;let u=Array.from(i.options),p=u.find(c=>c.text.toLowerCase()===o.toLowerCase())||u.find(c=>c.text.toLowerCase().includes(o.toLowerCase()));p?i.value=p.value:i.value=o;let f=new Event("change",{bubbles:!0});i.dispatchEvent(f)}return null},t,n)}async function Kn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');i.length>0&&i.forEach(u=>{if(u.nextElementSibling.textContent.trim()===o.trim()){u.checked=!0;let p=new Event("change",{bubbles:!0});u.dispatchEvent(p)}})}return null},t,n)}async function Xn(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s?.length===0)return null;let l=s[0],a=l.closest(".fb-dash-form-element"),i=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&i){async function u(p,f,c){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),y=new File([m],c,{type:"application/pdf"}),g=new DataTransfer;g.items.add(y),p.files=g.files;let h=new Event("change",{bubbles:!0});p.dispatchEvent(h)}await u(i,o,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,n)}async function Lo(e){let t=await Wn(e);if(t===null)return null;if(t?.type==="input"){let o=await Ot(t.labelText,t.errorMsgText);o=o?.trim()||o,t.answer=o,await Yn(e,t,o)}else if(t?.type==="radio"){let o=await lt(t.labelText,t.options);o=o?.trim()||o;let s=t.options||[];!s.find(a=>a.toLowerCase()===o?.toLowerCase())&&s.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${o}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),o=await lt(t.labelText,t.options),o=o?.trim()||o,s.find(i=>i.toLowerCase()===o?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${s[0]}"`),o=s[0])),t.answer=o,await Qn(e,t,o)}else if(t?.type==="select"){let o=await Re(t.labelText,t.options);o=o?.trim()||o;let s=t.options||[],l=s.find(a=>a.toLowerCase()===o?.toLowerCase());if(l)o=l;else if(s.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${o}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),o=await Re(t.labelText,t.options),o=o?.trim()||o;let a=s.find(i=>i.toLowerCase()===o?.toLowerCase());a?o=a:(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${s[0]}"`),o=s[0])}t.answer=o,await zn(e,t,o)}else if(t?.type==="checkbox"){let o=await Re(t.labelText,t.options);t.answer=o,await Kn(e,t,o)}else if(t?.type==="file"){let o=process.env.RESUME_PDF_URL;t.answer=o;let s=await fetch(o);if(!s.ok)throw new Error("Network response was not ok");let l=await s.arrayBuffer();await Xn(e,t,l)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let n=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${n}" \u2192 ${r}`),t}async function Zn(e){return await e.evaluate(async()=>{let t=[],n=document.querySelectorAll(".fb-dash-form-element");if(!n||n.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(n=r.querySelectorAll(".fb-dash-form-element"))}if(!n||n.length===0)return[];for(let r of n){let o=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),s=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),i=r.querySelector("select[data-test-text-entity-list-form-select]"),u=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),p=r.querySelector('input[type="file"]');if(o&&l&&a.length===0){let f=o.textContent.trim();t.push({type:"input",labelText:f,answer:l.value,isRequired:s,wasPreFilled:!!l.value})}else if(o&&a.length){let f=o?o.querySelector("span:nth-of-type(1)")?.textContent.trim():null,c=Array.from(a).map(m=>m.value),d=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:c,answer:d,isRequired:s,wasPreFilled:!!d})}else if(i){let f=r.querySelector('label[for="'+i.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),c=f?f.querySelector("span:nth-of-type(2)")?.textContent.trim():null,d=Array.from(i.options).map(y=>y.value).filter(y=>y!=="Select an option"),m=i.value!=="Select an option"?i.value:"";t.push({type:"select",labelText:c,options:d,answer:m,isRequired:s,wasPreFilled:!!m})}else if(u.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),c=Array.from(u).map(d=>({label:d.nextElementSibling?.textContent?.trim()||d.value,checked:d.checked}));t.push({type:"checkbox",labelText:f,options:c.map(d=>d.label),answer:c.filter(d=>d.checked).map(d=>d.label).join(", "),isRequired:s})}else if(p){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:p.value?"uploaded":"",isRequired:s})}}return t})}async function Ro(e,t,n){return await e.evaluate(async(r,o)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&i&&r===a.textContent.trim()){i.value=o;let u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r==="City"||r==="Location (city)"){let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(i)}return!0}}return!1},t,n)}async function Fo(e,t){let n=[],r=!0,o=0,s=null,l=0;for(;r;){if(o++,await ot(e))return console.log(" Daily limit reached during form navigation"),await Oo(e),{filledFields:n,formPages:o,skip:!0,dailyLimitReached:!0};let u=(await Zn(e)).filter(d=>!n.some(m=>m.labelText===d.labelText));n.push(...u);try{let d=n.find(y=>y.labelText==="City"||y.labelText==="Location (city)"),m=n.filter(y=>y.labelText!=null).find(y=>y.labelText!==null&&y.labelText.trim()!==null&&(y.labelText.trim().toLowerCase()==="cv"||y.labelText.trim().toLowerCase()==="curriculum vitae"||y.labelText.trim().toLowerCase()==="cover letter"||y.labelText.trim().toLowerCase()==="cover"));if(d&&!d.answer){let y=process.env.City;await Ro(e,d.labelText,y),d.answer=y}else if(m){let y=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==y)&&(await b(1e4),await Ro(e,m.labelText,y),m.answer=y,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}let p=null;try{p=await t(e)}catch(d){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${d.message?.slice(0,100)}`),{filledFields:n,formPages:o,skip:!0}}if(p!==null){if(p.type==="datePicker")return{filledFields:n,formPages:o,skip:!0,duplicateField:p};let d=p&&n.find(y=>y.errorMsgText&&y.labelText===p.labelText);if(d)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(p,null,2)),console.log("Previous attempt:",JSON.stringify(d,null,2)),{filledFields:n,formPages:o,skip:!0,duplicateField:p};let m=n.findIndex(y=>y.labelText===p.labelText&&!y.answer);m!==-1&&n.splice(m,1),n.push(p)}let f=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of d){let y=m.querySelectorAll("button");for(let g of y){let h=g.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return g.click(),h}}return null});f&&console.log(` Dismissed safety popup (${f})`);let c=await e.evaluate(async()=>{function d(w){let x=document.querySelector(w);if(x)return x;let I=document.querySelector("#interop-outlet")?.shadowRoot;return I?I.querySelector(w):null}function m(w){let x=document.querySelectorAll(w),I=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...x||[],...I||[]]}let y=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||m("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),h=d('button[aria-label="Submit application"]'),S=async()=>{let w=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(x=>x.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},k=()=>{let w=m("button").find(x=>x.innerText?.trim()==="Review");w&&w.click()};return y?(await S(),{type:"next"}):g?(await k(),{type:"review"}):h?{type:"submit"}:{type:null}});if(c==null)return{filledFields:n,formPages:o,skip:!0};if(c.type&&console.log(` \u2192 ${c.type}`),c.type===null){let d=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let y of m){let g=y.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let h of g){let S=h.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let k of h.querySelectorAll("button")){let w=k.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return k.click(),w}}}return null});if(d)return console.log(` Dismissed stale popup (${d}) \u2014 need to re-open Easy Apply`),await b(1500),{filledFields:n,formPages:o,skip:!1,stalePopupDismissed:!0};if(l===0){let m=await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],h=[];for(let S of y){for(let w of S.querySelectorAll("button")){let x=w.innerText?.trim();x&&x.length<60&&g.push(x)}let k=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');k&&h.push(k.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:h.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(c.type==="submit")return{filledFields:n,formPages:o,skip:!1};if(p===null&&c.type===s?l++:l=0,s=c.type,l>=5){let d=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),y=[],g=[];for(let h of m){for(let S of h.querySelectorAll(".artdeco-inline-feedback__message"))y.push(S.textContent?.trim()?.slice(0,60));for(let S of h.querySelectorAll(".fb-dash-form-element")){let k=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=S.querySelector("input, select, textarea"),x=!!S.querySelector(".artdeco-inline-feedback__message");k&&(x||w&&!w.value)&&g.push({label:k.slice(0,40),hasError:x,value:w?.value?.slice(0,20)||""})}}return{errors:y,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${c.type}" for ${l} iterations \u2014 form not progressing.`),d.errors.length&&console.error(` Visible errors: ${JSON.stringify(d.errors)}`),d.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(d.emptyRequired)}`),console.error(" Skipping job."),{filledFields:n,formPages:o,skip:!0,duplicateField:{labelText:`stuck_on_${c.type}`}}}await b(1500),r=!0}return{filledFields:n,formPages:o,skip:!1}}async function Mo(e){try{await e.evaluate(()=>{let t=document.getElementById("follow-company-checkbox");t?(t.checked=!1,t.dispatchEvent(new Event("change",{bubbles:!0}))):console.warn("Unfollow checkbox not found.")})}catch(t){console.error("Error in unfollowJobCheckbox:",t)}}async function er(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let n=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=n?.asElement?.()||null,t||await n.dispose().catch(()=>{})}t&&await t.click()}async function tr(e){try{let t=await e.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of n){for(let s of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(s.innerText?.trim()==="Done")return s.click(),"Done";let o=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let s of o){let l=s.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of s.querySelectorAll("button")){let i=a.innerText?.trim();if(i==="Not now"||i==="Dismiss")return a.click(),i}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await b(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function tt(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await b(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function Lt(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await b(500))}catch{console.log("No discard confirmation needed")}}async function Uo(e,t){let n=[],r=t._fromQueue;try{v.attempted++,console.log(`
|
|
26
|
-
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let o=t.id?.match(/\d+/)?.[0];if(o&&
|
|
24
|
+
`)}`;try{await te.addMessage(l,s)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Nn=Mn(import.meta.url),On=X.dirname(X.dirname(Nn)),Ft=process.env.DATA_DIR?X.resolve(process.env.DATA_DIR,"collected-profiles"):X.join(On,"collected-profiles"),Mt=X.join(Ft,"run-log.json");function Un(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";H.writeFileSync(r,n);for(let o=0;o<3;o++)try{H.renameSync(r,e);return}catch(i){if(o<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function jo(){try{if(!H.existsSync(Mt))return{runs:[]};let e=JSON.parse(H.readFileSync(Mt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Io(e){H.existsSync(Ft)||H.mkdirSync(Ft,{recursive:!0});try{Un(Mt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Do(e,t="default"){let n=jo();for(let l of n.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,o={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(o);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>i),Io(n),{script:e,mode:t,startTime:r.getTime(),runIndex:n.runs.length-1}}function qo(e,t,n=null,r=null){if(!e)return;let o=null;try{let l=jo(),a=l.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=r,o=a.duration;else{let s=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=r,o=s.duration)}Io(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";To({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:r,duration:o??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import Lo from"fs";import Bn from"path";var Jn="cookies.json";function Gn(){let e=process.env.ILML_SCOPE_DIR;return e?Bn.join(e,"plugins-state","linkedin","cookies.json"):Jn}function Nt(){let e=Gn();if(!Lo.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Lo.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}async function it(e,t,n="op"){let r,o=new Promise((i,l)=>{r=setTimeout(()=>l(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,o])}finally{clearTimeout(r)}}function ge(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let n=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(n)||/Target closed/i.test(n)||/Session closed/i.test(n)||/Connection closed/i.test(n)||/Most likely the page has been closed/i.test(n)||/Navigating frame was detached/i.test(n)||/Protocol error.*timed out/i.test(n)}async function Ro(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await it(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function Po(e,{timeoutMs:t=3e3,retryDelayMs:n=5e3}={}){return await Ro(e,t)?!0:(await b(n),await Ro(e,t))}async function Fo(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await it(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function Mo(e,t,{returnUrl:n,gotoTimeoutMs:r=6e4,cookiesProvider:o=null,setupPage:i=null}={}){try{await it(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let l=await e.newPage();if(i)try{await i(l)}catch{}if(o)try{let a=o();Array.isArray(a)&&a.length>0&&await l.setCookie(...a)}catch{}if(n){await l.goto(n,{waitUntil:"domcontentloaded",timeout:r});let a=l.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return l}async function No(e,{launchFn:t,returnUrl:n,gotoTimeoutMs:r=6e4,cookiesProvider:o=null,setupPage:i=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");try{await it(e.close(),5e3,"oldBrowser.close")}catch{}let l=await t(),a=await l.newPage();if(i)try{await i(a)}catch{}if(o)try{let s=o();Array.isArray(s)&&s.length>0&&await a.setCookie(...s)}catch{}if(n){await a.goto(n,{waitUntil:"domcontentloaded",timeout:r});let s=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(s))throw new Error(`Session expired after browser restart \u2014 landed on ${s}. Run: ilml linkedin login`)}return{browser:l,page:a}}await Ao();var dt=0,Vn=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Wn=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Yn=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Ot=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],lt=-1;async function Qn(){if(lt===-1){let e=await ue("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${e}`),!/^\d+$/.test(e.trim()))throw new Error(`Last Counter is not a number, got: "${e}"`);lt=Ht(e)+1,console.log(`lastIndex initialized as: ${lt}`)}return lt++}var zo=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${zo}`);var zn=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Ne={};function Ko(e){return zn.find(t=>t.match(e))||null}function Kn(e){return Ne[e]=(Ne[e]||0)+1,Ne[e]}function Uo(){for(let e of Object.keys(Ne))Ne[e]=0}var Ut=0;function Xn(){return Ut++,Ut>=zo?(console.log(`Max run counter reached with ${Ut}`),!1):!0}async function Zn(e){let t=await uo(e)}async function er(e){return po(e,{easyApplyOnly:!0})}async function tr(e){return fo(e)}async function Gt(e,t){return At(e,t)}var Bt=3,or=2;async function ct(e,t){let{searchUrl:n,launchFn:r,setupPage:o,cookiesProvider:i}=e.recoveryCtx,l=await Fo(e.browser);if(!l||e._pageRecoveryStreak>=Bt){if(S.browserRestarts>=or)throw new Error(`CDP unrecoverable: ${S.browserRestarts} browser restart${S.browserRestarts===1?"":"s"} and ${S.cdpRecoveries} page recover${S.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let s=l?`${Bt} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${s}). Reason: ${t}`);let c=await No(e.browser,{launchFn:r,setupPage:o,cookiesProvider:i,returnUrl:n});e.browser=c.browser,e.page=c.page,e._pageRecoveryStreak=0,S.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${S.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${Bt}). Reason: ${t}`),e.page=await Mo(e.browser,e.page,{returnUrl:n,cookiesProvider:i,setupPage:o}),e._pageRecoveryStreak+=1,S.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${S.cdpRecoveries}).`)}async function nr(e){let{searchUrl:t}=e.recoveryCtx,n=3;e._pageRecoveryStreak=e._pageRecoveryStreak||0;for(let r=1;r<=n;r++){if(r>1){console.log(`
|
|
25
|
+
--- Pass ${r}/${n}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(a){if(ge(a))await ct(e,`pass-${r} navigation: ${a.message?.slice(0,80)}`);else throw a}await b(3e3)}let o=S.submitted,i=!0,l=!0;for(;i&&l;){if(!await Po(e.page)){await ct(e,"liveness probe failed twice");continue}try{await Gt(e.page,t);let s=await mr(e.page,Zo,Zn);l=s.keepGoing;let c=s.jobsDone;if(console.log("keepGoing",l),console.log("pageDone"),console.log(c.length),!l)break;i=await tr(e.page),e._pageRecoveryStreak=0}catch(s){if(!ge(s))throw s;await ct(e,`mid-iteration: ${s.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!l)break;if(S.submitted===o){console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${S.submitted-o} new jobs in pass ${r}.`)}}async function Bo(e,t,n){let r=process.env.LINKEDIN_SEARCH_URL;return mo(e,t,n,r)}async function Jo(e,t){let n=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${n}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${n} from list`)):console.log(` Dismiss button not found for ${n}`)}async function rr(e,t){try{let n=await yo(e);if(n&&n.profileUrl){n.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},Ce("recruiters-from-jobs",n)?(dt++,console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F3AF} RECRUITER FOUND \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Name: ${n.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${n.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(dt).padEnd(23)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")):console.log(` \u2139 Recruiter already saved: ${n.name}`),Ae(n.profileUrl,{name:n.name,source:"recruiters-from-jobs"});let o=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(o){Qe(n.profileUrl,o),he(n.profileUrl,{source:"job-apply",jobId:o,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let i=n.fromJob?.companyUrl;i&&ot(i,{recruiterUrl:n.profileUrl,jobId:o})}return n}else console.log(" \u26AA No recruiter found on this job page");return null}catch(n){return console.error("Error extracting recruiter:",n.message),null}}async function ut(e){return await e.evaluate(()=>{let t=document.body.innerText||"",n=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+n;return r.includes("We limit daily submissions")||r.includes("We limit Easy Apply submissions")||r.includes("Easy Apply limit")||r.includes("reached today")||r.includes("apply tomorrow")})}async function Xo(e){try{let t=await e.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let o of n){let i=o.querySelectorAll("button");for(let l of i){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function Go(e){await e.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let s of a.querySelectorAll("button")){let c=s.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){s.click();return}}});let t=Date.now(),n=3e3,r=null;for(;!r&&Date.now()-t<n;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let l=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let s of a){let c=s.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return s}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let o=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${o>400?` (waited ${o}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await ut(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await b(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await b(2e3)}}else await r.click(),await b(1500);return await ut(e)?(await Xo(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await ut(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function sr(e){return await e.evaluate(async()=>{function t(){let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length>0)return s;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(s=c.querySelectorAll(".artdeco-inline-feedback__message")),s}let n=3e3,r=t();if(r?.length===0&&(await new Promise(s=>setTimeout(s,n)),r=t()),r?.length===0)return null;let o=r[0];console.log("errorMsg"),console.log(o);let i=o?.textContent.trim(),l=o.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=o.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(l),a||l){console.log("parentElement"),console.log(a);let s=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),c=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),p=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),u=o.parentElement.parentElement.querySelector('input[type="file"]'),d=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(u),s&&c)return{type:"input",labelText:s.textContent.trim(),errorMsgText:i};if(s&&p.length){let m=s?s.querySelector("span:nth-of-type(1)")?.textContent.trim():null,y=Array.from(p).map(h=>{let k=(document.querySelector(`label[for="${h.id}"]`)||h.nextElementSibling)?.textContent?.trim();return{value:h.value,label:k||h.value}}),g=y.map(h=>h.label);return{type:"radio",labelText:m,errorMsgText:i,options:g,optionsData:y}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),y=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(h=>h.value).filter(h=>h!=="Select an option");return{type:"select",labelText:y,errorMsgText:i,options:g}}else if(u){let m=o.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:i,labelText:m}}else{if(d)return{type:"datePicker",errorMsgText:i};{let m=s?s.querySelector("span:nth-of-type(2)")?.textContent.trim():null,y=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(y.length>0){let g=Array.from(y).map(h=>h.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:i,options:g}}else return null}}}return null})}async function ir(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let s=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));s.value=o;let c=new Event("input",{bubbles:!0});if(s.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(s)}}return null},t,n)}async function lr(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let s=a.querySelectorAll('input[type="radio"]'),c=o;if(r.optionsData){let p=r.optionsData.find(f=>f.label.toLowerCase()===o.toLowerCase());p&&(c=p.value,console.log(`Radio: matched label "${o}" to value "${c}"`))}for(let p of s){let u=(document.querySelector(`label[for="${p.id}"]`)||p.nextElementSibling)?.textContent?.trim()||"";if(p.value.toLowerCase()===c.toLowerCase()||u.toLowerCase()===o.toLowerCase()){p.checked=!0;let d=new Event("change",{bubbles:!0});p.dispatchEvent(d),console.log(`Radio selected: value="${p.value}", label="${u}"`);break}}}return null},t,n)}async function ar(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let s=a.querySelector("select[data-test-text-entity-list-form-select]");if(!s)return null;let c=Array.from(s.options),p=c.find(u=>u.text.toLowerCase()===o.toLowerCase())||c.find(u=>u.text.toLowerCase().includes(o.toLowerCase()));p?s.value=p.value:s.value=o;let f=new Event("change",{bubbles:!0});s.dispatchEvent(f)}return null},t,n)}async function cr(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let s=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');s.length>0&&s.forEach(c=>{if(c.nextElementSibling.textContent.trim()===o.trim()){c.checked=!0;let p=new Event("change",{bubbles:!0});c.dispatchEvent(p)}})}return null},t,n)}async function ur(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i?.length===0)return null;let l=i[0],a=l.closest(".fb-dash-form-element"),s=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&s){async function c(p,f,u){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),y=new File([m],u,{type:"application/pdf"}),g=new DataTransfer;g.items.add(y),p.files=g.files;let h=new Event("change",{bubbles:!0});p.dispatchEvent(h)}await c(s,o,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,n)}async function Ho(e){let t=await sr(e);if(t===null)return null;if(t?.type==="input"){let o=await Wt(t.labelText,t.errorMsgText);o=o?.trim()||o,t.answer=o,await ir(e,t,o)}else if(t?.type==="radio"){let o=await mt(t.labelText,t.options);o=o?.trim()||o;let i=t.options||[];!i.find(a=>a.toLowerCase()===o?.toLowerCase())&&i.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${o}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),o=await mt(t.labelText,t.options),o=o?.trim()||o,i.find(s=>s.toLowerCase()===o?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${i[0]}"`),o=i[0])),t.answer=o,await lr(e,t,o)}else if(t?.type==="select"){let o=await Ue(t.labelText,t.options);o=o?.trim()||o;let i=t.options||[],l=i.find(a=>a.toLowerCase()===o?.toLowerCase());if(l)o=l;else if(i.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${o}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),o=await Ue(t.labelText,t.options),o=o?.trim()||o;let a=i.find(s=>s.toLowerCase()===o?.toLowerCase());a?o=a:(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${i[0]}"`),o=i[0])}t.answer=o,await ar(e,t,o)}else if(t?.type==="checkbox"){let o=await Ue(t.labelText,t.options);t.answer=o,await cr(e,t,o)}else if(t?.type==="file"){let o=process.env.RESUME_PDF_URL;t.answer=o;let i=await fetch(o);if(!i.ok)throw new Error("Network response was not ok");let l=await i.arrayBuffer();await ur(e,t,l)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let n=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${n}" \u2192 ${r}`),t}async function dr(e){return await e.evaluate(async()=>{let t=[],n=document.querySelectorAll(".fb-dash-form-element");if(!n||n.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(n=r.querySelectorAll(".fb-dash-form-element"))}if(!n||n.length===0)return[];for(let r of n){let o=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),s=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),p=r.querySelector('input[type="file"]');if(o&&l&&a.length===0){let f=o.textContent.trim();t.push({type:"input",labelText:f,answer:l.value,isRequired:i,wasPreFilled:!!l.value})}else if(o&&a.length){let f=o?o.querySelector("span:nth-of-type(1)")?.textContent.trim():null,u=Array.from(a).map(m=>m.value),d=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:u,answer:d,isRequired:i,wasPreFilled:!!d})}else if(s){let f=r.querySelector('label[for="'+s.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),u=f?f.querySelector("span:nth-of-type(2)")?.textContent.trim():null,d=Array.from(s.options).map(y=>y.value).filter(y=>y!=="Select an option"),m=s.value!=="Select an option"?s.value:"";t.push({type:"select",labelText:u,options:d,answer:m,isRequired:i,wasPreFilled:!!m})}else if(c.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),u=Array.from(c).map(d=>({label:d.nextElementSibling?.textContent?.trim()||d.value,checked:d.checked}));t.push({type:"checkbox",labelText:f,options:u.map(d=>d.label),answer:u.filter(d=>d.checked).map(d=>d.label).join(", "),isRequired:i})}else if(p){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:p.value?"uploaded":"",isRequired:i})}}return t})}async function Vo(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let l of i){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),s=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&s&&r===a.textContent.trim()){s.value=o;let c=new Event("input",{bubbles:!0});if(s.dispatchEvent(c),r==="City"||r==="Location (city)"){let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(s)}return!0}}return!1},t,n)}async function Wo(e,t){let n=[],r=!0,o=0,i=null,l=0;for(;r;){if(o++,await ut(e))return console.log(" Daily limit reached during form navigation"),await Xo(e),{filledFields:n,formPages:o,skip:!0,dailyLimitReached:!0};let c=(await dr(e)).filter(d=>!n.some(m=>m.labelText===d.labelText));n.push(...c);try{let d=n.find(y=>y.labelText==="City"||y.labelText==="Location (city)"),m=n.filter(y=>y.labelText!=null).find(y=>y.labelText!==null&&y.labelText.trim()!==null&&(y.labelText.trim().toLowerCase()==="cv"||y.labelText.trim().toLowerCase()==="curriculum vitae"||y.labelText.trim().toLowerCase()==="cover letter"||y.labelText.trim().toLowerCase()==="cover"));if(d&&!d.answer){let y=process.env.City;await Vo(e,d.labelText,y),d.answer=y}else if(m){let y=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==y)&&(await b(1e4),await Vo(e,m.labelText,y),m.answer=y,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}let p=null;try{p=await t(e)}catch(d){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${d.message?.slice(0,100)}`),{filledFields:n,formPages:o,skip:!0}}if(p!==null){if(p.type==="datePicker")return{filledFields:n,formPages:o,skip:!0,duplicateField:p};let d=p&&n.find(y=>y.errorMsgText&&y.labelText===p.labelText);if(d)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(p,null,2)),console.log("Previous attempt:",JSON.stringify(d,null,2)),{filledFields:n,formPages:o,skip:!0,duplicateField:p};let m=n.findIndex(y=>y.labelText===p.labelText&&!y.answer);m!==-1&&n.splice(m,1),n.push(p)}let f=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of d){let y=m.querySelectorAll("button");for(let g of y){let h=g.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return g.click(),h}}return null});f&&console.log(` Dismissed safety popup (${f})`);let u=await e.evaluate(async()=>{function d(w){let x=document.querySelector(w);if(x)return x;let I=document.querySelector("#interop-outlet")?.shadowRoot;return I?I.querySelector(w):null}function m(w){let x=document.querySelectorAll(w),I=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...x||[],...I||[]]}let y=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||m("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),h=d('button[aria-label="Submit application"]'),v=async()=>{let w=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(x=>x.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},k=()=>{let w=m("button").find(x=>x.innerText?.trim()==="Review");w&&w.click()};return y?(await v(),{type:"next"}):g?(await k(),{type:"review"}):h?{type:"submit"}:{type:null}});if(u==null)return{filledFields:n,formPages:o,skip:!0};if(u.type&&console.log(` \u2192 ${u.type}`),u.type===null){let d=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let y of m){let g=y.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let h of g){let v=h.innerText||"";if(v.includes("application was sent")||v.includes("resume into a profile")||v.includes("Application submitted")||v.includes("Next best action"))for(let k of h.querySelectorAll("button")){let w=k.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return k.click(),w}}}return null});if(d)return console.log(` Dismissed stale popup (${d}) \u2014 need to re-open Easy Apply`),await b(1500),{filledFields:n,formPages:o,skip:!1,stalePopupDismissed:!0};if(l===0){let m=await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],h=[];for(let v of y){for(let w of v.querySelectorAll("button")){let x=w.innerText?.trim();x&&x.length<60&&g.push(x)}let k=v.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');k&&h.push(k.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:h.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(u.type==="submit")return{filledFields:n,formPages:o,skip:!1};if(p===null&&u.type===i?l++:l=0,i=u.type,l>=5){let d=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),y=[],g=[];for(let h of m){for(let v of h.querySelectorAll(".artdeco-inline-feedback__message"))y.push(v.textContent?.trim()?.slice(0,60));for(let v of h.querySelectorAll(".fb-dash-form-element")){let k=v.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=v.querySelector("input, select, textarea"),x=!!v.querySelector(".artdeco-inline-feedback__message");k&&(x||w&&!w.value)&&g.push({label:k.slice(0,40),hasError:x,value:w?.value?.slice(0,20)||""})}}return{errors:y,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${u.type}" for ${l} iterations \u2014 form not progressing.`),d.errors.length&&console.error(` Visible errors: ${JSON.stringify(d.errors)}`),d.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(d.emptyRequired)}`),console.error(" Skipping job."),{filledFields:n,formPages:o,skip:!0,duplicateField:{labelText:`stuck_on_${u.type}`}}}await b(1500),r=!0}return{filledFields:n,formPages:o,skip:!1}}async function Yo(e){try{await e.evaluate(()=>{let t=document.getElementById("follow-company-checkbox");t?(t.checked=!1,t.dispatchEvent(new Event("change",{bubbles:!0}))):console.warn("Unfollow checkbox not found.")})}catch(t){console.error("Error in unfollowJobCheckbox:",t)}}async function pr(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let n=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=n?.asElement?.()||null,t||await n.dispose().catch(()=>{})}t&&await t.click()}async function fr(e){try{let t=await e.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of n){for(let i of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(i.innerText?.trim()==="Done")return i.click(),"Done";let o=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let i of o){let l=i.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of i.querySelectorAll("button")){let s=a.innerText?.trim();if(s==="Not now"||s==="Dismiss")return a.click(),s}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await b(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function at(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await b(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function Jt(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await b(500))}catch{console.log("No discard confirmation needed")}}async function Zo(e,t){let n=[],r=t._fromQueue;try{S.attempted++,console.log(`
|
|
26
|
+
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let o=t.id?.match(/\d+/)?.[0];if(o&&Dt(o)?.status==="applied")return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let i=null;if(!r){let u=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name")?.innerText?.trim()?.replace(/\s+/g," ")?.toLowerCase()||""),d=(t.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),m=u.split(" ")[0],y=d.split(" ")[0];if(m&&y&&!u.includes(y)&&!d.includes(m))return S.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${u}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let h=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!h)return!1;let v=h.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(v)||v.includes("Application submitted")}))return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),o&&ae(o,"applied",{source:"detected"}),{keepGoing:!0};try{i=await ho(e)}catch{}}let l=await Go(e);if(l.dailyLimitReached){console.log(`
|
|
27
27
|
========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
|
|
28
|
-
`);let
|
|
28
|
+
`);let u=de("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${u.total}`),console.log(` - This session: ${dt}`),console.log(` - Unprocessed: ${u.unprocessed}`),S.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:u}}if(!l.clicked)return S.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await Yo(e);let a=await Qn();console.log(`Applying for job: ${t.id}`);let s=`### Job Information
|
|
29
29
|
- **Counter:** ${a}
|
|
30
30
|
- **Job Title:** ${t.jobTitle}
|
|
31
31
|
- **Company:** ${t.companyName}
|
|
32
32
|
- **Location:** ${t.location}
|
|
33
33
|
- **Salary:** ${t.salary}
|
|
34
|
-
- **Job URL:** ${t.href}`,
|
|
35
|
-
Closing browser...`);try{await n.close()}catch{}process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);let
|
|
36
|
-
\u{1F4C2} Existing recruiters for today: ${
|
|
37
|
-
`),await b(2e3);let
|
|
34
|
+
- **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await te.addMessage(c,s,{lifebot:Oo.off});let p=await ue("Should I apply for this job? Answer only 'yes' or 'no'!!");if(Uo(),console.log(`Should I apply for ${t.jobTitle} ?? `+p),p.toLowerCase()==="no"){S.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await at(e),await Jt(e),await Jo(e,t.id);let u=t.id?.match(/\d+/)?.[0];return be({jobId:u,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),ae(u,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let f=await Wo(e,Ho);if(f.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await Go(e)).clicked?f=await Wo(e,Ho):(console.log(" pressApplyButton failed on retry"),f={filledFields:[],formPages:0,skip:!0,duplicateField:{labelText:"stale_popup_retry_failed"}})),console.log(`processNavigation: pages=${f.formPages}, fields=${f.filledFields?.length||0}, skip=${f.skip}${f.dailyLimitReached?", DAILY LIMIT":""}`),f.dailyLimitReached)return console.log(" Daily limit reached \u2014 stopping"),await at(e),{keepGoing:!1,dailyLimitReached:!0};if(f.skip){if(await at(e),await Jt(e),f.duplicateField){await Jo(e,t.id);let u=process.env.NODE_EASY_APPLY_ERRORS;await te.addMessage(u,`${t.href} failed at label ${f.duplicateField?.labelText}`,{lifebot:Oo.off})}S.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${f.duplicateField?.labelText||"form error"}`),be({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"failed",formPages:f.formPages,failedField:f.duplicateField?.labelText||null,questions:f.filledFields||[]})}else{n=f.filledFields,n.length,await Yo(e),await pr(e),await b(2e3),await fr(e),S.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${f.formPages} pages, ${n.length} fields)`);let u=t.id?.match(/\d+/)?.[0];if(u&&(Ye(u,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),jt(u,{title:t.jobTitle,company:i?.companyName||t.companyName,companyUrl:i?.companyUrl,location:t.location,salary:t.salary,url:t.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:i?.description,techStack:i?.techStack,jobTags:i?.jobTags,seniority:i?.seniority,employmentType:i?.employmentType,industries:i?.industries,jobFunction:i?.jobFunction,postedTime:i?.postedTime,applicantCount:i?.applicantCount,companySize:i?.companySize,workplaceType:i?.workplaceType,contractType:i?.contractType,aboutCompany:i?.aboutCompany}),ae(u,"applied",{source:"easy-apply"}),i?.companyUrl&&ot(i.companyUrl,{name:i.companyName||t.companyName,about:i.aboutCompany,size:i.companySize,industries:i.industries,jobId:u})),await rr(e,t),be({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:f.formPages,questions:n}),!Xn())return{keepGoing:!1}}}catch(o){if(ge(o))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(o.message||"").slice(0,100)}`),o;console.log(o);let i=Ko(o);if(!i)return console.log(`\u274C Unknown error \u2014 stopping: ${(o.message||"").slice(0,120)}`),{keepGoing:!1};if(i.severity==="fatal")return console.log(`\u274C [${i.label}] Fatal \u2014 stopping: ${(o.message||"").slice(0,120)}`),i.instructions&&console.log(` \u2192 ${i.instructions}`),i.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":i.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin"),{keepGoing:!1};let l=Kn(i.label);if(console.log(`\u26A0 [${i.label}] on "${t.jobTitle}" (${l}/${i.maxConsecutive} consecutive): ${(o.message||"").slice(0,120)}`),i.cleanup==="popup"){try{await at(e)}catch{}try{await Jt(e)}catch{}}return l>=i.maxConsecutive?(console.log(`\u274C [${i.label}] ${i.maxConsecutive} consecutive \u2014 stopping.`),{keepGoing:!1}):(i.cooldownMs&&await b(i.cooldownMs),{keepGoing:!0})}return Uo(),{keepGoing:!0}}async function mr(e,t,n){let r=process.env.LINKEDIN_SEARCH_URL,o=[],i=0;for(;;){await Gt(e,r)&&(await B(e),await b(2e3)),await n(e);let a=await er(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(i++,i>3){console.log(" Too many recovery attempts \u2014 LinkedIn keeps redirecting. Stopping.");break}console.log(` No jobs found but not on /jobs/ page \u2014 recovery attempt ${i}/3...`),await Gt(e,r);continue}break}if(i=0,o.length===0){o=a;let{keepGoing:s}=await Bo(e,a,t);if(!s)return{keepGoing:!1,jobsDone:o}}else{let s=a.filter(p=>!o.some(f=>f.id===p.id));if(console.log(` New jobs on page: ${s.length} (page: ${a.length}, total seen: ${o.length})`),s.length===0)break;let{keepGoing:c}=await Bo(e,s,t);if(o=[...o,...s],!c)return{keepGoing:!1,jobsDone:o}}}return console.log(` All jobs processed. Total: ${o.length}`),{keepGoing:!0,jobsDone:o}}var S={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1,cdpRecoveries:0,browserRestarts:0,fatalAuthExpired:null};(async()=>{let e=process.argv.find(s=>s.startsWith("--job-urls=")),t=Do("apply",e?"queue":"search"),n=null,r=null,o=[],i=async()=>Hn.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),l=async s=>{await s.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>Nt();try{n=await i();let s=async()=>{console.log(`
|
|
35
|
+
Closing browser...`);try{await n.close()}catch{}process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);let c=await n.newPage();await l(c);let p=Nt();await c.setCookie(...p);let f=process.argv.find(C=>C.startsWith("--job-urls=")),u=f?f.split("=").slice(1).join("=").replace(/^@/,""):null,d=process.env.LINKEDIN_SEARCH_URL,m=u?"https://www.linkedin.com/feed/":d;try{await c.goto(m,{waitUntil:"domcontentloaded",timeout:6e4})}catch(C){console.error("\u274C Navigation error:",C.message),console.log("Trying to continue anyway..."),await b(5e3)}let y=c.url();if(y.includes("/login")||y.includes("/checkpoint"))throw new Error("Not logged in \u2014 cookies expired, run: npm run login");console.log("\u2713 \u0417\u0430\u043B\u043E\u0433\u0438\u043D\u0435\u043D\u044B \u043D\u0430 LinkedIn!");let g=de("recruiters-from-jobs");g.total>0&&console.log(`
|
|
36
|
+
\u{1F4C2} Existing recruiters for today: ${g.total} (${g.unprocessed} unprocessed)
|
|
37
|
+
`),await b(2e3);let h={page:c,browser:n,recoveryCtx:{searchUrl:d,launchFn:i,setupPage:l,cookiesProvider:a}},v=!1;if(u)try{let C=JSON.parse(Qo.readFileSync(u,"utf-8"));console.log(`
|
|
38
38
|
\u{1F4CB} Queue mode: ${C.length} jobs from ${u}
|
|
39
|
-
`);for(let
|
|
40
|
-
[${
|
|
41
|
-
Queue complete. ${
|
|
42
|
-
Queue done. Continuing with standard search...`);try{await
|
|
43
|
-
\
|
|
44
|
-
|
|
45
|
-
\
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
39
|
+
`);for(let D=0;D<C.length;D++){let _=typeof C[D]=="string"?{url:C[D]}:C[D],A=_.url,$=_.title||"Unknown",ve=_.company||"";console.log(`
|
|
40
|
+
[${D+1}/${C.length}] ${$} @ ${ve}`),console.log(` ${A}`),c=h.page,n=h.browser;try{let W=A.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await c.goto(A,{waitUntil:"domcontentloaded",timeout:6e4}),await b(8e3);let R=await c.evaluate(()=>{let ke=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:ke.includes("Application submitted"),noLongerAccepting:ke.includes("No longer accepting applications")}});if(R.alreadyApplied){console.log(" Already applied \u2014 skipping"),S.alreadyApplied++,ae(W,"applied",{applyMethod:"detected"});continue}if(R.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),S.expired++,ae(W,"expired",{reason:"no_longer_accepting"});continue}if(!R.hasApply){console.log(" No Easy Apply button \u2014 skipping"),S.noApplyButton++;continue}let Y={id:`/jobs/view/${W}/`,href:A,jobTitle:$,companyName:ve,location:_.location||"",salary:_.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let ee=await Zo(c,Y);if(console.log(` Result: keepGoing=${ee.keepGoing}, reason=${ee.dailyLimitReached?"daily_limit":"ok"}`),!ee.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),v=!0;break}}catch(W){if(ge(W))try{await ct(h,`queue job ${D+1}: ${W.message?.slice(0,80)}`),c=h.page,n=h.browser}catch(R){console.error(`\u274C Queue mode: CDP recovery failed: ${R.message}`),console.error(" Aborting queue, falling back to standard search if possible.");break}else{let R=Ko(W);if(R?.severity==="fatal"){console.error(`\u274C [${R.label}] Fatal \u2014 stopping queue: ${(W.message||"").slice(0,120)}`),R.instructions&&console.error(` \u2192 ${R.instructions}`),R.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":R.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin");break}console.error(` Error: ${W.message?.slice(0,80)}`)}}}console.log(`
|
|
41
|
+
Queue complete. ${v?"Daily limit hit.":"Continuing to search..."}`)}catch(C){console.error(`Failed to read job URLs file: ${C.message}`)}if(!v){if(u){console.log(`
|
|
42
|
+
Queue done. Continuing with standard search...`);try{await c.goto(d,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3)}catch(C){console.error(" Navigation to search failed:",C.message)}}h.page=c,h.browser=n;try{await nr(h)}catch(C){ge(C)||/CDP unrecoverable/.test(C.message||"")?(console.error(`
|
|
43
|
+
\u274C Apply phase ended: CDP channel could not be recovered after ${S.cdpRecoveries} page recoveries and ${S.browserRestarts} browser restarts.`),console.error(` Last error: ${C.message}`)):/Session expired/i.test(C.message||"")?(console.error(`
|
|
44
|
+
\u274C Apply phase ended: ${C.message}`),r=C):console.error(`
|
|
45
|
+
\u26A0 Apply phase crashed: ${C.message}`)}c=h.page,n=h.browser}let k=S.submitted+S.skippedByLifebot+S.failed+S.mismatch+S.alreadyApplied+S.expired+S.noApplyButton,w=S.attempted-k,x=de("recruiters-from-jobs");o.push(`Jobs attempted: ${S.attempted}`),o.push(`Successfully applied: ${S.submitted}`),o.push(`Skipped by Lifebot: ${S.skippedByLifebot}`),o.push(`Failed (form errors): ${S.failed}`),S.mismatch>0&&o.push(`Mismatch (wrong panel): ${S.mismatch}`),S.alreadyApplied>0&&o.push(`Already applied: ${S.alreadyApplied}`),S.expired>0&&o.push(`Expired (closed): ${S.expired}`),S.noApplyButton>0&&o.push(`No Apply button: ${S.noApplyButton}`),w>0&&o.push(`Unaccounted: ${w}`),o.push(`Daily limit reached: ${S.dailyLimitHit?"Yes":"No"}`),S.cdpRecoveries>0&&o.push(`Page recoveries (CDP): ${S.cdpRecoveries}`),S.browserRestarts>0&&o.push(`Browser restarts: ${S.browserRestarts}`),o.push(`Recruiters found: ${dt}`),o.push(`Recruiters total: ${x.total} (${x.unprocessed} unprocessed)`),console.log(`
|
|
46
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let C of o)console.log(` ${C}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let L=!!n&&n.isConnected?.()!==!1?S.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":S.fatalAuthExpired==="ilml"?"iLiveMyLife token expired (run: ilml login)":null:"browser is not in a usable state",V=!L;V||(console.log(`
|
|
47
|
+
\u26A0 Skipping recruiter funnel \u2014 ${L}.`),console.log(` ${x.unprocessed} recruiters saved for next run.`),o.push(`Funnel: skipped (${L})`));let{markProfileProcessed:we}=await Promise.resolve().then(()=>(bt(),Kt)),{canSendConnection:U,getQuotaStatus:Se}=await Promise.resolve().then(()=>(je(),$t)),Z=()=>({message:Yn,useCustomMessage:Vn,maxConnections:Wn,excludeLocations:Ot,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(C,D,_)=>{we("recruiters-from-jobs",C.profileUrl,{status:_.reason,connectionSent:_.connectionSent,withCustomMessage:_.withCustomMessage,message:_.messageSent,method:_.method,reason:_.reason,error:_.error,profileInfo:_.profileInfo},C._fromDate||null)}});if(V&&x.unprocessed>0){console.log(`
|
|
48
|
+
--- Funnel: today's recruiters (${x.unprocessed}) ---`),Ot.length>0&&console.log(` Excluding locations: ${Ot.join(", ")}`);let C=Je("recruiters-from-jobs");await Et(c,C,Z())}let Oe=U();if(V&&Oe.allowed){let C=Ge("recruiters-from-jobs"),D=new Date().toISOString().split("T")[0],_=C.filter(A=>A._fromDate!==D);if(_.length>0){let A=Se();console.log(`
|
|
49
|
+
--- Funnel: backfill from previous days (${_.length} unprocessed) ---`),console.log(` Quota remaining: ${A.daily.remaining} today, ${A.weekly.remaining} this week`),await Et(c,_,{...Z(),maxConnections:A.daily.remaining})}}let P=Se();console.log(`
|
|
50
|
+
\u2705 Funnel done. Quota: ${P.daily.remaining}/${P.daily.max} today, ${P.weekly.remaining}/${P.weekly.max} this week`),o.push(`Funnel quota: ${P.daily.remaining}/${P.daily.max} today, ${P.weekly.remaining}/${P.weekly.max} week`),!u&&!process.argv.includes("--no-wait")&&(console.log(`
|
|
49
51
|
Press Enter to close browser...`),await new Promise(C=>{process.stdin.once("data",()=>C())}))}catch(s){r=s,console.error(`
|
|
50
|
-
\u274C Apply session ended with error: ${s.message}`),s.stack&&console.error(s.stack)}
|
|
52
|
+
\u274C Apply session ended with error: ${s.message}`),s.stack&&console.error(s.stack)}qo(t,r?"error":"success",{summaryLines:o,dailyLimitHit:S.dailyLimitHit,attempted:S.attempted,submitted:S.submitted,failed:S.failed,skippedByLifebot:S.skippedByLifebot},r?r.message:null);try{await n?.close()}catch{}r&&process.exit(1)})();
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import"dotenv/config";import*as l from"fs";import*as s from"path";import{fileURLToPath as A}from"url";var g=s.dirname(A(import.meta.url)),y=process.env.DATA_DIR?s.resolve(process.env.DATA_DIR,"collected-profiles"):s.join(g,"collected-profiles"),a={};for(let n of process.argv.slice(2)){let e=n.match(/^--([^=]+)(?:=(.*))?$/);e&&(a[e[1]]=e[2]??!0)}var h=a.group||"apiLeaders",d=a["min-seniority"]||null,v=!!a["show-all"],S=[process.env.DATA_DIR&&s.resolve(process.env.DATA_DIR,"target-companies.json"),s.join(g,"target-companies.json"),s.resolve(g,"..","target-companies.json")].filter(Boolean),C=S.find(n=>l.existsSync(n));C||(console.error(`target-companies.json not found. Tried:
|
|
2
|
+
`+S.join(`
|
|
3
|
+
`)),console.error("Set DATA_DIR and place your own target-companies.json there, or reinstall the plugin to restore the shipped default."),process.exit(1));var j=JSON.parse(l.readFileSync(C,"utf8")),u=a.companies?String(a.companies).split(",").map(n=>n.trim()).filter(Boolean):j[h]?.companies;u||(console.error(`Unknown group: ${h}. Available: ${Object.keys(j).join(", ")}`),process.exit(1));var R=JSON.parse(l.readFileSync(s.join(y,"people.json"),"utf8")),b=JSON.parse(l.readFileSync(s.join(y,"conversations.json"),"utf8")),m=new Map;for(let[n,e]of Object.entries(b))typeof e.isConnection=="boolean"&&m.set(n,{isConnection:e.isConnection,conv:e});function k(n){if(n.name&&m.has(n.name)){let e=m.get(n.name);return{is:e.isConnection,src:"A.convInbox",conv:e.conv}}return n.connectionDegree==="1st"?{is:!0,src:"B.profileScrape"}:n.connectionDegree==="2nd"||n.connectionDegree==="3rd"?{is:!1,src:"B.profileScrape"}:n.connectionStatus==="connected"?{is:!0,src:"C.botStatus"}:["sent_without_note","sent_with_note","withdrawn","rejected"].includes(n.connectionStatus)?{is:!1,src:"C.botStatus"}:{is:null,src:null}}var $={intern:0,junior:1,mid:2,senior:3,lead:4,staff:4,principal:5,director:5,vp:6};function O(n,e){if(!e)return!0;if(!n)return!1;let r=n.toLowerCase(),i=$[e.toLowerCase()];if(i==null)return!0;for(let[o,t]of Object.entries($))if(r.includes(o)&&t>=i)return!0;return!1}function T(n,e){return[n.company,n.title,e?.personContext?.title,e?.personContext?.company].filter(Boolean).join(" | ").toLowerCase()}function x(n){let e=n.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b${e}\\b`,"i")}var B=u.map(n=>({name:n,re:x(n)})),p={};for(let n of u)p[n]={connected:[],notConnected:[],unknown:[]};for(let[n,e]of Object.entries(R)){let r=e.name?b[e.name]:null,i=T(e,r);if(i)for(let{name:o,re:t}of B){if(!t.test(i))continue;if(!O(e.title||r?.personContext?.title,d))break;let c=k(e),f={name:e.name||n.slice(-40),title:e.title||r?.personContext?.title||"",company:e.company,degree:e.connectionDegree,via:c.src,convStatus:c.conv?.conversationStatus,lastMsg:c.conv?.lastMessageTime,lastBy:c.conv?.lastMessageBy,category:c.conv?.category||e.category};c.is===!0?p[o].connected.push(f):c.is===!1?p[o].notConnected.push(f):p[o].unknown.push(f);break}}var _=d?` (min-seniority=${d})`:"";console.log(`
|
|
4
|
+
\u2550\u2550 Warm-scan: ${h}${_} \u2014 ${u.length} target companies \u2550\u2550
|
|
5
|
+
`);var I=Object.entries(p).sort((n,e)=>e[1].connected.length-n[1].connected.length),w=0;for(let[n,e]of I){let r=e.connected.length+e.notConnected.length+e.unknown.length;w+=e.connected.length;let i=`${n.padEnd(18)} connected: ${e.connected.length}, other: ${e.notConnected.length+e.unknown.length}, total seen: ${r}`;if(console.log(i),e.connected.length>0)for(let t of e.connected){let c=(t.title||"").slice(0,55),f=t.convStatus?` [${t.convStatus}]`:"",D=t.lastMsg?` (${t.lastMsg.slice(0,10)})`:"";console.log(` \xB7 ${t.name.padEnd(28)} ${c}${f}${D}`)}let o=[...e.notConnected,...e.unknown];if(o.length>0&&(v||o.length<=5)){console.log(" seen but not 1st-degree:");for(let t of o.slice(0,v?o.length:5))console.log(` ${t.name.padEnd(28)} ${(t.title||"").slice(0,55)}`)}else o.length>5&&console.log(` seen but not 1st-degree: ${o.length} \u2014 add --show-all or --companies="${n}" to expand`);console.log("")}console.log(`Total 1st-degree at target companies: ${w}`);
|
package/ilml-plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "linkedin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "LinkedIn job automation: apply, scout, sync, funnel, messages",
|
|
5
5
|
"commands": {
|
|
6
6
|
"apply": { "run": "node dist/run.mjs" },
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"visit": { "run": "node dist/visit.mjs" },
|
|
16
16
|
"viewers": { "run": "node dist/viewers.mjs" },
|
|
17
17
|
"apply-queue": { "run": "node dist/applyQueue.mjs" },
|
|
18
|
+
"warm-scan": { "run": "node dist/warmScan.mjs" },
|
|
18
19
|
"daily": { "run": "node dist/daily.mjs" },
|
|
19
20
|
"login": { "run": "node dist/src/saveLoginState.mjs" }
|
|
20
21
|
},
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ilml-plugin-linkedin",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "ilml plugin:
|
|
3
|
+
"version": "1.4.0",
|
|
4
|
+
"description": "ilml plugin: pull your LinkedIn graph (connections, threads, notes) into iLiveMyLife and run inbox sync, AI-drafted replies, Easy Apply, and recruiter outreach from the terminal.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
7
7
|
"dist",
|
|
8
8
|
"ilml-plugin.json",
|
|
9
|
+
"target-companies.json",
|
|
9
10
|
"CHANGELOG.md"
|
|
10
11
|
],
|
|
11
12
|
"scripts": {
|
|
@@ -62,7 +63,13 @@
|
|
|
62
63
|
"ilml-plugin",
|
|
63
64
|
"ilivemylife",
|
|
64
65
|
"linkedin",
|
|
65
|
-
"
|
|
66
|
+
"linkedin-bot",
|
|
67
|
+
"linkedin-automation",
|
|
68
|
+
"easy-apply",
|
|
69
|
+
"job-search",
|
|
70
|
+
"inbox-sync",
|
|
71
|
+
"recruiter-outreach",
|
|
72
|
+
"ai-messaging",
|
|
66
73
|
"puppeteer"
|
|
67
74
|
],
|
|
68
75
|
"author": "Ilya Sorokin <info@ilivemylife.io> (https://ilivemylife.io)",
|
|
@@ -72,7 +79,7 @@
|
|
|
72
79
|
},
|
|
73
80
|
"homepage": "https://github.com/iLiveMyLife/linkedInJobsAutoApply#readme",
|
|
74
81
|
"dependencies": {
|
|
75
|
-
"@ilivemylife/graph-sdk": "^1.0.
|
|
82
|
+
"@ilivemylife/graph-sdk": "^1.0.18",
|
|
76
83
|
"dotenv": "^16.4.5",
|
|
77
84
|
"puppeteer": "^22.15.0",
|
|
78
85
|
"puppeteer-extra": "^3.3.6",
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiLeaders": {
|
|
3
|
+
"description": "API/AI industry leaders (original focus). Substring match, word-boundary.",
|
|
4
|
+
"companies": [
|
|
5
|
+
"Anthropic",
|
|
6
|
+
"OpenAI",
|
|
7
|
+
"Stripe",
|
|
8
|
+
"Plaid",
|
|
9
|
+
"Twilio",
|
|
10
|
+
"Mastercard",
|
|
11
|
+
"Visa",
|
|
12
|
+
"Square",
|
|
13
|
+
"Block",
|
|
14
|
+
"Ramp",
|
|
15
|
+
"Retool",
|
|
16
|
+
"Linear",
|
|
17
|
+
"Cohere",
|
|
18
|
+
"Hugging Face",
|
|
19
|
+
"Scale AI"
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
"topPaying": {
|
|
23
|
+
"description": "FAANG + tier-1 tech + top AI + high-comp fintech/SaaS — senior engineer total comp typically $300K+. Broader target when user isn't picky about domain, only about pay.",
|
|
24
|
+
"companies": [
|
|
25
|
+
"Meta",
|
|
26
|
+
"Google",
|
|
27
|
+
"Amazon",
|
|
28
|
+
"Apple",
|
|
29
|
+
"Netflix",
|
|
30
|
+
"Microsoft",
|
|
31
|
+
"Uber",
|
|
32
|
+
"Airbnb",
|
|
33
|
+
"LinkedIn",
|
|
34
|
+
"Pinterest",
|
|
35
|
+
"Anthropic",
|
|
36
|
+
"OpenAI",
|
|
37
|
+
"Cohere",
|
|
38
|
+
"Databricks",
|
|
39
|
+
"Snowflake",
|
|
40
|
+
"Hugging Face",
|
|
41
|
+
"Scale AI",
|
|
42
|
+
"Stripe",
|
|
43
|
+
"Plaid",
|
|
44
|
+
"Mastercard",
|
|
45
|
+
"Visa",
|
|
46
|
+
"Square",
|
|
47
|
+
"Block",
|
|
48
|
+
"Ramp",
|
|
49
|
+
"Datadog",
|
|
50
|
+
"MongoDB",
|
|
51
|
+
"Figma",
|
|
52
|
+
"Notion",
|
|
53
|
+
"HashiCorp",
|
|
54
|
+
"Retool",
|
|
55
|
+
"Linear"
|
|
56
|
+
]
|
|
57
|
+
}
|
|
58
|
+
}
|