ilml-plugin-linkedin 1.16.0 → 1.17.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 +3 -0
- package/dist/applyQueue.mjs +12 -12
- package/dist/connect.mjs +68 -68
- package/dist/daily.mjs +7 -7
- package/dist/enrichProfile.mjs +15 -15
- package/dist/enrichProfiles.mjs +54 -54
- package/dist/funnelRunner.mjs +60 -60
- package/dist/migrationCli.mjs +5 -5
- package/dist/profileHistory.mjs +2 -2
- package/dist/quota.mjs +11 -11
- package/dist/run.mjs +65 -65
- package/dist/scout.mjs +5 -5
- package/dist/syncAll.mjs +102 -102
- package/dist/syncConnections.mjs +9 -9
- package/dist/verifyAbout.mjs +20 -20
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +4 -4
- package/dist/visit.mjs +45 -45
- package/dist/warmScan.mjs +2 -2
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/syncAll.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var Io=Object.defineProperty;var qe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{for(var n in t)Io(e,n,{get:t[n],enumerable:!0})};function Be(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function vt(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let l=Be(n),i=new Date(t);return l?i.setHours(l.hours,l.minutes,0,0):i.setHours(0,0,0,0),i.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=Mo[o[1].toLowerCase()],i=Be(o[2]||""),u=new Date(t),f=u.getDay()-l;return f<=0&&(f+=7),u.setDate(u.getDate()-f),i?u.setHours(i.hours,i.minutes,0,0):u.setHours(0,0,0,0),u.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=St[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let i=parseInt(s[2],10),u=parseInt(s[3],10),c=Be(s[4]||"");return new Date(u,l,i,c?.hours||0,c?.minutes||0,0,0).toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=St[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let i=parseInt(r[2],10),u=Be(r[3]||""),c=t.getFullYear(),f=new Date(c,l,i,u?.hours||0,u?.minutes||0,0,0);return f>t&&f.setFullYear(c-1),f.toISOString()}let a=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(a){let l=St[a[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let i=parseInt(a[2],10),u=Be(a[3]||""),c=t.getFullYear(),f=new Date(c,l,i,u?.hours||0,u?.minutes||0,0,0);return f>t&&f.setFullYear(c-1),f.toISOString()}return null}async function $(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function pn(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function ye(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",r=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),a=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),l=s.includes("Get hired faster")||s.includes("Get hired 2x");if(r||a||l){let i=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:s.substring(0,80)};let u=o.querySelectorAll("button");for(let c of u){let f=c.innerText?.trim().toLowerCase()||"",d=c.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return c.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function gn(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function hn(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var St,Mo,Re=qe(()=>{St={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Mo={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});import{getPluginConfig as Oo}from"@ilivemylife/graph-sdk";var No,z,V,He,De,Je=qe(async()=>{No=await Oo();for(let[e,t]of Object.entries(No))process.env[e]===void 0&&(process.env[e]=t);z=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),He=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),De=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as U from"fs";import*as B from"path";import{fileURLToPath as jo}from"url";import{execSync as $t}from"child_process";function kn(){Ie=null,Fo=null,le=null,be=null,Me=null,we=null}function ce(){U.existsSync(X)||U.mkdirSync(X,{recursive:!0})}function Oe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";U.writeFileSync(o,n);for(let s=0;s<3;s++)try{U.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw r}}function Ye(e,t){if(!U.existsSync(e))return null;try{let n=JSON.parse(U.readFileSync(e,"utf-8"));try{U.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(U.existsSync(o))try{let s=JSON.parse(U.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{U.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{U.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ge(){return new Date().toISOString().split("T")[0]}function Et(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Bo(){U.existsSync(Ct)||U.mkdirSync(Ct,{recursive:!0})}function Cn(e){let t=Et(e);return t?B.join(Ct,`${t}.json`):null}function Ho(e){let t=Cn(e);return t?Ye(t,`profile-history/${Et(e)}.json`)||[]:[]}function Jo(e,t){let n=Cn(e);if(!n)return;Bo();let o=Ho(e);o.unshift(t);try{Oe(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Et(e)}: ${s.message}`)}}function wn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function bn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Vo(e,t){if(!e)return[];let n=[];for(let o of qo){let s=e[o],r=t[o];wn(s)||wn(r)||bn(s)!==bn(r)&&n.push(o)}return n}function Wo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function J(){return Ie||(ce(),Ie=Ye(kt,"people.json")||{},Ie)}function Ne(e){ce(),Ie=e;try{Oe(kt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(kt)}`)}}function ze(){return be||(ce(),be=Ye(ct,"conversations.json")||{},Yo(be),be)}function Yo(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(r=>r.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.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(ct,e)}catch{}}}function me(e){ce(),be=e;try{Oe(ct,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(ct)}`)}}function Se(e,t={}){if(!e)return null;let n=J(),o=Ge(),s=new Date().toISOString(),r=n[e];if(r){let a=Vo(r,t);a.length>0&&(Jo(e,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:a,snapshot:Wo(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let l of Uo)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(r[l])&&r[l].length>0)continue;r[l]=t[l]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Ne(n),n[e]}function En(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let r={date:Ge(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(r.jobId=String(t.jobId)),t.jobTitle&&(r.jobTitle=t.jobTitle),t.jobCompany&&(r.jobCompany=t.jobCompany),!o.encounters.some(l=>l.date===r.date&&l.source===r.source&&l.action===r.action&&(l.jobId||"")===(r.jobId||""))&&(o.encounters.push(r),o.lastUpdated=new Date().toISOString(),Ne(n))}function _n(e){return e&&J()[e]?.connectionStatus||null}function xn(e,t,n={}){if(!e)return;n.profileInfo?Se(e,n.profileInfo):J()[e]||Se(e,{});let o=J(),s=o[e];if(!s)return;let r=Ge();s.connectionStatus=t,t==="connected"?s.connectionDate=r:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(s.requestedConnectionAt||(s.requestedConnectionAt=r)),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),Ne(o)}function An(){return le||(ce(),le=Ye(Sn,"quota.json"),(!le||!le.connections)&&(le={connections:[]}),le)}function Go(e){ce(),le=e;try{Oe(Sn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Tn(e,t="unknown"){let n=An(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Go(n)}function Rn(){let e=An(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function _t(){let e=Rn(),t=Ge(),n=e.filter(i=>i.date===t).length,o=e.length,s=n>=Ve,r=o>=We,a=!s&&!r,l={allowed:a,daily:{sent:n,max:Ve},weekly:{sent:o,max:We}};return a||(l.reason=s?`Daily limit reached (${n}/${Ve})`:`Weekly limit reached (${o}/${We})`),l}function Ke(){let e=Rn(),t=Ge(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:Ve,remaining:Ve-n},weekly:{sent:o,max:We,remaining:We-o}}}function xt(){return Me||(ce(),Me=Ye(vn,"sync-state.json")||{},Me)}function Dn(e){ce(),Me=e;try{Oe(vn,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function zo(){if(we)return we;ce();try{U.existsSync(yn)&&(we=JSON.parse(U.readFileSync(yn,"utf-8")))}catch{}return we||(we={}),we}function Ko(e){return Array.isArray(e.applications)}function Qo(){let e=zo();if(Ko(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function In(){let e=Qo(),t=new Map;for(let r of e)for(let a of r.questions||[]){let l=a.question.toLowerCase().trim();if(!l)continue;t.has(l)||t.set(l,{question:a.question,count:0,answers:new Map});let i=t.get(l);i.count++;let u=(a.answer||"").trim();i.answers.set(u,(i.answers.get(u)||0)+1)}let n=[...t.values()].sort((r,a)=>a.count-r.count),o=n.slice(0,15).map(r=>({question:r.question,count:r.count,topAnswer:[...r.answers.entries()].sort((a,l)=>l[1]-a[1])[0]?.[0]||""})),s=n.filter(r=>r.answers.size>1&&r.count>=3).map(r=>({question:r.question,count:r.count,answers:[...r.answers.entries()].sort((a,l)=>l[1]-a[1]).map(([a,l])=>`${a} (${l}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function At(e){if(U.existsSync(B.join(X,".git")))try{let t={cwd:X,stdio:"pipe",timeout:1e4};$t("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{$t("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');$t(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Po,Lo,X,kt,$i,Sn,ct,vn,yn,Ct,$n,Ve,We,Ie,Fo,le,be,Me,we,Uo,qo,Qe=qe(async()=>{await Je();Po=jo(import.meta.url),Lo=B.dirname(B.dirname(Po)),X=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Lo,"collected-profiles"),kt=B.join(X,"people.json"),$i=B.join(X,"jobs.json"),Sn=B.join(X,"quota.json"),ct=B.join(X,"conversations.json"),vn=B.join(X,"sync-state.json"),yn=B.join(X,"application-questions.json"),Ct=B.join(X,"profile-history"),$n=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ve=$n(process.env.CONNECT_MAX_DAILY,20),We=$n(process.env.CONNECT_MAX_WEEKLY,100),Ie=null,Fo=null,le=null,be=null,Me=null,we=null;Uo=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],qo=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var po={};Te(po,{extractCertificationsFromDetails:()=>Br,extractEducationFromDetails:()=>Ur,extractExperienceFromDetails:()=>Lr,extractFeaturedFromDetails:()=>Fr,extractRecommendationsFromDetails:()=>Hr,extractSkillsFromDetails:()=>qr});async function Lr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let r=0;r<5;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(900);await $(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)s++,await $(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(700);return await e.evaluate(()=>{let r=document.querySelector("main");if(!r)return[];function a(c){let f=[];for(let d of c.querySelectorAll("div")){let m=Array.from(d.children).filter(p=>p.tagName==="DIV");if(m.length<3)continue;let y=m.filter(p=>(p.textContent||"").trim().length>50);y.length<3||(d.textContent||"").length<500||f.push({el:d,count:y.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let l=a(r);if(!l)return[];let i=Array.from(l.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function u(c){let f=c[0]||null,d=null,m=null;if(c[1]){let T=c[1].split("\xB7").map(L=>L.trim());d=T[0]||null,T[1]&&(m=T[1])}let y=c.findIndex(T=>/(\d{4}|present)/i.test(T)&&/(-|–|—)/i.test(T)&&T.length<80),p=null,S=null;if(y>=0){let T=c[y].split("\xB7").map(L=>L.trim());p=T[0]||null,T[1]&&(S=T[1])}let w=null,b=-1;if(y>=0&&c[y+1]){let T=c[y+1],L=/^[>*\-•]|^>/.test(T),G=/https?:\/\//.test(T),v=/\d{4}/.test(T),_=/,/.test(T)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(T);!L&&!G&&!v&&T.length<100&&_&&(w=T,b=y+1)}let g=null,h=-1,k=c[c.length-1];if(k&&/and\s+\+\d+\s+skills?$/i.test(k)){h=c.length-1;let T=k.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);T&&(g={listed:T[1].split(",").map(L=>L.trim()),additional:parseInt(T[2],10)})}let C=new Set([0,1,y,b,h].filter(T=>T>=0)),x=c.filter((T,L)=>!C.has(L)),I=x.length>0?x.join(`
|
|
1
|
+
var jo=Object.defineProperty;var Je=(e,t)=>()=>(e&&(t=e(e=0)),t);var De=(e,t)=>{for(var n in t)jo(e,n,{get:t[n],enumerable:!0})};function Ve(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function Ct(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let l=Ve(n),r=new Date(t);return l?r.setHours(l.hours,l.minutes,0,0):r.setHours(0,0,0,0),r.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=Po[o[1].toLowerCase()],r=Ve(o[2]||""),u=new Date(t),f=u.getDay()-l;return f<=0&&(f+=7),u.setDate(u.getDate()-f),r?u.setHours(r.hours,r.minutes,0,0):u.setHours(0,0,0,0),u.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=kt[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let r=parseInt(s[2],10),u=parseInt(s[3],10),c=Ve(s[4]||"");return new Date(u,l,r,c?.hours||0,c?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let l=kt[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let r=parseInt(i[2],10),u=Ve(i[3]||""),c=t.getFullYear(),f=new Date(c,l,r,u?.hours||0,u?.minutes||0,0,0);return f>t&&f.setFullYear(c-1),f.toISOString()}let a=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(a){let l=kt[a[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let r=parseInt(a[2],10),u=Ve(a[3]||""),c=t.getFullYear(),f=new Date(c,l,r,u?.hours||0,u?.minutes||0,0,0);return f>t&&f.setFullYear(c-1),f.toISOString()}return null}async function v(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function yn(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await v(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function ye(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),a=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),l=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||a||l){let r=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(r)return r.click(),{dismissed:!0,matched:s.substring(0,80)};let u=o.querySelectorAll("button");for(let c of u){let f=c.innerText?.trim().toLowerCase()||"",d=c.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return c.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function wn(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function bn(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var kt,Po,Ie=Je(()=>{kt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Po={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});import{getPluginConfig as Lo}from"@ilivemylife/graph-sdk";var Fo,z,V,We,Me,Ye=Je(async()=>{Fo=await Lo();for(let[e,t]of Object.entries(Fo))process.env[e]===void 0&&(process.env[e]=t);z=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),We=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Me=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as L from"fs";import*as B from"path";import{fileURLToPath as Uo}from"url";import{execSync as Et}from"child_process";function xn(){Oe=null,Ho=null,le=null,be=null,Ne=null,we=null}function ce(){L.existsSync(X)||L.mkdirSync(X,{recursive:!0})}function Pe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";L.writeFileSync(o,n);for(let s=0;s<3;s++)try{L.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw i}}function Ke(e,t){if(!L.existsSync(e))return null;try{let n=JSON.parse(L.readFileSync(e,"utf-8"));try{L.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(L.existsSync(o))try{let s=JSON.parse(L.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{L.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{L.copyFileSync(e,e+".corrupted")}catch{}return null}}function Qe(){return new Date().toISOString().split("T")[0]}function Se(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function vn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function je(e,t,n=null){if(!t||e[t])return t;let o=Se(t);if(!o)return t;let s=null;for(let[i,a]of Object.entries(e)){if(Se(a.profileUrl||i)===o)return i;!s&&Array.isArray(a.aliases)&&a.aliases.includes(o)&&(s=i)}if(s){let i=vn(n),a=vn(e[s].name);if(i&&a&&i===a)return s}return t}function Wo(){L.existsSync(xt)||L.mkdirSync(xt,{recursive:!0})}function An(e){let t=Se(e);return t?B.join(xt,`${t}.json`):null}function Yo(e){let t=An(e);return t?Ke(t,`profile-history/${Se(e)}.json`)||[]:[]}function Go(e,t){let n=An(e);if(!n)return;Wo();let o=Yo(e);o.unshift(t);try{Pe(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Se(e)}: ${s.message}`)}}function $n(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function kn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function zo(e,t){if(!e)return[];let n=[];for(let o of Vo){let s=e[o],i=t[o];$n(s)||$n(i)||kn(s)!==kn(i)&&n.push(o)}return n}function Ko(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function J(){return Oe||(ce(),Oe=Ke(_t,"people.json")||{},Oe)}function $e(e){ce(),Oe=e;try{Pe(_t,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(_t)}`)}}function Xe(){return be||(ce(),be=Ke(dt,"conversations.json")||{},Qo(be),be)}function Qo(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(i=>i.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.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{Pe(dt,e)}catch{}}}function me(e){ce(),be=e;try{Pe(dt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(dt)}`)}}function ve(e,t={}){if(!e)return null;let n=J(),o=Qe(),s=new Date().toISOString(),i=je(n,e,t.name),a=n[i];if(a){let l=zo(a,t);l.length>0&&(Go(i,{capturedAt:s,previousLastUpdated:a.lastUpdated||null,changedFields:l,snapshot:Ko(a)}),a.lastSnapshotAt=s),a.seenCount=(a.seenCount||1)+1,a.lastSeen=o,a.lastUpdated=s,t.source&&!a.sources?.includes(t.source)&&(a.sources=a.sources||[],a.sources.push(t.source));for(let r of Jo)if(t[r]!=null){if(Array.isArray(t[r])&&t[r].length===0&&Array.isArray(a[r])&&a[r].length>0)continue;a[r]=t[r]}Array.isArray(t.availableSections)&&(a.lastFullVisitAt=s)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return $e(n),n[i]}function Tn(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Qe(),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),!o.encounters.some(l=>l.date===i.date&&l.source===i.source&&l.action===i.action&&(l.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),$e(n))}function Rn(e){return e&&J()[e]?.connectionStatus||null}function Dn(e,t,n={}){if(!e)return;if(n.profileInfo)ve(e,n.profileInfo);else{let l=J(),r=je(l,e,n.profileInfo?.name);l[r]||ve(e,{})}let o=J(),s=je(o,e,n.profileInfo?.name),i=o[s];if(!i)return;let a=Qe();i.connectionStatus=t,t==="connected"?i.connectionDate=a:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=a)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),$e(o)}function ft(e,t,n={}){if(n.dryRun||!e||!t)return;let o=Se(t);if(!o)return;let s=J(),i=je(s,e),a=s[i];if(!a)return;let l=Se(a.profileUrl||i);o!==l&&(Array.isArray(a.aliases)||(a.aliases=[]),a.aliases.includes(o)||(a.aliases.push(o),a.lastUpdated=new Date().toISOString(),$e(s)))}function In(){return le||(ce(),le=Ke(Cn,"quota.json"),(!le||!le.connections)&&(le={connections:[]}),le)}function Xo(e){ce(),le=e;try{Pe(Cn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Mn(e,t="unknown"){let n=In(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Xo(n)}function On(){let e=In(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function At(){let e=On(),t=Qe(),n=e.filter(r=>r.date===t).length,o=e.length,s=n>=Ge,i=o>=ze,a=!s&&!i,l={allowed:a,daily:{sent:n,max:Ge},weekly:{sent:o,max:ze}};return a||(l.reason=s?`Daily limit reached (${n}/${Ge})`:`Weekly limit reached (${o}/${ze})`),l}function Ze(){let e=On(),t=Qe(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:Ge,remaining:Ge-n},weekly:{sent:o,max:ze,remaining:ze-o}}}function Tt(){return Ne||(ce(),Ne=Ke(En,"sync-state.json")||{},Ne)}function Nn(e){ce(),Ne=e;try{Pe(En,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Zo(){if(we)return we;ce();try{L.existsSync(Sn)&&(we=JSON.parse(L.readFileSync(Sn,"utf-8")))}catch{}return we||(we={}),we}function es(e){return Array.isArray(e.applications)}function ts(){let e=Zo();if(es(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function jn(){let e=ts(),t=new Map;for(let i of e)for(let a of i.questions||[]){let l=a.question.toLowerCase().trim();if(!l)continue;t.has(l)||t.set(l,{question:a.question,count:0,answers:new Map});let r=t.get(l);r.count++;let u=(a.answer||"").trim();r.answers.set(u,(r.answers.get(u)||0)+1)}let n=[...t.values()].sort((i,a)=>a.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((a,l)=>l[1]-a[1])[0]?.[0]||""})),s=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((a,l)=>l[1]-a[1]).map(([a,l])=>`${a} (${l}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function Rt(e){if(L.existsSync(B.join(X,".git")))try{let t={cwd:X,stdio:"pipe",timeout:1e4};Et("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{Et("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Et(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var qo,Bo,X,_t,_i,Cn,dt,En,Sn,xt,_n,Ge,ze,Oe,Ho,le,be,Ne,we,Jo,Vo,Le=Je(async()=>{await Ye();qo=Uo(import.meta.url),Bo=B.dirname(B.dirname(qo)),X=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Bo,"collected-profiles"),_t=B.join(X,"people.json"),_i=B.join(X,"jobs.json"),Cn=B.join(X,"quota.json"),dt=B.join(X,"conversations.json"),En=B.join(X,"sync-state.json"),Sn=B.join(X,"application-questions.json"),xt=B.join(X,"profile-history"),_n=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ge=_n(process.env.CONNECT_MAX_DAILY,20),ze=_n(process.env.CONNECT_MAX_WEEKLY,100),Oe=null,Ho=null,le=null,be=null,Ne=null,we=null;Jo=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],Vo=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var wo={};De(wo,{extractCertificationsFromDetails:()=>Wr,extractEducationFromDetails:()=>Jr,extractExperienceFromDetails:()=>Br,extractFeaturedFromDetails:()=>Hr,extractRecommendationsFromDetails:()=>Yr,extractSkillsFromDetails:()=>Vr});async function Br(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await v(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await v(900);await v(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)s++,await v(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await v(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function a(c){let f=[];for(let d of c.querySelectorAll("div")){let m=Array.from(d.children).filter(g=>g.tagName==="DIV");if(m.length<3)continue;let y=m.filter(g=>(g.textContent||"").trim().length>50);y.length<3||(d.textContent||"").length<500||f.push({el:d,count:y.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let l=a(i);if(!l)return[];let r=Array.from(l.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function u(c){let f=c[0]||null,d=null,m=null;if(c[1]){let T=c[1].split("\xB7").map(F=>F.trim());d=T[0]||null,T[1]&&(m=T[1])}let y=c.findIndex(T=>/(\d{4}|present)/i.test(T)&&/(-|–|—)/i.test(T)&&T.length<80),g=null,S=null;if(y>=0){let T=c[y].split("\xB7").map(F=>F.trim());g=T[0]||null,T[1]&&(S=T[1])}let w=null,b=-1;if(y>=0&&c[y+1]){let T=c[y+1],F=/^[>*\-•]|^>/.test(T),G=/https?:\/\//.test(T),k=/\d{4}/.test(T),E=/,/.test(T)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(T);!F&&!G&&!k&&T.length<100&&E&&(w=T,b=y+1)}let h=null,p=-1,$=c[c.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){p=c.length-1;let T=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);T&&(h={listed:T[1].split(",").map(F=>F.trim()),additional:parseInt(T[2],10)})}let C=new Set([0,1,y,b,p].filter(T=>T>=0)),A=c.filter((T,F)=>!C.has(F)),R=A.length>0?A.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:f,company:d,employmentType:m,dates:
|
|
4
|
-
`).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return u(d)}).filter(c=>c.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function
|
|
5
|
-
${
|
|
3
|
+
`):null;return{title:f,company:d,employmentType:m,dates:g,duration:S,location:w,description:R,skills:h,_raw:c}}return r.map(c=>{let d=(c.innerText||"").trim().split(`
|
|
4
|
+
`).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return u(d)}).filter(c=>c.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function rt(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await v(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/${n}/`);if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let a=0;a<4;a++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await v(700);await v(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)i++,await v(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await v(600)}async function at(e,t,n,o){try{return await o()}catch(s){let i=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw s;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function Hr(e,t){return at(t,"featured","extractFeaturedFromDetails",async()=>(await rt(e,t,"featured"),await e.evaluate(`(() => {
|
|
5
|
+
${it}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
8
8
|
if (!main) return [];
|
|
@@ -42,8 +42,8 @@ var Io=Object.defineProperty;var qe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
42
42
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
43
43
|
return true;
|
|
44
44
|
});
|
|
45
|
-
})()`)))}async function
|
|
46
|
-
${
|
|
45
|
+
})()`)))}async function Jr(e,t){return at(t,"education","extractEducationFromDetails",async()=>(await rt(e,t,"education"),await e.evaluate(`(() => {
|
|
46
|
+
${it}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
49
49
|
if (!main) return [];
|
|
@@ -79,8 +79,8 @@ var Io=Object.defineProperty;var qe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
79
79
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
80
80
|
return true;
|
|
81
81
|
});
|
|
82
|
-
})()`)))}async function
|
|
83
|
-
${
|
|
82
|
+
})()`)))}async function Vr(e,t){return at(t,"skills","extractSkillsFromDetails",async()=>(await rt(e,t,"skills"),await e.evaluate(`(() => {
|
|
83
|
+
${it}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
86
86
|
if (!main) return [];
|
|
@@ -111,8 +111,8 @@ var Io=Object.defineProperty;var qe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
115
|
-
${
|
|
114
|
+
})()`)))}async function Wr(e,t){return at(t,"certifications","extractCertificationsFromDetails",async()=>(await rt(e,t,"certifications"),await e.evaluate(`(() => {
|
|
115
|
+
${it}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
118
118
|
if (!main) return [];
|
|
@@ -136,8 +136,8 @@ var Io=Object.defineProperty;var qe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
136
136
|
|
|
137
137
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
138
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function
|
|
140
|
-
${
|
|
139
|
+
})()`)))}async function Yr(e,t){return at(t,"recommendations","extractRecommendationsFromDetails",async()=>(await rt(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
140
|
+
${it}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
143
143
|
if (!main) return [];
|
|
@@ -172,7 +172,7 @@ var Io=Object.defineProperty;var qe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
172
172
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
173
173
|
return true;
|
|
174
174
|
});
|
|
175
|
-
})()`)))}var
|
|
175
|
+
})()`)))}var it,bo=Je(()=>{Ie();it=`
|
|
176
176
|
function findEntryContainer(root) {
|
|
177
177
|
const candidates = [];
|
|
178
178
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,132 +235,132 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});var wo={};Te(wo,{clickConnectButton:()=>Zt,default:()=>Wr,detectConnectionStatus:()=>xe,findConnectButton:()=>it,runFunnel:()=>yo,sendConnectionRequest:()=>en,shouldExcludeLocation:()=>yt,viewProfile:()=>Xt});async function ho(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 $(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function yt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Xt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:r=!1,extractSkills:a=!1,extractRecommendations:l=!1,extractCertifications:i=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await $(1500),await ho(e,t));let c=0;for(let g=0;g<2;g++){let h=await e.evaluate(()=>document.body.scrollHeight);for(let C=1;C<=6;C++)await e.evaluate(x=>window.scrollTo(0,x),h*C/6),await $(900);let k=await e.evaluate(()=>document.body.scrollHeight);if(k===c)break;c=k}await $(800);let f=await e.evaluate(()=>{let g=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),h=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),k=R=>{let D=(R||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},C={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},x=document.querySelector("main");if(!x)return C;let I=[...Array.from(x.querySelectorAll("h1")),...Array.from(x.querySelectorAll("h2"))],T=Array.from(x.querySelectorAll("h2")),L=I.find(R=>{let D=R.textContent&&R.textContent.trim(),O=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!g.has(O)&&!h.has(O)}),G=L?L.textContent.trim():null,v=L?L.parentElement:null;for(;v&&v!==x&&!Array.from(v.children).filter(D=>D.tagName==="P").some(D=>{let O=D.textContent&&D.textContent.trim();return O&&O.length>5&&!k(O)});)v=v.parentElement;let _=null,A=null,M=null,q=null;if(v&&v!==x){let R=Array.from(v.children).filter(O=>O.tagName==="P").filter(O=>{let fe=O.textContent&&O.textContent.trim();return fe&&fe.length>5&&!k(fe)});if(R[0]&&(_=R[0].textContent.trim()),R[1]){let O=R[1].textContent.trim().split(/\s*[·•]\s*/);A=O[0]||null,O.length>1&&(M=O.slice(1).join(" \xB7 "))}let D=Array.from(v.children).filter(O=>O.tagName==="DIV");for(let O=D.length-1;O>=0;O--){let fe=D[O].textContent&&D[O].textContent.trim();if(fe&&!(G&&fe.startsWith(G))&&(q=fe.split(/[·•]/)[0].trim(),q))break}}let ie=null;if(v){let R=v.querySelectorAll("p, span, div");for(let D of R){let O=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(O==="1st"||O==="2nd"||O==="3rd"){ie=O;break}}}let ae=!!x.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),j=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),F=j&&j.src||null,P=x.textContent||"",H=null,se=P.match(/(\d+\+?)\s+connections\b/i);se&&(H=se[1]+" connections");let lt=null,an=P.match(/(\d+)\s+mutual connection/i),ln=P.match(/and\s+(\d+)\s+other mutual/i),xo=P.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);an?lt=parseInt(an[1],10):ln?lt=2+parseInt(ln[1],10):xo&&(lt=2);let cn=null,un=null,dn=T.find(R=>R.textContent&&R.textContent.trim()==="About");if(dn){let R=dn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let O=D.match(/Top skills\s*(.+?)$/i);if(O){let bt=O[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Do=>Do.trim()).filter(Boolean);bt.length>0&&bt.length<10&&(un=bt)}D=D.split(/\n?…\s*more/i)[0].trim(),D=D.split(/\n?\.\.\.\s*more/i)[0].trim(),D=D.split(/\bTop skills\b/i)[0].trim(),D=D.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),cn=D||null}}let fn=null,mn=T.find(R=>R.textContent&&R.textContent.trim()==="Activity");if(mn){let R=mn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(fn=parseInt(D[1].replace(/,/g,""),10))}}let Ao=[...new Set(T.map(R=>(R.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(R=>R&&R.length>1&&R.length<60&&R!==G).filter(R=>g.has(R)))],Ue=document.body.textContent||"",To=/#OpenToWork\b/i.test(Ue)||/\bOpen to work\b/.test(Ue),Ro=/#Hiring\b/i.test(Ue)||/\bI'?m hiring\b/i.test(Ue)||/\bWe are hiring\b/i.test(Ue);return{name:G,title:_,location:q,currentCompany:A,currentSchool:M,connectionDegree:ie,hasVerifiedBadge:ae,photoUrl:F,connectionsLevel:H,mutualConnectionsCount:lt,followers:fn,openToWork:To,hiring:Ro,about:cn,topSkills:un,availableSections:Ao}});console.log(`Viewed: ${f.name} - ${f.title}`);let d=null,m=null,y=null,p=null,S=null,w=null;if(o||s||r||a||l||i){let g=await Promise.resolve().then(()=>(go(),po));o&&(d=await g.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),s&&(m=await g.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),r&&(y=await g.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),a&&(p=await g.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),l&&(S=await g.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),i&&(w=await g.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${w.length} entries`))}return{...f,profileUrl:t,...d!==null&&{experience:d},...m!==null&&{featured:m},...y!==null&&{education:y},...p!==null&&{skillsFull:p},...S!==null&&{recommendations:S},...w!==null&&{certifications:w}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function xe(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=u=>u&&!u.closest(n),s=u=>Array.from(document.querySelectorAll(u)).filter(o),r=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,i={pendingCount:r.length,pendingLabels:r.map(u=>u.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return r.length>0?{status:"pending",debug:i}:a&&!l?{status:"connected",debug:i}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:i}:{status:"not_connected",debug:i}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function it(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 c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.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 c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).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(c=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=c.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of f){let p=y.getBoundingClientRect();if(p.width===0||p.height===0||y.closest(m))continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(d))return y}return 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 d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(p=>{let S=p.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&d.test(S)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let y of d){let p=y.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p))return y}return null},i);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,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(c=>(c.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 o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let s=n?n.split(" ")[0].toLowerCase():"",r=null;for(let i of o){let u=await e.evaluate((c,f)=>{let d=c.className.includes("muted"),m=c.className.includes("sticky-header")||c.className.includes("sticky"),y=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(c.getAttribute("aria-label")||"").toLowerCase(),S=p.includes("invite"),w=f?p.includes(f):!0;return{isMuted:d,isStickyHeader:m,inRecommendations:y,hasInvite:S,matchesName:w,ariaLabel:p}},i,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}r=i;break}}for(let i of o)i!==r&&await i.dispose().catch(()=>{});if(r)return console.log(" Found: secondary button"),{button:r,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 a=null,l=await e.$$('button[id*="profile-overflow-action"]');for(let i of l){let u=await e.evaluate(c=>{let f=c.getBoundingClientRect(),d=f.width>0&&f.height>0,m=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:m,top:f.top}},i);if(u.isVisible&&!u.isInStickyHeader){a=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of l)i!==a&&await i.dispose().catch(()=>{});if(!a&&l.length>0&&(a=l[l.length-1],console.log(" Found More button by ID pattern (last)")),a||(a=await e.$('button[aria-label="More actions"]'),a&&console.log(" Found More button by aria-label")),!a){let i=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(d=>{let m=d.innerText?.trim(),y=d.getAttribute("aria-label")||"",p=d.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!c)return null;let f=c.parentElement;for(let d=0;d<8&&f;d++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==c)return m;f=f.parentElement}return null});a=i?.asElement?.()||null,a||await i?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),a),await $(500),await e.evaluate(c=>c.click(),a),await $(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 c=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let m=d.querySelector('a[href*="custom-invite"]');if(m)return m;for(let y of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(y.innerText?.trim()==="Connect")return y}return null});u=c?.asElement?.()||null,u||await c?.dispose?.().catch(()=>{})}if(!u){let c=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let m of f)for(let y of m.querySelectorAll('[role="menuitem"], a, div')){let p=y.innerText?.trim();p&&p.length<40&&d.push(p)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}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(c=>(c.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 Zt(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await $(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),r=n.tag==="DIV",a=(n.ariaLabel||"").toLowerCase();if(a.includes("invite")){let c=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(c&&!a.includes(c))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${c})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await $(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 $(2e3),"premium_redirect"}else r?(await e.evaluate(c=>c.click(),t),await $(3e3)):(await e.evaluate(c=>c.click(),t),await $(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 i=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(i?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function Jr(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 $(1500);let n=await it(e);if(n){await e.evaluate(s=>s.click(),n),await $(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function en(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:r=!1}=n;if(!s){let l=_t();if(!l.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${l.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:l.reason,profileInfo:null}}let a=await Vr(e,t,n);return a.connectionSent&&!r&&Tn(t,o),a}async function Vr(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:r=!0,skipIfConnected:a=!0,excludeLocations:l=[]}=n,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
239
|
-
--- Connecting: ${u} ---`),l.length>0){let w=J()[t]?.location;if(yt(w,l))return console.log(` \u26A0 Excluded location (stored): ${w}`),i.reason="excluded_location",i.profileInfo={location:w},i}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(5e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await $(2e3),await ho(e,t),await $(2e3)),i.profileInfo=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),b=j=>{let F=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(F)},g={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},h=document.querySelector("main");if(!h)return g;let k=[...Array.from(h.querySelectorAll("h1")),...Array.from(h.querySelectorAll("h2"))],C=Array.from(h.querySelectorAll("h2")),x=k.find(j=>{let F=j.textContent&&j.textContent.trim();return F&&F.length>1&&F.length<100&&!w.has(F)&&F!=="0 notifications"}),I=x?x.textContent.trim():null,T=x?x.parentElement:null;for(;T&&T!==h&&!Array.from(T.children).filter(P=>P.tagName==="P").some(P=>{let H=P.textContent&&P.textContent.trim();return H&&H.length>5&&!b(H)});)T=T.parentElement;let L=null,G=null,v=null;if(T&&T!==h){let j=Array.from(T.children),F=j.filter(H=>H.tagName==="P").filter(H=>{let se=H.textContent&&H.textContent.trim();return se&&se.length>5&&!b(se)});F[0]&&(L=F[0].textContent.trim()),F[1]&&(G=F[1].textContent.trim());let P=j.filter(H=>H.tagName==="DIV");for(let H=P.length-1;H>=0;H--){let se=P[H].textContent&&P[H].textContent.trim();if(se&&!(I&&se.startsWith(I))&&(v=se.split(/[·•]/)[0].trim(),v))break}}let _=null;if(T){let j=T.querySelectorAll("p, span, div");for(let F of j){let P=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){_=P;break}}}let A=null,M=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(M){let j=M.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(A=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,A&&(A=A.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let q=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),ie=q&&q.src||null,ae=!!h.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:I,title:L,location:v,about:A,company:G,connectionDegree:_,connectionsCount:null,mutualConnections:null,photoUrl:ie,hasVerifiedBadge:ae}});try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(i.resolvedUrl=w.split("?")[0].replace(/\/+$/,""))}catch{}if(l.length>0){let w=i.profileInfo?.location,b=J()[t]?.location,g=w||b;if(yt(g,l))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${g}`),i.reason="excluded_location",i;!w&&b==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await xe(e);if(i.profileInfo?.connectionDegree==="1st"&&f!=="pending"&&(f!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),f="connected"),f==="pending"&&r)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(f==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await ye(e);let d=await it(e);if(!d&&(await ye(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await $(2e3),d=await it(e)),!d))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;i.method=d.method;let m=await Zt(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),i.reason="wrong_target",i;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let w=await xe(e);if(w==="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: ${w} \u2014 trying More dropdown...`),await ye(e),await $(1e3);let b=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(b)try{await e.evaluate(h=>h.scrollIntoView({behavior:"smooth",block:"center"}),b),await $(500),await b.click().catch(()=>e.evaluate(h=>h.click(),b)),await $(2e3);let g=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(g){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),g),await $(3e3);let h=e.url();if(h.includes("/premium/")||h.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),i.reason="premium_required",i;if(await xe(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 $(500),i.reason="premium_required",i}catch(g){return console.log(" More dropdown failed:",g.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 w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await $(500),i.reason="email_required",i}let p=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!p&&!S){let w=await e.evaluate(()=>{let b=document.querySelector("#interop-outlet")?.shadowRoot;if(!b)return{addNote:!1,sendWithout:!1};let g=b.querySelector('button[aria-label="Add a note"]'),h=b.querySelector('button[aria-label="Send without a note"]');return{addNote:!!g,sendWithout:!!h}});if(w.addNote){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=b?.asElement?.()||null,p||await b.dispose().catch(()=>{})}if(w.sendWithout){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=b?.asElement?.()||null,S||await b.dispose().catch(()=>{})}}if(s){if(p&&o){if(console.log(" Adding personalized note..."),await p.click(),await $(1500),await e.$("div.modal-upsell")){let g=await Jr(e);return i.success=g,i.connectionSent=g,i.reason=g?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let b=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(b){let g=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),h=o.replace("{name}",g);await b.type(h,{delay:20}),await $(500);let k=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(k){try{await k.evaluate(C=>C.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=h,i}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await $(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(p&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await $(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 w=S;if(w){try{await w.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3)),await ye(e),await $(500);let b=await e.$$('button[id*="profile-overflow-action"]'),g=null;for(let h of b){let k=await e.evaluate(C=>{let x=C.getBoundingClientRect();return{visible:x.width>0&&x.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},h);if(k.visible&&!k.inSticky){g=h;break}}!g&&b.length>0&&(g=b[b.length-1]);for(let h of b)h!==g&&await h.dispose().catch(()=>{});if(g)try{await e.evaluate(k=>k.scrollIntoView({behavior:"smooth",block:"center"}),g),await $(500),await g.click().catch(()=>e.evaluate(k=>k.click(),g)),await $(2e3);let h=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(h){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(I=>I.click(),h),await $(3e3);let k=e.url();if(k.includes("/premium/")||k.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await xe(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 xe(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 x=await e.$('button[aria-label="Send without a note"]');if(x){console.log(" Modal appeared via More dropdown, sending without note...");try{await x.evaluate(I=>I.click())}catch{}return await $(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(h){console.log(" More dropdown fallback failed:",h.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 c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{i.fatal=!0}return i}}async function yo(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:r=20,viewOnly:a=!1,delayBetweenProfiles:l=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:c="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
240
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${a?"View Only":`Connect (max ${
|
|
238
|
+
`});var $o={};De($o,{clickConnectButton:()=>tn,default:()=>Kr,detectConnectionStatus:()=>Te,findConnectButton:()=>lt,runFunnel:()=>vo,sendConnectionRequest:()=>nn,shouldExcludeLocation:()=>St,viewProfile:()=>en});async function So(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 v(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function St(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function en(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:a=!1,extractRecommendations:l=!1,extractCertifications:r=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await v(3e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await v(1500),await So(e,t));let c=0;for(let p=0;p<2;p++){let $=await e.evaluate(()=>document.body.scrollHeight);for(let A=1;A<=6;A++)await e.evaluate(R=>window.scrollTo(0,R),$*A/6),await v(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===c)break;c=C}await v(800);let f=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(f=p.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let p=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),$=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),C=D=>{let I=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},A={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},R=document.querySelector("main");if(!R)return A;let T=[...Array.from(R.querySelectorAll("h1")),...Array.from(R.querySelectorAll("h2"))],F=Array.from(R.querySelectorAll("h2")),G=T.find(D=>{let I=D.textContent&&D.textContent.trim(),O=(I||"").replace(/\s*\(\d+\)$/,"").trim();return I&&I.length>1&&I.length<100&&!p.has(O)&&!$.has(O)}),k=G?G.textContent.trim():null,E=G?G.parentElement:null;for(;E&&E!==R&&!Array.from(E.children).filter(I=>I.tagName==="P").some(I=>{let O=I.textContent&&I.textContent.trim();return O&&O.length>5&&!C(O)});)E=E.parentElement;let x=null,M=null,H=null,se=null;if(E&&E!==R){let D=Array.from(E.children).filter(O=>O.tagName==="P").filter(O=>{let fe=O.textContent&&O.textContent.trim();return fe&&fe.length>5&&!C(fe)});if(D[0]&&(x=D[0].textContent.trim()),D[1]){let O=D[1].textContent.trim().split(/\s*[·•]\s*/);M=O[0]||null,O.length>1&&(H=O.slice(1).join(" \xB7 "))}let I=Array.from(E.children).filter(O=>O.tagName==="DIV");for(let O=I.length-1;O>=0;O--){let fe=I[O].textContent&&I[O].textContent.trim();if(fe&&!(k&&fe.startsWith(k))&&(se=fe.split(/[·•]/)[0].trim(),se))break}}let re=null;if(E){let D=E.querySelectorAll("p, span, div");for(let I of D){let O=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(O==="1st"||O==="2nd"||O==="3rd"){re=O;break}}}let j=!!R.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),P=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=P&&P.src||null,q=R.textContent||"",ie=null,cn=q.match(/(\d+\+?)\s+connections\b/i);cn&&(ie=cn[1]+" connections");let ut=null,un=q.match(/(\d+)\s+mutual connection/i),dn=q.match(/and\s+(\d+)\s+other mutual/i),Do=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);un?ut=parseInt(un[1],10):dn?ut=2+parseInt(dn[1],10):Do&&(ut=2);let fn=null,mn=null,pn=F.find(D=>D.textContent&&D.textContent.trim()==="About");if(pn){let D=pn.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;if(D){let I=(D.textContent||"").trim();I=I.replace(/^About\s*/,"").trim();let O=I.match(/Top skills\s*(.+?)$/i);if(O){let $t=O[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(No=>No.trim()).filter(Boolean);$t.length>0&&$t.length<10&&(mn=$t)}I=I.split(/\n?…\s*more/i)[0].trim(),I=I.split(/\n?\.\.\.\s*more/i)[0].trim(),I=I.split(/\bTop skills\b/i)[0].trim(),I=I.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),fn=I||null}}let gn=null,hn=F.find(D=>D.textContent&&D.textContent.trim()==="Activity");if(hn){let D=hn.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;if(D){let I=(D.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);I&&(gn=parseInt(I[1].replace(/,/g,""),10))}}let Io=[...new Set(F.map(D=>(D.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(D=>D&&D.length>1&&D.length<60&&D!==k).filter(D=>p.has(D)))],He=document.body.textContent||"",Mo=/#OpenToWork\b/i.test(He)||/\bOpen to work\b/.test(He),Oo=/#Hiring\b/i.test(He)||/\bI'?m hiring\b/i.test(He)||/\bWe are hiring\b/i.test(He);return{name:k,title:x,location:se,currentCompany:M,currentSchool:H,connectionDegree:re,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:ie,mutualConnectionsCount:ut,followers:gn,openToWork:Mo,hiring:Oo,about:fn,topSkills:mn,availableSections:Io}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,y=null,g=null,S=null,w=null,b=null;if(o||s||i||a||l||r){let p=await Promise.resolve().then(()=>(bo(),wo));o&&(m=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(y=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${y.length} entries`)),i&&(g=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),a&&(S=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${S.length} entries`)),l&&(w=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.length} entries`)),r&&(b=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${b.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...y!==null&&{featured:y},...g!==null&&{education:g},...S!==null&&{skillsFull:S},...w!==null&&{recommendations:w},...b!==null&&{certifications:b}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await v(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function Te(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=u=>u&&!u.closest(n),s=u=>Array.from(document.querySelectorAll(u)).filter(o),i=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,r={pendingCount:i.length,pendingLabels:i.map(u=>u.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return i.length>0?{status:"pending",debug:r}:a&&!l?{status:"connected",debug:r}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:r}:{status:"not_connected",debug:r}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function lt(e){let t=null,n=await e.evaluate(()=>{let r=document.querySelector("h1")?.textContent?.trim();if(r&&!r.includes("notification"))return r;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(r=u.textContent?.trim(),r&&!r.includes("notification")))return r;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let r=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});r.count>0&&console.log(` S0: ${r.count} custom-invite links: ${JSON.stringify(r.labels)}`),t=await e.evaluateHandle(c=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=c.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of f){let g=y.getBoundingClientRect();if(g.width===0||g.height===0||y.closest(m))continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(d))return y}return 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 r=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${r}"`);let u=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(g=>{let S=g.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&d.test(S)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},r);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let y of d){let g=y.getAttribute("aria-label")||"";if((g.toLowerCase().includes("invite")||g.toLowerCase().includes("connect"))&&m.test(g))return y}return null},r);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,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 r=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(u)&&(console.log(` Skipping primary button: wrong person (${r})`),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 o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let r of o){let u=await e.evaluate((c,f)=>{let d=c.className.includes("muted"),m=c.className.includes("sticky-header")||c.className.includes("sticky"),y=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(c.getAttribute("aria-label")||"").toLowerCase(),S=g.includes("invite"),w=f?g.includes(f):!0;return{isMuted:d,isStickyHeader:m,inRecommendations:y,hasInvite:S,matchesName:w,ariaLabel:g}},r,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=r;break}}for(let r of o)r!==i&&await r.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 a=null,l=await e.$$('button[id*="profile-overflow-action"]');for(let r of l){let u=await e.evaluate(c=>{let f=c.getBoundingClientRect(),d=f.width>0&&f.height>0,m=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:m,top:f.top}},r);if(u.isVisible&&!u.isInStickyHeader){a=r,console.log(" Found More button by ID pattern (main)");break}}for(let r of l)r!==a&&await r.dispose().catch(()=>{});if(!a&&l.length>0&&(a=l[l.length-1],console.log(" Found More button by ID pattern (last)")),a||(a=await e.$('button[aria-label="More actions"]'),a&&console.log(" Found More button by aria-label")),!a){let r=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(d=>{let m=d.innerText?.trim(),y=d.getAttribute("aria-label")||"",g=d.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!c)return null;let f=c.parentElement;for(let d=0;d<8&&f;d++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==c)return m;f=f.parentElement}return null});a=r?.asElement?.()||null,a||await r?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),a),await v(500),await e.evaluate(c=>c.click(),a),await v(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 c=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let m=d.querySelector('a[href*="custom-invite"]');if(m)return m;for(let y of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(y.innerText?.trim()==="Connect")return y}return null});u=c?.asElement?.()||null,u||await c?.dispose?.().catch(()=>{})}if(!u){let c=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let m of f)for(let y of m.querySelectorAll('[role="menuitem"], a, div')){let g=y.innerText?.trim();g&&g.length<40&&d.push(g)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(r){console.log(" More dropdown click failed:",r.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let r=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(u)&&(console.log(` Skipping generic button: wrong person (${r})`),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 tn(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await v(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",a=(n.ariaLabel||"").toLowerCase();if(a.includes("invite")){let c=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(c&&!a.includes(c))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${c})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await v(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 v(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await v(3e3)):(await e.evaluate(c=>c.click(),t),await v(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 r=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(r?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function Gr(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 v(1500);let n=await lt(e);if(n){await e.evaluate(s=>s.click(),n),await v(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await v(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function nn(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let l=At();if(!l.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${l.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:l.reason,profileInfo:null}}let a=await zr(e,t,n);return a.connectionSent&&!i&&Mn(t,o),a}async function zr(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:a=!0,excludeLocations:l=[]}=n,r={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
239
|
+
--- Connecting: ${u} ---`),l.length>0){let w=J()[t]?.location;if(St(w,l))return console.log(` \u26A0 Excluded location (stored): ${w}`),r.reason="excluded_location",r.profileInfo={location:w},r}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await v(5e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await v(2e3),await So(e,t),await v(2e3)),r.profileInfo=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),b=j=>{let P=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},h={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},p=document.querySelector("main");if(!p)return h;let $=[...Array.from(p.querySelectorAll("h1")),...Array.from(p.querySelectorAll("h2"))],C=Array.from(p.querySelectorAll("h2")),A=$.find(j=>{let P=j.textContent&&j.textContent.trim();return P&&P.length>1&&P.length<100&&!w.has(P)&&P!=="0 notifications"}),R=A?A.textContent.trim():null,T=A?A.parentElement:null;for(;T&&T!==p&&!Array.from(T.children).filter(U=>U.tagName==="P").some(U=>{let q=U.textContent&&U.textContent.trim();return q&&q.length>5&&!b(q)});)T=T.parentElement;let F=null,G=null,k=null;if(T&&T!==p){let j=Array.from(T.children),P=j.filter(q=>q.tagName==="P").filter(q=>{let ie=q.textContent&&q.textContent.trim();return ie&&ie.length>5&&!b(ie)});P[0]&&(F=P[0].textContent.trim()),P[1]&&(G=P[1].textContent.trim());let U=j.filter(q=>q.tagName==="DIV");for(let q=U.length-1;q>=0;q--){let ie=U[q].textContent&&U[q].textContent.trim();if(ie&&!(R&&ie.startsWith(R))&&(k=ie.split(/[·•]/)[0].trim(),k))break}}let E=null;if(T){let j=T.querySelectorAll("p, span, div");for(let P of j){let U=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){E=U;break}}}let x=null,M=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(M){let j=M.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(x=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,x&&(x=x.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let H=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),se=H&&H.src||null,re=!!p.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:F,location:k,about:x,company:G,connectionDegree:E,connectionsCount:null,mutualConnections:null,photoUrl:se,hasVerifiedBadge:re}});try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(r.resolvedUrl=w.split("?")[0].replace(/\/+$/,""))}catch{}if(l.length>0){let w=r.profileInfo?.location,b=J()[t]?.location,h=w||b;if(St(h,l))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${h}`),r.reason="excluded_location",r;!w&&b==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await Te(e);if(r.profileInfo?.connectionDegree==="1st"&&f!=="pending"&&(f!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),f="connected"),f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),r.reason="pending",r;if(f==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),r.reason="connected",r;await ye(e);let d=await lt(e);if(!d&&(await ye(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await v(2e3),d=await lt(e)),!d))return console.log(" \u2717 Connect not found"),r.reason="button_not_found",r;r.method=d.method;let m=await tn(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),r.reason="wrong_target",r;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await v(4e3);let w=await Te(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await ye(e),await v(1e3);let b=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(b)try{await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),b),await v(500),await b.click().catch(()=>e.evaluate(p=>p.click(),b)),await v(2e3);let h=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(h){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),h),await v(3e3);let p=e.url();if(p.includes("/premium/")||p.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await v(3e3),r.reason="premium_required",r;if(await Te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.method="more_dropdown",r.withCustomMessage=!1,r;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await v(500),r.reason="premium_required",r}catch(h){return console.log(" More dropdown failed:",h.message),await e.keyboard.press("Escape").catch(()=>{}),r.reason="premium_required",r}else return console.log(" \u2717 No More button found \u2014 Premium required"),r.reason="premium_required",r}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await v(500),r.reason="email_required",r}let g=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!g&&!S){let w=await e.evaluate(()=>{let b=document.querySelector("#interop-outlet")?.shadowRoot;if(!b)return{addNote:!1,sendWithout:!1};let h=b.querySelector('button[aria-label="Add a note"]'),p=b.querySelector('button[aria-label="Send without a note"]');return{addNote:!!h,sendWithout:!!p}});if(w.addNote){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));g=b?.asElement?.()||null,g||await b.dispose().catch(()=>{})}if(w.sendWithout){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=b?.asElement?.()||null,S||await b.dispose().catch(()=>{})}}if(s){if(g&&o){if(console.log(" Adding personalized note..."),await g.click(),await v(1500),await e.$("div.modal-upsell")){let h=await Gr(e);return r.success=h,r.connectionSent=h,r.reason=h?"sent_without_note_upsell":"upsell_failed",r.withCustomMessage=!1,r}let b=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(b){let h=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),p=o.replace("{name}",h);await b.type(p,{delay:20}),await v(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(C=>C.click())}catch{console.log(" Click timeout, likely still sent")}return await v(3e3),console.log(" \u2713 Connection sent (with note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_with_note",r.withCustomMessage=!0,r.messageSent=p,r}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await v(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}else if(g&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await v(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}}else{console.log(" Sending without note (custom messages disabled)...");let w=S;if(w){try{await w.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await v(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await v(4e3)),await ye(e),await v(500);let b=await e.$$('button[id*="profile-overflow-action"]'),h=null;for(let p of b){let $=await e.evaluate(C=>{let A=C.getBoundingClientRect();return{visible:A.width>0&&A.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},p);if($.visible&&!$.inSticky){h=p;break}}!h&&b.length>0&&(h=b[b.length-1]);for(let p of b)p!==h&&await p.dispose().catch(()=>{});if(h)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),h),await v(500),await h.click().catch(()=>e.evaluate($=>$.click(),h)),await v(2e3);let p=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(p){console.log(" Found Connect in More dropdown, clicking..."),r.method="more_dropdown",await e.evaluate(R=>R.click(),p),await v(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await v(3e3),await Te(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r):(r.reason="premium_required",r);if(await Te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;let A=await e.$('button[aria-label="Send without a note"]');if(A){console.log(" Modal appeared via More dropdown, sending without note...");try{await A.evaluate(R=>R.click())}catch{}return await v(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(p){console.log(" More dropdown fallback failed:",p.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),r.reason="modal_failed",r}catch(u){console.error(` \u2717 Error: ${u.message}`),r.reason="error",r.error=u.message;let c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return r.fatal=!0,r;try{await e.goto("about:blank",{timeout:1e4}),await v(1e3)}catch{r.fatal=!0}return r}}async function vo(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:a=!1,delayBetweenProfiles:l=3e3,onProfileProcessed:r=null,excludeLocations:u=[],source:c="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
240
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${a?"View Only":`Connect (max ${i})`}`),a||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!a){let m=Ze();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let y=t[m];try{if(e.isClosed()){console.log(`
|
|
241
241
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
242
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let
|
|
242
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let g=Rn(y.profileUrl);if(g==="pending"||g==="connected"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl} \u2014 skipped (db: ${g})`),g==="pending"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,r&&await r(y,f,{success:!1,reason:g,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl}`);let S=null;if(a){let w=await en(e,y.profileUrl);w?(ve(y.profileUrl,{...w,source:c}),f.viewed++,S={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w,resolvedUrl:w.resolvedUrl}):(f.errors++,S={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=At();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(S=await nn(e,y.profileUrl,{message:o,useCustomMessage:s,excludeLocations:u,source:c,skipQuotaGate:!0}),S.success)f.connectionsSent++;else switch(S.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(S?.fatal){console.log(`
|
|
243
243
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(S?.reason==="error"){if(d++,d>=3){console.log(`
|
|
244
|
-
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(S&&S.reason&&(
|
|
245
|
-
=== 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}`),!a){let m=
|
|
246
|
-
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=
|
|
244
|
+
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(S&&S.reason&&(Dn(y.profileUrl,S.reason,{method:S.method,messageSent:S.messageSent,profileInfo:S.profileInfo}),S.resolvedUrl&&ft(y.profileUrl,S.resolvedUrl),Tn(y.profileUrl,{source:c||"funnel",jobId:y.jobId||y.fromJob?.jobId||null,jobTitle:y.fromJob?.title||null,jobCompany:y.fromJob?.company||null,action:S.reason})),r&&await r(y,f,S),m<t.length-1){let w=l+Math.random()*2e3;await v(w)}}if(console.log(`
|
|
245
|
+
=== 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}`),!a){let m=Ze();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}var Kr,ko=Je(async()=>{Ie();await Le();Kr={viewProfile:en,detectConnectionStatus:Te,findConnectButton:lt,clickConnectButton:tn,sendConnectionRequest:nn,runFunnel:vo,shouldExcludeLocation:St}});Ie();await Le();import"dotenv/config";import*as Ce from"fs";import*as K from"path";import{fileURLToPath as ns}from"url";var os=ns(import.meta.url),ss=K.dirname(K.dirname(os)),ot=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(ss,"market-research"),rs=K.join(ot,"scouted-jobs.json"),is=K.join(ot,"discovered-people.json"),as=K.join(ot,"visit-log.json"),Ri=K.join(ot,"companies.json"),ls=K.join(ot,"job-decisions.json");function mt(e){try{if(Ce.existsSync(e))return JSON.parse(Ce.readFileSync(e,"utf-8"))}catch{}return null}function Pn(){et=null,tt=null,nt=null,us=null,ke=null}var et=null;function Dt(){return et||(et=mt(rs)||{},et)}var tt=null;function Ln(){return tt||(tt=mt(ls)||{},tt)}var nt=null;function cs(){return nt||(nt=mt(is)||{},nt)}var us=null;var ke=null;function ds(){return ke||(ke=mt(as)||{visits:[]},Array.isArray(ke.visits)||(ke.visits=[]),ke)}function Fn(){let e=Dt(),t=cs(),n=Object.values(e),o=Object.values(t),s={};for(let d of n)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),a={};for(let d of n)for(let m of d.techStack||[])a[m]=(a[m]||0)+1;let l=Object.entries(a).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),r=ds(),u=new Date().toISOString().slice(0,10),c=r.visits.filter(d=>d.date.startsWith(u)).length,f=new Set(r.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:l,totalVisited:f,todayVisited:c,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}await Le();var fs=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),ms=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Un=["vancouver","british columbia"],ps=["canada","montreal","quebec","alberta","calgary","ottawa"],gs=["toronto","ontario"],hs=["india","pakistan","nigeria","philippines"];function ys(e,t={}){let n=0,o=(e.techStack||[]).map(c=>c.toLowerCase()),s=0,i=0;for(let c of o)fs.has(c)&&s++,ms.has(c)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let c=ws(e.salary);c&&(c>=15e4?n+=20:c>=12e4?n+=15:c>=1e5?n+=10:c>=8e4?n+=5:c>=100&&c<1e3?n+=15:c>=70&&c<1e3&&(n+=10))}let a=(e.location||"").toLowerCase(),l=/remote/i.test(a)||e.workplaceType==="remote";hs.some(c=>a.includes(c))?n-=30:l&&/united states|usa|\bus\b/i.test(a)?n+=25:l&&Un.some(c=>a.includes(c))?n+=22:l?n+=20:Un.some(c=>a.includes(c))?n+=18:ps.some(c=>a.includes(c))?n+=10:gs.some(c=>a.includes(c))&&(n+=5),e.isEasyApply&&(n+=5);let r=(e.seniority||"").toLowerCase();r.includes("senior")||r.includes("lead")||r.includes("staff")?n+=10:r.includes("mid")?n+=5:(r.includes("entry")||r.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let u=new Set(e.jobTags||[]);return u.has("managerial")?n+=8:u.has("senior-ic")&&(n+=5),u.has("junior")&&(n-=15),u.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function qn(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=Dt(),s=J(),i=new Set,a=new Set;for(let[f,d]of Object.entries(s))d.connectionStatus==="connected"&&i.add(f);let l={connectedRecruiters:i,conversationRecruiters:a},r=Ln(),u=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([f,d])=>{if(typeof d!="object"||n&&!d.isEasyApply||d.applied)return!1;let m=r[f];return!(m&&u.has(m.status))}).map(([f,d])=>({jobId:f,score:ys(d,l),job:d})).sort((f,d)=>{if(d.score!==f.score)return d.score-f.score;let m=f.job.scoutedAt||f.job.postedTime||"";return(d.job.scoutedAt||d.job.postedTime||"").localeCompare(m)}).slice(0,e)}function ws(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await Ye();import $s from"puppeteer";import{addExtra as ks}from"puppeteer-extra";import Cs from"puppeteer-extra-plugin-stealth";Ie();await Ye();import Bn from"fs";import bs from"path";var Ss="cookies.json";function vs(){let e=process.env.ILML_SCOPE_DIR;return e?bs.join(e,"plugins-state","linkedin","cookies.json"):Ss}function pt(){let e=vs();if(!Bn.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Bn.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.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}var Vn=ks($s);Vn.use(Cs());async function Wn(){let e=await Vn.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
|
|
246
|
+
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=pt();await n.setCookie(...o),console.log(" Browser launched, cookies loaded.")}catch(o){console.error(`
|
|
247
247
|
[!] ${o.message}
|
|
248
|
-
`),await e.close(),process.exit(1)}return{browser:e,page:n}}async function Rt(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector(".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:15e3})}catch{console.warn(" Inbox container not found via known selectors, proceeding..."),await $(3e3)}console.log(" Inbox loaded.")}async function Hn(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let a=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!a)continue;let i=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(i)||/^\s*Promoted\b/i.test(i))continue;let c=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",f=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,d,m;if(i.startsWith("You:"))d="me",m=i.slice(4).trim();else{let p=a.split(" ")[0];if(i.startsWith(a+":")||i.startsWith(p+":")){d="them";let S=i.indexOf(":");m=i.slice(S+1).trim()}else d="them",m=i}let y=s.getBoundingClientRect();o.push({name:a,lastMessagePreview:m,lastMessageTime:c,unread:f,lastMessageBy:d,x:y.x+y.width/2,y:y.y+y.height/2})}return o});for(let n of t)n.lastMessageTime=vt(n.lastMessageTime)||n.lastMessageTime;return t}async function Dt(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function vs(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let r=document.querySelector(s);if(r){let a=r.textContent?.trim()?.replace(/\s+/g," ");if(a&&a.length>1&&a.length<100&&!t.test(a))return a}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let r=s.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function It(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function Fn(e,t){let n=await vs(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=n.toLowerCase();return{match:r.includes(o)||s.some(l=>r.includes(l)),headerName:n}}async function ft(e,t){let n=t.split(" ")[0],o=8e3,s=500,r=0;for(;r<o;){let{match:i,headerName:u}=await Fn(e,t);if(i)return await $(500),{verified:!0,headerName:u};let c=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),d=Array.from(f).map(y=>y.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:d,msgCount:m}});if(c.msgCount>0&&c.allSenders.some(d=>d.toLowerCase().includes(n.toLowerCase())))return await $(300),{verified:!0,headerName:n};await $(s),r+=s}let{match:a,headerName:l}=await Fn(e,t);return a?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function $s(e){let n=0,o=0;for(let s=0;s<50;s++){let r=await e.evaluate(()=>{let a=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!a){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(a=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!a)return{found:!1};let l=a.querySelectorAll("li.msg-s-message-list__event").length;return a.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(a.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!r.found||r.atTop)break;if(await $(800),r.msgCount===n){if(o++,o>=3)break}else o=0;n=r.msgCount}}async function Mt(e,{scrollUp:t=!0}={}){t&&await $s(e);let n=await e.evaluate(()=>{let o=[],s="",r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let c=document.querySelector(".msg-overlay-conversation-bubble");c&&(r=c.querySelector(".msg-s-message-list-container")||c.querySelector(".msg-s-message-list"))}if(!r)return o;let a=r.querySelectorAll("li.msg-s-message-list__event");if(a.length===0){let c=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");c&&(a=c.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(c){let f=c.getAttribute("data-event-urn");if(!f)return null;let d=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!d)return null;try{let y=atob(d[1]).match(/^(\d{13})/);if(!y)return null;let p=Number(y[1]);if(p>14200704e5&&p<20512224e5)return p}catch{}return null}let i="";function u(c,f,d){let m=l(c),p=c.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",S=c.querySelector(".msg-s-event-listitem__message-bubble");if(!S)return null;let w=S.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!w)return null;let b=m?new Date(m).toISOString():d?`${d} ${p}`.trim():p;return{sender:f,text:w,time:b}}for(let c of a){let f=c.querySelector("time.msg-s-message-list__time-heading");f&&(i=f.textContent?.trim()||i);let d=c.querySelectorAll(".msg-s-message-group");if(d.length>0)for(let m of d){let y=m.querySelector(".msg-s-message-group__name");y&&(s=y.textContent?.trim()||s);let p=s||"Unknown",S=m.querySelectorAll(".msg-s-event-listitem");for(let w of S){let b=u(w,p,i);b&&o.push(b)}}else{let m=c.querySelectorAll(".msg-s-event-listitem");for(let y of m){let p=y.querySelector(".msg-s-message-group__name");p&&(s=p.textContent?.trim()||s);let w=u(y,s||"Unknown",i);w&&o.push(w)}}}if(o.length===0){let c=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of c){let d=f.textContent?.trim();d&&o.push({sender:"",text:d,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=vt(o.time)||o.time);return n}function Ot(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(u=>u.length>1),r=[...new Set(e.map(u=>u.sender).filter(u=>u&&u!=="Unknown"))],a=r.some(u=>{let c=u.toLowerCase();return c.includes(o)||s.some(f=>c.includes(f))}),l=z.toLowerCase().split(/\s+/),i=r.every(u=>{let c=u.toLowerCase();return l.some(f=>c.includes(f))});if(a)return!0;if(i){for(let u of e){let f=(u.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let d=f[1].toLowerCase();if(d!=="there"&&d!=="all"&&!(s.some(y=>y===d)||d===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let u=n.map(f=>f.toLowerCase());if(r.some(f=>{let d=f.toLowerCase();return u.some(m=>d.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${r.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${r.join(", ")})`),!1}function je(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Nt(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=d=>je(d.sender)+"||"+je(d.text),o=new Set(t.map(n)),s=new Set(e.map(n)),r=e.filter(d=>De.has(d.status)?!1:!o.has(n(d))),a=t.filter(d=>!s.has(n(d))),l=t.filter(d=>s.has(n(d))),i=e.filter(d=>De.has(d.status)),u=[...r,...l,...a],c=[];for(let d of u){let m=je(d.text),y=je(d.sender),p=!1;for(let S=0;S<c.length;S++){let w=c[S];if(je(w.sender)!==y)continue;let b=je(w.text);if(m.length>b.length&&m.endsWith(b)){p=!0;break}if(b.length>m.length&&b.endsWith(m)){c[S]=d,p=!0;break}}p||c.push(d)}return[...c,...i]}async function Jn(e,t){await Rt(e),await $(2500),await e.evaluate(()=>{let l=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let i of l){let u=document.querySelector(i);if(u){u.scrollTop=0;return}}}),await $(500);async function n(){return e.evaluate(l=>{let i=document.querySelectorAll(".msg-conversation-listitem");for(let u of i)if(u.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===l){let d=u.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t)}let o=await n(),s=50,r=-1,a=0;for(let l=0;l<s&&!o;l++){let i=await Dt(e);if(!i)break;if(i.scrollTop===r){if(a++,a>=2)break}else a=0,r=i.scrollTop;await $(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await $(3e3),ft(e,t)):{verified:!1,headerName:null}}async function jt(e,t){let n=await e.evaluate(a=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let i of l)if(i.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===a){let f=i.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await $(3e3);let a=await ft(e,t);if(a.verified)return a}let o=gn(t),s=o!==t?[t,o]:[t];for(let a of s)if(await Un(e,a,t)){let i=await ft(e,t);if(i.verified)return i}let r=hn(o);if(r!==o&&r.length>0&&await Un(e,r,t,{requireUnique:!0})){let l=await ft(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Un(e,t,n,o={}){let{requireUnique:s=!1}=o,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await $(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await $(300),await r.type(t,{delay:30}),await $(500),await e.keyboard.press("Enter"),await $(3500);let a=await e.evaluate((l,i)=>{let u=l.split(" ")[0].toLowerCase(),c=l.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),d=[],m=[];for(let p of f){let w=p.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",b=w.toLowerCase();if(b.includes(u)){let g=p.getBoundingClientRect();if(g.height>0){let h=w.includes(",")||/\d+ other/.test(w),k=b===c?3:b.includes(c)?2:1,C={text:w,isGroup:h,score:k,x:g.x+g.width/2,y:g.y+g.height/2};h?m.push(C):d.push(C)}}}d.sort((p,S)=>S.score-p.score);let y=[...d,...m];return i&&y.length!==1?null:d[0]||m[0]||null},n,s);return a?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(a.x,a.y),!0):!1}async function pe(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await $(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await $(1e3))}await Je();function Lt(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(i=>!De.has(i.status)),r=Rs(t,e.profileUrl,n),a=Ft(s,t);if(e.lastMessageBy=a,e.conversationStatus=a==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let i=ks(s,t,r);i&&(e.category=i,e.categorySource=e.categorySource||"message_content")}if(e.situation=Cs(s,a,t),s.length>0){let i=s[s.length-1];e.lastMessageTime=i.time}if(s.length>0&&!e.initiatedBy){let i=s[0];i.sender===z?e.initiatedBy="us":i.sender!=="Unknown"&&i.sender!==""&&(e.initiatedBy="them")}e.engagement=Gn(s,t),e.personContext=As(r),e.summary=Es(e,t,r),e.autoTags=_s(e,t,r);let l=xs(e);return e.actionNeeded=l.action,e.actionDetail=l.detail,e.suggestedPriority=Ts(e),e}var Wn={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};function ks(e,t,n){if(!e||e.length===0)return n?.title?Pt(n.title):null;let o=e.filter(s=>s.sender!==z&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,r]of Object.entries(Wn))if(r.theirMessages){for(let a of r.theirMessages)if(a.test(o))return s}if(n?.title){let s=Pt(n.title);if(s)return s}return null}function Pt(e){if(!e)return null;for(let[t,n]of Object.entries(Wn))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}var Vn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i;function Cs(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return Vn.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(r=>r.sender!==z&&r.sender!=="Unknown");return Vn.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Ft(e,t){if(!e||e.length===0)return"them";let n=[...e].map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,r)=>r.t-s.t).map(s=>s.m),o=n.length>0?n:[...e].reverse();for(let s of o){let r=s.sender;if(r===z)return"me";if(r!=="Unknown"&&r!=="")return"them"}return"them"}function Es(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],r=e.category,a=n?.title,l=n?.company,i=n?.location;r==="recruiter"&&l?s.push(`Recruiter from ${l}`):r==="hiring_manager"&&l?s.push(`Hiring manager at ${l}`):r==="founder"&&l?s.push(`Founder of ${l}`):r&&a?s.push(`${Ut(r)}: ${Pe(a,40)}`):a?s.push(Pe(a,50)):s.push(t.split(" ")[0]);let u=o.filter(y=>y.sender!==z&&y.sender!=="Unknown").map(y=>y.text).join(" "),c=Ds(u),f=Is(u),d=Ms(u),m=[];return c&&m.push(c),d&&d!==i&&m.push(d),f&&m.push(f),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function _s(e,t,n){let o=[],s=(e.messages||[]).filter(u=>!De.has(u.status)),r=s.map(u=>u.text).join(" "),a=s.filter(u=>u.sender!==z&&u.sender!=="Unknown").map(u=>u.text).join(" "),l=Yn(a,n?.location);o.push(...l),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(r)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(r)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(r)&&o.push("remote"),/\b(hybrid)\b/i.test(r)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(r)&&o.push("onsite"),/\b(java)\b/i.test(r)&&!/javascript/i.test(r)&&o.push("java"),/\b(python)\b/i.test(r)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(r)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(r)&&o.push("backend"),/\b(full.?stack)\b/i.test(r)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(r)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(r)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(r)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(r)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(r)&&o.push("has-salary");let i=e.engagement||Gn(s,t);return i.messageCount>=6&&o.push("active-thread"),i.theirCount===0&&i.ourCount>0&&o.push("no-response"),i.ourCount===0&&i.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(u=>He.has(u.status))&&o.push("has-draft"),[...new Set(o)]}function Yn(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],r=(e+" "+(t||"")).toLowerCase();for(let a of o)r.includes(a)&&n.push(a.replace(/\s+/g,"-"));for(let[a,l]of s)r.includes(a)&&n.push(l);return n}function xs(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&nt(e.lastMessagePreview)===nt(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(r=>He.has(r.status));return s?s.status===V.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Ut(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Gn(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,s=0,r=!1,a=!1,l=e.map(i=>i.text).join(" ");for(let i of e)i.sender===z?n++:i.sender==="Unknown"||i.sender===""?s++:o++;return r=/\b(job|role|position|opening)\b/i.test(l),a=/\$[\d,]+|\d+k|\d+\/hr/i.test(l),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:r,hasSalary:a}}function As(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Ts(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function Rs(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function nt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Ut(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Pe(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Ds(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function Is(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function Ms(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function zn(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Pt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Os(e),e.personSummary=Ns(e),e.personAutoTags=js(e);let n=Ps(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Ls(e)),e}function Os(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function Ns(e){let t=[],n=e.category,o=e.title,s=e.company,r=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${Pe(o,40)} at ${Pe(s,30)}`):o?t.push(Pe(o,50)):e.name&&t.push(e.name.split(" ")[0]),r&&t.push(r),e.connectionDate){let a=new Date(e.connectionDate);if(!isNaN(a)){let l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${l[a.getMonth()]} ${a.getDate()}`)}}if(e.jobCount>0){let a=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(a+=` (last: ${Pe(e.lastJobTitle,30)}`,e.lastJobDate){let l=new Date(e.lastJobDate);isNaN(l)||(a+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][l.getMonth()]} ${l.getDate()}`)}a+=")"}t.push(a)}return t.join(". ").replace(/\.\./g,".")||null}function js(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=Yn("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function Ps(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Ut(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Ls(e){let t=e.category;if(!t)return null;let n=Fs(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function Fs(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}import"dotenv/config";import*as Z from"fs";import*as ge from"path";import{fileURLToPath as Vs}from"url";import"dotenv/config";import{createGraphClient as Us,resolveToken as qs}from"@ilivemylife/graph-sdk";import{config as Bs}from"dotenv";Bs();var Kn=qs()||process.env.TOKEN;Kn||(console.error(`
|
|
248
|
+
`),await e.close(),process.exit(1)}return{browser:e,page:n}}async function It(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await v(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector(".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:15e3})}catch{console.warn(" Inbox container not found via known selectors, proceeding..."),await v(3e3)}console.log(" Inbox loaded.")}async function Yn(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let a=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!a)continue;let r=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(r)||/^\s*Promoted\b/i.test(r))continue;let c=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",f=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,d,m;if(r.startsWith("You:"))d="me",m=r.slice(4).trim();else{let g=a.split(" ")[0];if(r.startsWith(a+":")||r.startsWith(g+":")){d="them";let S=r.indexOf(":");m=r.slice(S+1).trim()}else d="them",m=r}let y=s.getBoundingClientRect();o.push({name:a,lastMessagePreview:m,lastMessageTime:c,unread:f,lastMessageBy:d,x:y.x+y.width/2,y:y.y+y.height/2})}return o});for(let n of t)n.lastMessageTime=Ct(n.lastMessageTime)||n.lastMessageTime;return t}async function Mt(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function Es(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let i=document.querySelector(s);if(i){let a=i.textContent?.trim()?.replace(/\s+/g," ");if(a&&a.length>1&&a.length<100&&!t.test(a))return a}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function Ot(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function Hn(e,t){let n=await Es(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(l=>i.includes(l)),headerName:n}}async function gt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:r,headerName:u}=await Hn(e,t);if(r)return await v(500),{verified:!0,headerName:u};let c=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),d=Array.from(f).map(y=>y.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:d,msgCount:m}});if(c.msgCount>0&&c.allSenders.some(d=>d.toLowerCase().includes(n.toLowerCase())))return await v(300),{verified:!0,headerName:n};await v(s),i+=s}let{match:a,headerName:l}=await Hn(e,t);return a?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function _s(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let a=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!a){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(a=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!a)return{found:!1};let l=a.querySelectorAll("li.msg-s-message-list__event").length;return a.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(a.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!i.found||i.atTop)break;if(await v(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function Nt(e,{scrollUp:t=!0}={}){t&&await _s(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let c=document.querySelector(".msg-overlay-conversation-bubble");c&&(i=c.querySelector(".msg-s-message-list-container")||c.querySelector(".msg-s-message-list"))}if(!i)return o;let a=i.querySelectorAll("li.msg-s-message-list__event");if(a.length===0){let c=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");c&&(a=c.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(c){let f=c.getAttribute("data-event-urn");if(!f)return null;let d=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!d)return null;try{let y=atob(d[1]).match(/^(\d{13})/);if(!y)return null;let g=Number(y[1]);if(g>14200704e5&&g<20512224e5)return g}catch{}return null}let r="";function u(c,f,d){let m=l(c),g=c.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",S=c.querySelector(".msg-s-event-listitem__message-bubble");if(!S)return null;let w=S.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!w)return null;let b=m?new Date(m).toISOString():d?`${d} ${g}`.trim():g;return{sender:f,text:w,time:b}}for(let c of a){let f=c.querySelector("time.msg-s-message-list__time-heading");f&&(r=f.textContent?.trim()||r);let d=c.querySelectorAll(".msg-s-message-group");if(d.length>0)for(let m of d){let y=m.querySelector(".msg-s-message-group__name");y&&(s=y.textContent?.trim()||s);let g=s||"Unknown",S=m.querySelectorAll(".msg-s-event-listitem");for(let w of S){let b=u(w,g,r);b&&o.push(b)}}else{let m=c.querySelectorAll(".msg-s-event-listitem");for(let y of m){let g=y.querySelector(".msg-s-message-group__name");g&&(s=g.textContent?.trim()||s);let w=u(y,s||"Unknown",r);w&&o.push(w)}}}if(o.length===0){let c=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of c){let d=f.textContent?.trim();d&&o.push({sender:"",text:d,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Ct(o.time)||o.time);return n}function jt(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(u=>u.length>1),i=[...new Set(e.map(u=>u.sender).filter(u=>u&&u!=="Unknown"))],a=i.some(u=>{let c=u.toLowerCase();return c.includes(o)||s.some(f=>c.includes(f))}),l=z.toLowerCase().split(/\s+/),r=i.every(u=>{let c=u.toLowerCase();return l.some(f=>c.includes(f))});if(a)return!0;if(r){for(let u of e){let f=(u.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let d=f[1].toLowerCase();if(d!=="there"&&d!=="all"&&!(s.some(y=>y===d)||d===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let u=n.map(f=>f.toLowerCase());if(i.some(f=>{let d=f.toLowerCase();return u.some(m=>d.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Fe(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Pt(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=d=>Fe(d.sender)+"||"+Fe(d.text),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(d=>Me.has(d.status)?!1:!o.has(n(d))),a=t.filter(d=>!s.has(n(d))),l=t.filter(d=>s.has(n(d))),r=e.filter(d=>Me.has(d.status)),u=[...i,...l,...a],c=[];for(let d of u){let m=Fe(d.text),y=Fe(d.sender),g=!1;for(let S=0;S<c.length;S++){let w=c[S];if(Fe(w.sender)!==y)continue;let b=Fe(w.text);if(m.length>b.length&&m.endsWith(b)){g=!0;break}if(b.length>m.length&&b.endsWith(m)){c[S]=d,g=!0;break}}g||c.push(d)}return[...c,...r]}async function Gn(e,t){await It(e),await v(2500),await e.evaluate(()=>{let l=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let r of l){let u=document.querySelector(r);if(u){u.scrollTop=0;return}}}),await v(500);async function n(){return e.evaluate(l=>{let r=document.querySelectorAll(".msg-conversation-listitem");for(let u of r)if(u.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===l){let d=u.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t)}let o=await n(),s=50,i=-1,a=0;for(let l=0;l<s&&!o;l++){let r=await Mt(e);if(!r)break;if(r.scrollTop===i){if(a++,a>=2)break}else a=0,i=r.scrollTop;await v(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await v(3e3),gt(e,t)):{verified:!1,headerName:null}}async function Lt(e,t){let n=await e.evaluate(a=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let r of l)if(r.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===a){let f=r.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await v(3e3);let a=await gt(e,t);if(a.verified)return a}let o=wn(t),s=o!==t?[t,o]:[t];for(let a of s)if(await Jn(e,a,t)){let r=await gt(e,t);if(r.verified)return r}let i=bn(o);if(i!==o&&i.length>0&&await Jn(e,i,t,{requireUnique:!0})){let l=await gt(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Jn(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await v(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await v(300),await i.type(t,{delay:30}),await v(500),await e.keyboard.press("Enter"),await v(3500);let a=await e.evaluate((l,r)=>{let u=l.split(" ")[0].toLowerCase(),c=l.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),d=[],m=[];for(let g of f){let w=g.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",b=w.toLowerCase();if(b.includes(u)){let h=g.getBoundingClientRect();if(h.height>0){let p=w.includes(",")||/\d+ other/.test(w),$=b===c?3:b.includes(c)?2:1,C={text:w,isGroup:p,score:$,x:h.x+h.width/2,y:h.y+h.height/2};p?m.push(C):d.push(C)}}}d.sort((g,S)=>S.score-g.score);let y=[...d,...m];return r&&y.length!==1?null:d[0]||m[0]||null},n,s);return a?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(a.x,a.y),!0):!1}async function pe(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await v(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await v(1e3))}await Ye();await Le();function Ut(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(r=>!Me.has(r.status)),i=Os(t,e.profileUrl,n),a=qt(s,t);if(e.lastMessageBy=a,e.conversationStatus=a==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let r=xs(s,t,i);r&&(e.category=r,e.categorySource=e.categorySource||"message_content")}if(e.situation=As(s,a,t),s.length>0){let r=s[s.length-1];e.lastMessageTime=r.time}if(s.length>0&&!e.initiatedBy){let r=s[0];r.sender===z?e.initiatedBy="us":r.sender!=="Unknown"&&r.sender!==""&&(e.initiatedBy="them")}e.engagement=Xn(s,t),e.personContext=Is(i),e.summary=Ts(e,t,i),e.autoTags=Rs(e,t,i);let l=Ds(e);return e.actionNeeded=l.action,e.actionDetail=l.detail,e.suggestedPriority=Ms(e),e}var Kn={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};function xs(e,t,n){if(!e||e.length===0)return n?.title?Ft(n.title):null;let o=e.filter(s=>s.sender!==z&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,i]of Object.entries(Kn))if(i.theirMessages){for(let a of i.theirMessages)if(a.test(o))return s}if(n?.title){let s=Ft(n.title);if(s)return s}return null}function Ft(e){if(!e)return null;for(let[t,n]of Object.entries(Kn))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}var zn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i;function As(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return zn.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(i=>i.sender!==z&&i.sender!=="Unknown");return zn.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function qt(e,t){if(!e||e.length===0)return"them";let n=[...e].map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),o=n.length>0?n:[...e].reverse();for(let s of o){let i=s.sender;if(i===z)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function Ts(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,a=n?.title,l=n?.company,r=n?.location;i==="recruiter"&&l?s.push(`Recruiter from ${l}`):i==="hiring_manager"&&l?s.push(`Hiring manager at ${l}`):i==="founder"&&l?s.push(`Founder of ${l}`):i&&a?s.push(`${Bt(i)}: ${Ue(a,40)}`):a?s.push(Ue(a,50)):s.push(t.split(" ")[0]);let u=o.filter(y=>y.sender!==z&&y.sender!=="Unknown").map(y=>y.text).join(" "),c=Ns(u),f=js(u),d=Ps(u),m=[];return c&&m.push(c),d&&d!==r&&m.push(d),f&&m.push(f),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function Rs(e,t,n){let o=[],s=(e.messages||[]).filter(u=>!Me.has(u.status)),i=s.map(u=>u.text).join(" "),a=s.filter(u=>u.sender!==z&&u.sender!=="Unknown").map(u=>u.text).join(" "),l=Qn(a,n?.location);o.push(...l),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let r=e.engagement||Xn(s,t);return r.messageCount>=6&&o.push("active-thread"),r.theirCount===0&&r.ourCount>0&&o.push("no-response"),r.ourCount===0&&r.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(u=>We.has(u.status))&&o.push("has-draft"),[...new Set(o)]}function Qn(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let a of o)i.includes(a)&&n.push(a.replace(/\s+/g,"-"));for(let[a,l]of s)i.includes(a)&&n.push(l);return n}function Ds(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&st(e.lastMessagePreview)===st(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(i=>We.has(i.status));return s?s.status===V.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Bt(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Xn(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,s=0,i=!1,a=!1,l=e.map(r=>r.text).join(" ");for(let r of e)r.sender===z?n++:r.sender==="Unknown"||r.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(l),a=/\$[\d,]+|\d+k|\d+\/hr/i.test(l),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:a}}function Is(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Ms(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function Os(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let s=je(n,t,e);if(n[s])return n[s]}if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function st(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Bt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ue(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Ns(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function js(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function Ps(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function Zn(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Ft(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Ls(e),e.personSummary=Fs(e),e.personAutoTags=Us(e);let n=qs(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Bs(e)),e}function Ls(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function Fs(e){let t=[],n=e.category,o=e.title,s=e.company,i=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${Ue(o,40)} at ${Ue(s,30)}`):o?t.push(Ue(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let a=new Date(e.connectionDate);if(!isNaN(a)){let l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${l[a.getMonth()]} ${a.getDate()}`)}}if(e.jobCount>0){let a=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(a+=` (last: ${Ue(e.lastJobTitle,30)}`,e.lastJobDate){let l=new Date(e.lastJobDate);isNaN(l)||(a+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][l.getMonth()]} ${l.getDate()}`)}a+=")"}t.push(a)}return t.join(". ").replace(/\.\./g,".")||null}function Us(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=Qn("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function qs(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Bt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Bs(e){let t=e.category;if(!t)return null;let n=Hs(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function Hs(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}import"dotenv/config";import*as Z from"fs";import*as ge from"path";import{fileURLToPath as zs}from"url";import"dotenv/config";import{createGraphClient as Js,resolveToken as Vs}from"@ilivemylife/graph-sdk";import{config as Ws}from"dotenv";Ws();var eo=Vs()||process.env.TOKEN;eo||(console.error(`
|
|
249
249
|
[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.
|
|
250
250
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
251
251
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
252
|
-
`),process.exit(1));var
|
|
252
|
+
`),process.exit(1));var to=Js({token:eo});function Ys(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),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Gs({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",a=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${Ys(s)}`:"",r=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${r} \u2014 ${a}${l}`}async function no({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let a=process.env.NODE_RUN_REPORTS;if(!a||!Array.isArray(o)||o.length===0)return;let r=`**${Gs({scriptName:e,mode:t,status:n,error:s,duration:i})}**
|
|
253
253
|
|
|
254
254
|
${o.join(`
|
|
255
|
-
`)}`;try{await
|
|
256
|
-
`)}import"dotenv/config";import*as
|
|
255
|
+
`)}`;try{await to.addMessage(a,r)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Ks=zs(import.meta.url),Qs=ge.dirname(ge.dirname(Ks)),Ht=process.env.DATA_DIR?ge.resolve(process.env.DATA_DIR,"collected-profiles"):ge.join(Qs,"collected-profiles"),Jt=ge.join(Ht,"run-log.json");function Xs(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";Z.writeFileSync(o,n);for(let s=0;s<3;s++)try{Z.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw i}}function ht(){try{if(!Z.existsSync(Jt))return{runs:[]};let e=JSON.parse(Z.readFileSync(Jt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function oo(e){Z.existsSync(Ht)||Z.mkdirSync(Ht,{recursive:!0});try{Xs(Jt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function yt(e,t="default"){let n=ht();for(let a of n.runs)a.status==="running"&&(a.status="interrupted",a.result="interrupted",a.timestamp&&(a.duration=Date.now()-new Date(a.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(a=>new Date(a.timestamp).getTime()>i),oo(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function qe(e,t,n=null,o=null){if(!e)return;let s=null;try{let a=ht(),l=a.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,s=l.duration;else{let r=a.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());r&&(r.status=t,r.result=t,r.duration=Date.now()-e.startTime,r.stats=n,r.error=o,s=r.duration)}oo(a)}catch(a){console.error(`[runLog] Failed to end run: ${a.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let a=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";no({scriptName:e.script,mode:e.mode,status:a,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}function Zs(){let e=new Date().toISOString().slice(0,10),t=ht(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let s=n[o.script];s.total++,o.status==="success"?s.success++:o.status==="error"?s.error++:o.status==="interrupted"?s.interrupted++:o.status==="partial"?s.partial++:o.status==="running"&&s.running++,s.lastRun=o}return n}function er(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:s===1?"yesterday":`${s} days ago`}function so(){let e=["sync-all","messages","funnel","sync","apply"],t=ht(),n=Zs(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let i of e){let a=t.runs.filter(g=>g.script===i),l=[...a].reverse().find(g=>g.status==="success"),r=a[a.length-1],u=l||r,c=u?er(u.timestamp):"never",d=(u?Math.floor((Date.now()-new Date(u.timestamp).getTime())/864e5):1/0)>1?" \u26A0":u?.status==="error"?" \u2717":" \u2713",m="";if(u?.stats){let g=u.stats,S=Object.entries(g).filter(([,w])=>typeof w=="number"&&w>0).slice(0,3).map(([w,b])=>`${b} ${w}`);S.length&&(m=` (${S.join(", ")})`)}let y=u?.duration?` ${Math.round(u.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${c.padEnd(16)}${y}${m}${d}`)}let s=Object.entries(n);if(s.length>0){o.push("");for(let[i,a]of s){let l=[];a.success&&l.push(`${a.success} success`),a.error&&l.push(`${a.error} error`),a.interrupted&&l.push(`${a.interrupted} interrupted`),a.running&&l.push(`${a.running} running`),o.push(` Today: ${i} \xD7${a.total} (${l.join(", ")})`)}}return o.push("\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"),o.join(`
|
|
256
|
+
`)}import"dotenv/config";import*as _ from"fs";import*as Xt from"os";import*as N from"path";import{fileURLToPath as Cr}from"url";var Yt={};De(Yt,{NAME:()=>nr,VERSION:()=>tr,up:()=>rr});import*as ee from"fs";import*as wt from"path";var tr=1,nr="normalize-jobs-and-questions",or=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],sr=50;function Vt(e){return ee.existsSync(e)?JSON.parse(ee.readFileSync(e,"utf-8")):null}function Wt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ee.writeFileSync(o,n)}catch(s){try{ee.unlinkSync(o)}catch{}throw s}try{ee.renameSync(o,e)}catch(s){try{ee.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function rr(e,t){let n=wt.join(e,"jobs.json"),o=wt.join(t,"scouted-jobs.json"),s=wt.join(e,"application-questions.json"),i=Vt(n)||{},a=Vt(o)||{},l=0,r=[];for(let c of Object.keys(i)){if(!a[c])continue;let f=a[c],d=i[c];for(let m of or)f[m]!=null&&d[m]==null&&(d[m]=f[m]);r.push(c),l++}l>0?(Wt(n,i),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Vt(s);if(u&&Array.isArray(u.applications)){let c={},f=0;for(let d of u.applications){let m=d.jobId||"unknown";c[m]||(c[m]={applications:[]});let y=(d.questions||[]).map(g=>{let S={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=sr?S.options=g.options:(S.optionsOmitted=!0,f++)),g.page&&(S.page=g.page),g.wasPreFilled&&(S.wasPreFilled=!0),g.wasRetry&&(S.wasRetry=!0),S});c[m].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||y.length,questions:y})}Wt(s,c),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(r.length>0){for(let c of r)delete a[c];Wt(o,a),console.log(` Phase 3: Removed ${r.length} merged entries from scouted-jobs.json (${Object.keys(a).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Gt={};De(Gt,{NAME:()=>ar,VERSION:()=>ir,up:()=>ur});import*as te from"fs";import*as ro from"path";var ir=2,ar="reset-unread-flags";function lr(e){return te.existsSync(e)?JSON.parse(te.readFileSync(e,"utf-8")):null}function cr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{te.writeFileSync(o,n)}catch(s){try{te.unlinkSync(o)}catch{}throw s}try{te.renameSync(o,e)}catch(s){try{te.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function ur(e){let t=ro.join(e,"conversations.json"),n=lr(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}cr(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var zt={};De(zt,{NAME:()=>fr,VERSION:()=>dr,up:()=>yr});import*as ne from"fs";import*as io from"path";var dr=3,fr="recompute-last-message-by",mr=new Set(["draft","confirmed","rejected","needs_review"]);function pr(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function gr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(s){try{ne.unlinkSync(o)}catch{}throw s}try{ne.renameSync(o,e)}catch(s){try{ne.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function hr(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!mr.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,a)=>a.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let a=i.sender;if(a===t)return"me";if(a!=="Unknown"&&a!=="")return"them"}return"them"}async function yr(e){let t=io.join(e,"conversations.json"),n=pr(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,i=0,a=0;for(let l of Object.keys(n)){let r=n[l];if(!r||typeof r!="object")continue;Object.prototype.hasOwnProperty.call(r,"_cardSynced")&&(delete r._cardSynced,i++);let u=Array.isArray(r.messages)?r.messages:[],c=hr(u,o),f=c==="me"?"awaiting_reply":"unanswered_by_us";r.lastMessageBy!==c&&a++,r.lastMessageBy=c,r.conversationStatus=f,s++}if(s===0){console.log(" No conversations to recompute.");return}gr(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${a} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Kt={};De(Kt,{NAME:()=>br,VERSION:()=>wr,up:()=>kr});import*as oe from"fs";import*as ao from"path";var wr=4,br="split-connection-timestamps",Sr=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function vr(e){if(!oe.existsSync(e))return null;let t=oe.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function $r(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(s){try{oe.unlinkSync(o)}catch{}throw s}try{oe.renameSync(o,e)}catch(s){try{oe.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function kr(e){let t=ao.join(e,"people.json"),n=vr(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let i of Object.keys(n)){let a=n[i];!a||typeof a!="object"||(s++,Sr.has(a.connectionStatus)&&a.connectionDate&&!a.requestedConnectionAt&&(a.requestedConnectionAt=a.connectionDate,a.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}$r(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Le();var Er=Cr(import.meta.url),_r=N.dirname(Er),xr=N.dirname(N.dirname(_r));function Ar(e){return e&&(e==="~"?Xt.homedir():e.startsWith("~/")||e.startsWith("~\\")?N.join(Xt.homedir(),e.slice(2)):e)}var ae=process.env.DATA_DIR?N.resolve(Ar(process.env.DATA_DIR)):xr,_e=N.join(ae,"collected-profiles"),xe=N.join(ae,"market-research"),Y=N.join(ae,".schema-version"),lo=[N.join(_e,".schema-version"),N.join(xe,".schema-version")],he=4,ue=[{version:1,module:Yt},{version:2,module:Gt},{version:3,module:zt},{version:4,module:Kt}];(function(){ue.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of ue){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ue.length?ue[ue.length-1].version:0;if(n!==he)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${he}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ue.length;o++){let s=o+1;if(ue[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${ue[o].version}`)}})();function mo(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
257
257
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
258
|
-
`),process.exit(1));try{
|
|
259
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
260
|
-
`),process.exit(1))}let e;try{e=
|
|
261
|
-
[FATAL] DATA_DIR (${
|
|
258
|
+
`),process.exit(1));try{_.mkdirSync(ae,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
259
|
+
[FATAL] Cannot create DATA_DIR (${ae}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
260
|
+
`),process.exit(1))}let e;try{e=_.statSync(ae)}catch(t){console.error(`
|
|
261
|
+
[FATAL] DATA_DIR (${ae}) is not accessible: ${t.message}
|
|
262
262
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
263
|
-
[FATAL] DATA_DIR (${
|
|
264
|
-
`),process.exit(1));for(let t of[
|
|
263
|
+
[FATAL] DATA_DIR (${ae}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
264
|
+
`),process.exit(1));for(let t of[_e,xe]){let n;try{n=_.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
265
265
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
266
|
-
`),process.exit(1))}}var
|
|
267
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
266
|
+
`),process.exit(1))}}var Ee=N.join(ae,".migration-lock");function Tr(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return _.writeFileSync(Ee,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(_.readFileSync(Ee,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(a){a.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,i=1/0;if(t.startedAt){let a=Date.parse(t.startedAt);Number.isNaN(a)||(i=Date.now()-a)}o&&i<s&&(console.error(`
|
|
267
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Ee}
|
|
268
268
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
269
|
-
`),process.exit(1)),o&&
|
|
270
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let
|
|
269
|
+
`),process.exit(1)),o&&i>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Ee+".tmp";try{return _.writeFileSync(n,e),_.renameSync(n,Ee),!0}catch(o){try{_.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Zt(){try{if(JSON.parse(_.readFileSync(Ee,"utf-8")).pid!==process.pid)return;_.unlinkSync(Ee)}catch{}}var co=!1;function Rr(){if(co)return;co=!0;let e=()=>{try{Zt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Dr(){if(_.existsSync(Y))return;let e=[],t=[];for(let i of lo)if(_.existsSync(i))try{e.push({file:i,schema:bt(i)})}catch(a){t.push({file:i,err:a.message})}if(t.length>0){console.error(`
|
|
270
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
271
271
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
272
|
-
`),process.exit(1)}if(e.length===0)return;let n=e.map(
|
|
273
|
-
[FATAL] Legacy .schema-version files disagree:`);for(let
|
|
274
|
-
`),process.exit(1)}let o=e[0].schema,s=Y+".tmp";try{
|
|
272
|
+
`),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
|
|
273
|
+
[FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
274
|
+
`),process.exit(1)}let o=e[0].schema,s=Y+".tmp";try{_.writeFileSync(s,JSON.stringify(o,null,2)),_.renameSync(s,Y)}catch(i){try{_.unlinkSync(s)}catch{}throw i}for(let i of lo)if(_.existsSync(i))try{_.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${Y}`)}function Ir(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function bt(e){let t=_.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function uo(){if(Dr(),!_.existsSync(Y))return{version:0,migrations:[]};let e;try{e=bt(Y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
275
275
|
[FATAL] ${Y} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
276
|
-
`),process.exit(1)}let t=
|
|
276
|
+
`),process.exit(1)}let t=Ir(e);return t===null&&(console.error(`
|
|
277
277
|
[FATAL] ${Y} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
278
|
-
`),process.exit(1)),t}function
|
|
278
|
+
`),process.exit(1)),t}function po(e){try{_.chmodSync(e,384)}catch{}}function Mr(e){if(mo(),_.existsSync(Y))try{if(_.lstatSync(Y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${Y}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=Y+".tmp";try{_.writeFileSync(t,JSON.stringify(e,null,2)),po(t),_.renameSync(t,Y)}catch(n){try{_.unlinkSync(t)}catch{}throw n}}function fo(e,t){if(!_.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=_.readdirSync(e).filter(l=>{let r=l.toLowerCase();if(r.includes(".backup")||r===".schema-version"||r.endsWith(".tmp"))return!1;try{return _.statSync(N.join(e,l)).isFile()}catch{return!1}}),s=0,i=0,a=[];for(let l of o){let r=N.join(e,l),u=N.join(e,l+n);if(_.existsSync(u)){i++;continue}try{ho(r,u),s++}catch(c){a.push({file:l,err:c.message})}}if(a.length>0){let l=new Error(`Failed to back up ${a.length} file(s) in ${N.basename(e)}/: `+a.map(r=>`${r.file} (${r.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(s>0||i>0){let l=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${N.basename(e)}/ (${n})${l}`)}}var Qt=!1;async function go(){if(Qt)return;mo(),Lr();let t=uo().version;if(t===he){Qt=!0;return}Rr(),Tr(),process.on("exit",Zt),t>he&&(console.error(`
|
|
279
279
|
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${he}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
280
280
|
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${he}.
|
|
281
281
|
`),process.exit(1)),console.log(`
|
|
282
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${he}`);let n=
|
|
282
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${he}`);let n=Fr();if(!n.ok){console.error(`
|
|
283
283
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
|
|
284
284
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
285
285
|
`),process.exit(1)}let o=ue.filter(s=>s.version>t);for(let s of o){console.log(`
|
|
286
|
-
Running migration v${String(s.version).padStart(3,"0")}...`);let
|
|
287
|
-
[FATAL] Pre-migration backup failed for ${
|
|
288
|
-
`),process.exit(1)}let l=s.module;try{await l.up(
|
|
289
|
-
[FATAL] Migration ${
|
|
286
|
+
Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,a=`.pre-${i}.backup`;try{fo(_e,s.version),fo(xe,s.version)}catch(r){console.error(`
|
|
287
|
+
[FATAL] Pre-migration backup failed for ${i}: ${r.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
288
|
+
`),process.exit(1)}let l=s.module;try{await l.up(_e,xe)}catch(r){console.error(`
|
|
289
|
+
[FATAL] Migration ${i} failed: ${r.message}`),console.error(` Attempting auto-rollback from ${a} files...`);try{let u=Ur(a);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
290
290
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${a} files back over the originals.
|
|
291
291
|
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${a} files back over the originals.
|
|
292
|
-
`)}process.exit(1)}try{let
|
|
293
|
-
[FATAL] Migration ${
|
|
294
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${
|
|
292
|
+
`)}process.exit(1)}try{let r=new Date().toISOString(),u={version:s.version,name:l.NAME||i,appliedAt:r},c=uo();c.version=s.version,c.migratedAt=r,c.migrations=c.migrations||[],c.migrations.push(u),Mr(c)}catch(r){console.error(`
|
|
293
|
+
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${r.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
294
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{xn()}catch{}try{Pn()}catch{}Qt=!0,Zt(),console.log(`
|
|
295
295
|
\u2713 Schema is now at v${he}
|
|
296
|
-
`)}var
|
|
297
|
-
\u{1F504} CDP dead \u2014 recovering page (#${
|
|
298
|
-
`)}function
|
|
296
|
+
`)}var Or=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Nr(e){let t=e.toLowerCase();return Or.some(n=>n.test(t))}var jr=6e4;function Pr(){let e=Date.now(),t=[];for(let n of[ae,_e,xe]){if(!_.existsSync(n))continue;let o;try{o=_.readdirSync(n)}catch{continue}for(let s of o){if(!Nr(s))continue;let i=N.join(n,s);try{let a=_.statSync(i);if(!a.isFile()||e-a.mtimeMs<jr)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Lr({verbose:e=!1}={}){let t=Pr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{_.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${N.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Fr(){let e=[];for(let t of[_e,xe]){if(!_.existsSync(t))continue;let n=_.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=N.join(t,o);try{bt(s)}catch(i){e.push({dir:N.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ur(e){let t=[],n=[];for(let i of[_e,xe]){if(!_.existsSync(i))continue;let a=_.readdirSync(i).filter(l=>l.endsWith(e));for(let l of a){let r=N.join(i,l),u=l.slice(0,-e.length),c=N.join(i,u);try{u.toLowerCase().endsWith(".json")?bt(r):_.accessSync(r,_.constants.R_OK),t.push({backupPath:r,originalPath:c,fileName:l,dir:i})}catch(f){n.push(`${N.basename(i)}/${l}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:a,fileName:l,dir:r}of t)try{ho(i,a),o++}catch(u){s.push(`${N.basename(r)}/${l}: ${u.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function ho(e,t){let n=t+".tmp";try{_.copyFileSync(e,n),po(n)}catch(o){try{_.unlinkSync(n)}catch{}throw o}try{_.renameSync(n,t)}catch(o){try{_.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}Ie();async function qr(e,t,n="op"){let o,s=new Promise((i,a)=>{o=setTimeout(()=>a(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function Ae(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 yo(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await qr(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let a=await e.newPage();if(i)try{await i(a)}catch{}if(s)try{let l=s();Array.isArray(l)&&l.length>0&&await a.setCookie(...l)}catch{}if(n){await a.goto(n,{waitUntil:"domcontentloaded",timeout:o});let l=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(l))throw new Error(`Session expired after recovery \u2014 landed on ${l}. Run: ilml linkedin login`)}return a}await go();var To="https://www.linkedin.com/messaging/",Qr=10,on=3,Xr=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},Zr=()=>pt(),Re={pageRecoveries:0};async function vt(e,t){if(Re.pageRecoveries>=Qr)throw new Error(`CDP unrecoverable: ${Re.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
|
|
297
|
+
\u{1F504} CDP dead \u2014 recovering page (#${Re.pageRecoveries+1}). Reason: ${t}`),e.page=await yo(e.browser,e.page,{returnUrl:To,cookiesProvider:Zr,setupPage:Xr}),Re.pageRecoveries++,await v(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${Re.pageRecoveries}).
|
|
298
|
+
`)}function Be(e){return(e.messages||[]).find(t=>We.has(t.status))?.status}var Q=process.argv.slice(2),sn=Q.includes("--full"),W=Q.includes("--dry-run"),Co=Q.includes("--report"),rn=Q.includes("--verbose"),Eo=Q.includes("--backfill"),_o=Q.includes("--enrich"),xo=Q.includes("--today"),an=Q.includes("--read-unread"),ct=parseInt(Q.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),ei=Q.includes("--auto-enrich-replies"),Ao=parseInt(Q.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),ti=parseInt(Q.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function ni(e,t){if(!t)return"new";if(e.unread)return"unread";if(!t.profileUrl&&(t.messages?.length||t.lastMessagePreview))return"missing_url";let n=(t.lastMessagePreview||"").substring(0,50),o=(e.lastMessagePreview||"").substring(0,50);if(o&&n&&o!==n)return"preview_changed";if(e.lastMessageBy==="me"&&t.lastMessageBy!=="me")return"sender_changed";if(t.lastSynced&&e.lastMessageTime){let s=new Date(e.lastMessageTime).getTime(),i=new Date(t.lastSynced).getTime();if(Number.isFinite(s)&&Number.isFinite(i)&&s>i)return"activity_after_last_read"}return null}async function oi(e,t){console.log(`
|
|
299
299
|
\u2550\u2550 PHASE 1: Inbox Scan \u2550\u2550
|
|
300
|
-
`);let n=
|
|
301
|
-
3 rounds with no new items \u2014 end of visible list.`);break}}else f=0;if(!
|
|
302
|
-
Caught up \u2014 3 screens with no new threads to read.`);break}}else u=0;c=
|
|
303
|
-
Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;d=
|
|
304
|
-
`);let y=new Date().toISOString(),
|
|
305
|
-
Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${
|
|
300
|
+
`);let n=Tt(),o=n.lastIncrementalSync?new Date(n.lastIncrementalSync):null,s=new Map,i=new Map,a=new Map,l=0,r=0,u=0,c=0,f=0,d=-1,m=0;for(;;){r++;let w=await Yn(e),b=0;for(let p of w){if(!p.name||s.has(p.name))continue;s.set(p.name,p),b++,p.unread&&a.set(p.name,p);let $=t[p.name],C=ni(p,$);C&&(!an&&p.unread?l++:i.set(p.name,{card:p,reason:C})),$&&(C||($.lastMessageBy=p.lastMessageBy,$.lastMessagePreview=p.lastMessagePreview||$.lastMessagePreview,$.lastMessageTime=p.lastMessageTime||$.lastMessageTime),$.unread=p.unread,p.lastMessageBy==="them"&&p.unread&&($.conversationStatus="unanswered_by_us"))}if(rn?console.log(` Round #${r}: +${b} new | Total: ${s.size} | Need reading: ${i.size}`):process.stdout.write(`\r Scanned: ${s.size} conversations (page #${r}, ${i.size} need reading)`),b===0){if(f++,f>=3){console.log(`
|
|
301
|
+
3 rounds with no new items \u2014 end of visible list.`);break}}else f=0;if(!sn){if(i.size===c){if(u++,u>=3){console.log(`
|
|
302
|
+
Caught up \u2014 3 screens with no new threads to read.`);break}}else u=0;c=i.size}let h=await Mt(e);if(h){if(h.scrollTop===d){if(m++,m>=3){console.log(`
|
|
303
|
+
Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;d=h.scrollTop}else{let p=await e.$(".msg-conversation-listitem");if(p){let $=await p.boundingBox();$&&(await e.mouse.move($.x+$.width/2,$.y+$.height/2),await e.mouse.wheel({deltaY:600}))}}await v(2e3)}rn||process.stdout.write(`
|
|
304
|
+
`);let y=new Date().toISOString(),g=0;for(let[w,{card:b}]of i)t[w]||(t[w]={profileUrl:null,lastSynced:y,lastMessageBy:b.lastMessageBy,lastMessagePreview:b.lastMessagePreview||"",lastMessageTime:b.lastMessageTime||"",unread:b.unread||!1,conversationStatus:b.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},g++);let S=0;for(let[w,b]of a)t[w]||(t[w]={profileUrl:null,lastSynced:y,lastMessageBy:b.lastMessageBy,lastMessagePreview:b.lastMessagePreview||"",lastMessageTime:b.lastMessageTime||"",unread:!0,conversationStatus:b.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},S++);if(console.log(`
|
|
305
|
+
Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${g}`),console.log(` Need reading/re-reading: ${i.size}`),!an&&l>0&&console.log(` Preserved unread (default): ${l} \u2014 kept bold in LinkedIn UI; pass --read-unread to vacuum them into the DB`),S>0&&console.log(` New unread stubs: ${S} \u2014 saved to DB so 'today' / 'report' can show them offline`),i.size>0){let w={};for(let{reason:b}of i.values())w[b]=(w[b]||0)+1;for(let[b,h]of Object.entries(w))console.log(` ${b}: ${h}`)}if(!W){let w=Tt();w.lastIncrementalSync=new Date().toISOString(),sn&&(w.lastFullSync=w.lastIncrementalSync),Nn(w),me(t)}return{allCards:s,toReRead:i,unreadCards:a}}async function si(e,t,n,o){console.log(`
|
|
306
306
|
\u2550\u2550 PHASE 2: Read Changed Threads \u2550\u2550
|
|
307
|
-
`);let s=Array.from(t.entries()),
|
|
308
|
-
`);let l=[],
|
|
309
|
-
Phase 2 complete: ${l.length} read, ${u} failed${c?`, ${c} skipped on CDP recovery`:""}`),s.length>
|
|
307
|
+
`);let s=Array.from(t.entries()),i=Math.min(s.length,ct);if(i===0)return console.log(" No threads to read \u2014 all up to date."),[];console.log(" Resetting inbox view...");try{await e.page.goto(To,{waitUntil:"domcontentloaded",timeout:6e4})}catch(f){if(!Ae(f))throw f;await vt(e,"Phase 2 inbox reset")}await v(4e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}let a={unread:0,preview_changed:1,sender_changed:2,no_messages:3,new:4};s.sort((f,d)=>(a[f[1].reason]??5)-(a[d[1].reason]??5)),console.log(` Reading ${i} of ${s.length} threads (--max=${ct})
|
|
308
|
+
`);let l=[],r=[],u=0,c=0;for(let f=0;f<i;f++){let[d,{card:m,reason:y}]=s[f];console.log(` [${f+1}/${i}] ${d} (${y})`);let g=e.page;try{let S={verified:!1,headerName:null};try{S=await Lt(g,d)}catch(b){if(Ae(b))throw b;console.log(` searchAndOpenThread threw: ${(b.message||"").substring(0,80)}`)}if(!S.verified){console.log(" Sidebar fallback (scroll-to-find)...");try{S=await Gn(e.page,d)}catch(b){if(Ae(b))throw b;console.log(` Fallback threw: ${(b.message||"").substring(0,80)}`)}}if(!S.verified){console.log(" Could not open thread."),u++;try{await pe(e.page)}catch{}continue}let w=await Nt(g);if(w&&w.length>0){if(!jt(w,d,r)){console.log(" Skipped \u2014 stale data."),u++,await pe(g);continue}let h=await Ot(g),p=n[d]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},$=p.messages?.length||0;p.messages=Pt(p.messages,w),p.lastSynced=new Date().toISOString(),h&&!p.profileUrl&&(p.profileUrl=h);let C=p.messages.filter(R=>!["draft","confirmed","rejected","needs_review"].includes(R.status));p.lastMessageBy=qt(C,d),p.lastMessagePreview=m.lastMessagePreview||p.lastMessagePreview,p.lastMessageTime=m.lastMessageTime||p.lastMessageTime,p.unread=!1,n[d]=p,W||me(n);let A=p.messages.length-$;console.log(` ${p.messages.length} msgs (${A>=0?"+"+A:A} new)${h&&!p.profileUrl?" +url":""}`),l.push({name:d}),r=[...new Set(w.map(R=>R.sender).filter(R=>R&&R!=="Unknown"))]}else console.log(" No messages extracted."),u++;await pe(g),await v(500)}catch(S){if(!Ae(S))throw S;c++,o&&o.add(d),await vt(e,`Phase 2 thread ${f+1}/${i} (${d})`)}}return console.log(`
|
|
309
|
+
Phase 2 complete: ${l.length} read, ${u} failed${c?`, ${c} skipped on CDP recovery`:""}`),s.length>i&&console.log(` ${s.length-i} more threads pending (run again or increase --max)`),l}async function ri(e,t,n){if(!ei)return null;console.log(`
|
|
310
310
|
\u2550\u2550 PHASE 2.5: Auto-enrich-replies \u2550\u2550
|
|
311
|
-
`);let o=new Set(n.map(m=>m.name)),s=J(),
|
|
312
|
-
`),{picked:0,enriched:0,skipped:0,errors:0,dryRun:W};l.sort((m,y)=>{let
|
|
313
|
-
[${m+1}/${
|
|
311
|
+
`);let o=new Set(n.map(m=>m.name)),s=J(),i=Date.now(),a=ti*24*60*60*1e3,l=[];for(let m of o){let y=t[m];if(!y||y.lastMessageBy!=="them")continue;let g=y.profileUrl;if(!g)continue;let w=s[g]?._lastEnrichedAt;if(w){let b=i-new Date(w).getTime();if(Number.isFinite(b)&&b<a)continue}l.push({name:m,profileUrl:g,lastMessageTime:y.lastMessageTime||null})}if(l.length===0)return console.log(` No stale contacts to enrich. Skipping phase.
|
|
312
|
+
`),{picked:0,enriched:0,skipped:0,errors:0,dryRun:W};l.sort((m,y)=>{let g=new Date(m.lastMessageTime||0).getTime();return new Date(y.lastMessageTime||0).getTime()-g});let r=l.slice(0,Ao),u=l.length-r.length;if(console.log(` Candidates: ${l.length} | picking ${r.length} (cap ${Ao}) | skipping ${u}`),u>0&&console.log(" (raise --auto-enrich-max=N to lift the cap, but be mindful of ban-risk)"),W){console.log(" [DRY RUN] Would enrich:");for(let m of r)console.log(` - ${m.name} ${m.profileUrl} (last msg: ${m.lastMessageTime||"unknown"})`);return console.log(""),{picked:r.length,enriched:0,skipped:u,errors:0,dryRun:!0}}let{viewProfile:c}=await ko().then(()=>$o),f=0,d=0;for(let m=0;m<r.length;m++){let y=r[m];console.log(`
|
|
313
|
+
[${m+1}/${r.length}] Enriching ${y.name} ${y.profileUrl}`);try{let g=await c(e.page,y.profileUrl,{extractExperience:!0,extractFeatured:!0,extractEducation:!0,extractSkills:!0,extractRecommendations:!0,extractCertifications:!0});if(!g||!g.name){console.log(" \u2717 viewProfile returned no data \u2014 skipping save"),d++;continue}let S={name:g.name,title:g.title,location:g.location,about:g.about,currentCompany:g.currentCompany,currentSchool:g.currentSchool,topSkills:g.topSkills,availableSections:g.availableSections,connectionsLevel:g.connectionsLevel,mutualConnectionsCount:g.mutualConnectionsCount,followers:g.followers,openToWork:g.openToWork,hiring:g.hiring,hasVerifiedBadge:g.hasVerifiedBadge,photoUrl:g.photoUrl,source:"auto-enrich-replies"},w=!1;for(let[b,h]of[["experience",g.experience],["featured",g.featured],["education",g.education],["skillsFull",g.skillsFull],["recommendations",g.recommendations],["certifications",g.certifications]])Array.isArray(h)&&h.length>0&&(S[b]=h,w=!0);w&&(S._lastEnrichedAt=new Date().toISOString()),ve(y.profileUrl,S),g.resolvedUrl&&ft(y.profileUrl,g.resolvedUrl),f++,console.log(` \u2713 saved (rich sections: ${w?"yes":"no \u2014 basic only"})`)}catch(g){if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(g.message||""))return console.log(" \u26A0 Session expired during auto-enrich. Stopping phase."),console.log(" Sync-all post-processing will still run on already-enriched data."),{picked:r.length,enriched:f,skipped:u,errors:d,authWall:!0};console.log(` \u2717 ${g.message?.slice(0,200)}`),d++}m+1<r.length&&await v(8e3)}return console.log(`
|
|
314
314
|
Auto-enrich done: ${f} enriched, ${d} errors, ${u} skipped (over cap)
|
|
315
|
-
`),{picked:
|
|
315
|
+
`),{picked:r.length,enriched:f,skipped:u,errors:d}}function ii(e,t){console.log(`
|
|
316
316
|
\u2550\u2550 PHASE 3: Post-processing & Enrichment \u2550\u2550
|
|
317
|
-
`);let n=J();for(let o of t){let{name:s}=o,
|
|
317
|
+
`);let n=J();for(let o of t){let{name:s}=o,i=e[s];if(!i?.messages?.length)continue;try{Ut(i,s,n)}catch(r){console.warn(` [!] Enrichment failed for ${s}: ${r.message}`)}i._cardSynced&&delete i._cardSynced;let a=i.profileUrl,l=null;if(a&&(l=n[a]||null),!l){let r=Object.entries(n).filter(([,u])=>u.name===s);r.length===1&&(a||(a=r[0][0],i.profileUrl=a),l=r[0][1])}!l&&a&&(l=ve(a,{name:s,source:"sync-all"})),l&&(i.category&&!l.category&&(l.category=i.category),l.conversationStatus=i.conversationStatus,l.lastUpdated=new Date().toISOString()),a&&l&&(i.isConnection=l.connectionStatus==="connected")}W||($e(n),me(e)),console.log(` Enriched ${t.length} conversations.`),Ro(e)}function Ro(e){let t=new Map;for(let[s,i]of Object.entries(e)){if(!i.profileUrl)continue;let a=i.profileUrl.toLowerCase().replace(/\/$/,"");t.has(a)||t.set(a,[]),t.get(a).push(s)}let n=[...t.entries()].filter(([,s])=>s.length===2);if(n.length===0)return;let o=0;for(let[,s]of n){let[i,a]=s.map(c=>({name:c,conv:e[c]})),l=(i.conv.messages?.length||0)>=(a.conv.messages?.length||0)?i:a,r=l===i?a:i,u=new Set((l.conv.messages||[]).map(c=>`${c.text?.slice(0,80)}|${c.time}`));for(let c of r.conv.messages||[]){let f=`${c.text?.slice(0,80)}|${c.time}`;u.has(f)||(l.conv.messages.push(c),u.add(f))}l.conv.messages.sort((c,f)=>(c.time||"").localeCompare(f.time||"")),r.conv.notes&&!l.conv.notes&&(l.conv.notes=r.conv.notes),r.conv.priority&&!l.conv.priority&&(l.conv.priority=r.conv.priority),r.conv.categorySource==="manual"&&l.conv.categorySource!=="manual"&&(l.conv.category=r.conv.category,l.conv.categorySource="manual"),(r.conv.lastSynced||"")>(l.conv.lastSynced||"")&&(l.conv.lastSynced=r.conv.lastSynced),delete e[r.name],console.log(` Merged: "${r.name}" \u2192 "${l.name}"`),o++}o>0&&(W||me(e),console.log(` ${o} duplicates merged.`))}function ai(){let e=Xe(),t=J(),n=Object.entries(e);console.log(`
|
|
318
318
|
\u2550\u2550 ENRICHMENT: Re-processing all conversations \u2550\u2550
|
|
319
|
-
`);let o=0,s=0,
|
|
320
|
-
People enriched: ${u}`),console.log(` People skipped (have conversation or not connected): ${c}`),console.log(` People total: ${
|
|
319
|
+
`);let o=0,s=0,i=0;for(let[f,d]of n){if(!d.profileUrl){let m=Object.entries(t).filter(([,y])=>y.name===f);m.length===1&&(d.profileUrl=m[0][0],i++)}if(!d.messages||d.messages.length===0){s++;continue}try{Ut(d,f,t)}catch(m){console.warn(` [!] Enrichment failed for ${f}: ${m.message}`)}o++}Ro(e),W||me(e),console.log(` Enriched: ${o}`),console.log(` Skipped (no messages): ${s}`),i>0&&console.log(` Linked profileUrl from people.json: ${i}`),console.log(` Total: ${n.length}`);let a=new Set(Object.keys(e)),l=new Set(Object.values(e).map(f=>f.profileUrl).filter(Boolean)),r=Object.entries(t),u=0,c=0;for(let[f,d]of r){if(l.has(f)){c++;continue}if(d.name&&a.has(d.name)){c++;continue}if(d.connectionStatus!=="connected"){c++;continue}Zn(d,f),u++}W||$e(t),console.log(`
|
|
320
|
+
People enriched: ${u}`),console.log(` People skipped (have conversation or not connected): ${c}`),console.log(` People total: ${r.length}`),ln(e,null,null)}function ln(e,t,n,o={}){let s=Object.entries(e),i=J(),{unreadCards:a=null,readUnread:l=!1}=o;console.log(`
|
|
321
321
|
\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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SYNC REPORT"),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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
322
|
-
`),t&&(console.log(" Inbox Scan:"),console.log(` Conversations seen: ${t.allCards.size}`),console.log(` Needed reading: ${t.toReRead.size}`)),n&&console.log(` Actually read: ${n.length}`);let
|
|
323
|
-
Database:`),console.log(` Total conversations: ${
|
|
324
|
-
Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${y} (${m>0?(y/m*100).toFixed(1):0}%)`);let
|
|
325
|
-
Statuses:`);for(let[
|
|
326
|
-
Categories:`);for(let[
|
|
327
|
-
Actions Needed:`);for(let[
|
|
328
|
-
Duplicates (${
|
|
322
|
+
`),t&&(console.log(" Inbox Scan:"),console.log(` Conversations seen: ${t.allCards.size}`),console.log(` Needed reading: ${t.toReRead.size}`)),n&&console.log(` Actually read: ${n.length}`);let r=s.length,u=s.filter(([,k])=>k.messages?.length>0).length,c=s.filter(([,k])=>!k.messages||k.messages.length===0).length,f=s.filter(([,k])=>k.profileUrl).length,d=s.filter(([,k])=>!k.profileUrl).length;console.log(`
|
|
323
|
+
Database:`),console.log(` Total conversations: ${r}`),console.log(` With messages: ${u}`),console.log(` Without messages: ${c}`),console.log(` With profileUrl: ${f}`),console.log(` Without profileUrl: ${d}`);let m=0,y=0;for(let[,k]of s)for(let E of k.messages||[])m++,(!E.sender||E.sender==="Unknown")&&y++;console.log(`
|
|
324
|
+
Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${y} (${m>0?(y/m*100).toFixed(1):0}%)`);let g={};for(let[,k]of s){let E=k.conversationStatus||"null";g[E]=(g[E]||0)+1}console.log(`
|
|
325
|
+
Statuses:`);for(let[k,E]of Object.entries(g).sort((x,M)=>M[1]-x[1]))console.log(` ${k}: ${E}`);let S={};for(let[,k]of s){let E=k.category||"(none)";S[E]=(S[E]||0)+1}console.log(`
|
|
326
|
+
Categories:`);for(let[k,E]of Object.entries(S).sort((x,M)=>M[1]-x[1]))console.log(` ${k}: ${E}`);let w={};for(let[,k]of s){let E=k.actionNeeded||"(none)";w[E]=(w[E]||0)+1}if(Object.keys(w).length>1||!w["(none)"]){console.log(`
|
|
327
|
+
Actions Needed:`);for(let[k,E]of Object.entries(w).sort((x,M)=>M[1]-x[1]))console.log(` ${k}: ${E}`)}let b=new Map;for(let[k,E]of s){if(!E.profileUrl)continue;let x=E.profileUrl.toLowerCase().replace(/\/$/,"");b.has(x)||b.set(x,[]),b.get(x).push(k)}let h=[...b.entries()].filter(([,k])=>k.length>1);if(h.length>0){console.log(`
|
|
328
|
+
Duplicates (${h.length}):`);for(let[k,E]of h)console.log(` ${E.join(" | ")} \u2192 ${k}`)}let p=s.filter(([,k])=>k.conversationStatus==="unanswered_by_us").sort((k,E)=>(E[1].lastSynced||"").localeCompare(k[1].lastSynced||"")),$=s.filter(([,k])=>Be(k));if(console.log(`
|
|
329
329
|
\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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(" ACTION NEEDED"),console.log(`\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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
330
|
-
`),a&&!l&&a.size>0){let
|
|
331
|
-
`);let
|
|
332
|
-
... and ${
|
|
330
|
+
`),a&&!l&&a.size>0){let k=[...a.entries()];console.log(` STILL UNREAD ON LINKEDIN (${k.length}) \u2014 kept bold; read them in the LinkedIn UI:
|
|
331
|
+
`);let E=30;for(let[x,M]of k.slice(0,E)){let H=e[x],se=H?.category?` [${H.category}]`:"",re=M.lastMessageTime||H?.lastMessageTime||"",j=(M.lastMessagePreview||"").slice(0,80),P=H?.summary,U=H?.personContext?.title?`${H.personContext.title}${H.personContext.company?` at ${H.personContext.company}`:""}`:null;console.log(` ${x}${se}${re?` \u2014 ${re}`:""}`),j&&console.log(` "${j}"`),P?console.log(` ${P}`):U&&console.log(` ${U}`)}k.length>E&&console.log(`
|
|
332
|
+
... and ${k.length-E} more`),console.log(`
|
|
333
333
|
To pull them into the local DB (will lose unread badges): npm run sync-all -- --read-unread
|
|
334
|
-
`)}if(
|
|
335
|
-
`);for(let[
|
|
336
|
-
`);let
|
|
337
|
-
... and ${
|
|
338
|
-
INITIATE CONTACT (${
|
|
339
|
-
`);let
|
|
340
|
-
... and ${
|
|
334
|
+
`)}if($.length>0){let k=$.filter(([,x])=>Be(x)===V.CONFIRMED),E=$.filter(([,x])=>{let M=Be(x);return M===V.DRAFT||M===V.NEEDS_REVIEW});console.log(` Drafts: ${$.length} total (${k.length} confirmed, ${E.length} pending)`),E.length>0&&console.log(" Review: npm run messages -- --review-drafts"),k.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let C=p.filter(([,k])=>k.actionNeeded==="schedule_call"),A=p.filter(([,k])=>k.actionNeeded!=="schedule_call");if(A.sort((k,E)=>{let x={high:0,medium:1,low:2}[k[1].suggestedPriority]??3,M={high:0,medium:1,low:2}[E[1].suggestedPriority]??3;return x-M}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
|
|
335
|
+
`);for(let[k,E]of C){let x=E.category||"",M=E.summary||"";console.log(` ${k}${x?` [${x}]`:""} \u2192 schedule_call`),M&&console.log(` ${M}`)}console.log()}if(A.length>0){console.log(` REPLY NEEDED (${A.length}):
|
|
336
|
+
`);let k=20;for(let[E,x]of A.slice(0,k)){let M=x.category||"",H=x.suggestedPriority?`[${x.suggestedPriority}]`:"",se=(x.autoTags||[]).slice(0,4).join(", "),re=x.summary||"",P=[...x.messages||[]].reverse().find(U=>U.sender!==z&&U.sender!=="Unknown")?.text?.slice(0,80)||x.lastMessagePreview?.slice(0,80)||"";console.log(` ${H} ${E}${M?` [${M}]`:""}`),console.log(re?` ${re}`:` "${P}"`),se&&console.log(` #${se.replace(/, /g," #")}`)}A.length>k&&console.log(`
|
|
337
|
+
... and ${A.length-k} more`)}p.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let R=new Set(Object.keys(e)),T=new Set(Object.values(e).map(k=>k.profileUrl).filter(Boolean)),F=Object.entries(i).filter(([k,E])=>E.connectionStatus==="connected"&&E.personActionNeeded==="initiate_contact"&&!T.has(k)&&!(E.name&&R.has(E.name))).sort((k,E)=>{let x={high:0,medium:1,low:2}[k[1].personPriority]??3,M={high:0,medium:1,low:2}[E[1].personPriority]??3;return x!==M?x-M:(E[1].connectionDate||"").localeCompare(k[1].connectionDate||"")});if(F.length>0){console.log(`
|
|
338
|
+
INITIATE CONTACT (${F.length}):
|
|
339
|
+
`);let k=20;for(let[E,x]of F.slice(0,k)){let M=x.personPriority?`[${x.personPriority.toUpperCase()}]`:"",H=x.personSummary||x.title||"";console.log(` ${M} ${x.name||"Unknown"} \u2014 ${H}`)}F.length>k&&console.log(`
|
|
340
|
+
... and ${F.length-k} more`)}let G=s.filter(([,k])=>k.conversationStatus==="awaiting_reply");G.length>0&&console.log(`
|
|
341
341
|
BALL IN THEIR COURT: ${G.length} conversations`),W&&console.log(`
|
|
342
342
|
[DRY RUN \u2014 no changes written]`),console.log(`
|
|
343
343
|
\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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
344
|
-
`)}async function
|
|
344
|
+
`)}async function li(e,t){console.log(`
|
|
345
345
|
\u2550\u2550 BACKFILL: Reading conversations with 0 messages \u2550\u2550
|
|
346
|
-
`);let n=Object.entries(t).filter(([,
|
|
347
|
-
`);let s=[],
|
|
348
|
-
Backfill complete: ${s.length} read, ${
|
|
346
|
+
`);let n=Object.entries(t).filter(([,r])=>!r.messages||r.messages.length===0).map(([r,u])=>({name:r,preview:u.lastMessagePreview||"",lastBy:u.lastMessageBy}));if(n.length===0)return console.log(" All conversations already have messages."),[];n.sort((r,u)=>r.lastBy==="them"&&u.lastBy!=="them"?-1:r.lastBy!=="them"&&u.lastBy==="them"?1:0);let o=Math.min(n.length,ct);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${ct})
|
|
347
|
+
`);let s=[],i=0,a=0,l=[];for(let r=0;r<o;r++){let{name:u}=n[r];console.log(` [${r+1}/${o}] ${u}`);let c=e.page;try{if(await yn(c),!(await Lt(c,u)).verified){console.log(" Not found or thread didn't load."),i++,await pe(c),await v(500);continue}let d=await Nt(c);if(!d||d.length===0){console.log(" No messages extracted."),i++,await pe(c),await v(500);continue}if(!jt(d,u,l)){console.log(" Skipped \u2014 stale data."),i++,await pe(c),await v(500);continue}let y=await Ot(c),g=t[u]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]};g.messages=Pt(g.messages,d),g.lastSynced=new Date().toISOString(),y&&(g.profileUrl=y),t[u]=g,W||me(t),console.log(` \u2713 ${g.messages.length} msgs${y?" +url":""}`),s.push({name:u}),l=[...new Set(d.map(S=>S.sender).filter(S=>S&&S!=="Unknown"))],await pe(c),await v(500)}catch(f){if(!Ae(f))throw f;a++,await vt(e,`Backfill thread ${r+1}/${o} (${u})`)}}return console.log(`
|
|
348
|
+
Backfill complete: ${s.length} read, ${i} failed${a?`, ${a} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function ci(e){let t=Ze(),n=Object.values(e),o=n.filter(r=>r.sources?.includes("recruiters-from-jobs")&&!r.connectionStatus).length,s=n.filter(r=>r.connectionStatus==="modal_failed").length,i=o+s,a=n.filter(r=>r.connectionStatus==="connected"&&r.connectionMethod).length,l=n.filter(r=>r.connectionStatus==="pending"||r.connectionStatus==="sent_without_note").length;console.log("\u2550\u2550\u2550 CONNECTION QUOTA & QUEUE \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Today: ${t.daily.sent}/${t.daily.max} sent (${t.daily.remaining} remaining)`),console.log(` Week: ${t.weekly.sent}/${t.weekly.max} sent (${t.weekly.remaining} remaining)`),console.log(` Queue: ${i} profiles (${o} new, ${s} retry)`),console.log(` Funnel: ${a} accepted, ${l} pending`),i===0&&console.log(" \u26A0 Queue empty \u2014 need new job applications to feed funnel"),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")}function ui(e){let t=Object.values(e).filter(n=>n.jobCount>=2).sort((n,o)=>(o.jobCount||0)-(n.jobCount||0)).slice(0,10);if(t.length!==0){console.log("\u2550\u2550\u2550 TOP RECRUITERS (by job count) \u2550\u2550\u2550");for(let n=0;n<t.length;n++){let o=t[n],s=o.connectionStatus==="connected"?"connected":o.connectionStatus==="pending"||o.connectionStatus==="sent_without_note"?"pending":o.connectionStatus||"unknown",i=o.lastJobTitle?de(o.lastJobTitle,25):"",a=o.lastJobDate||"",l=i?` (last: ${i}${a?", "+a:""})`:"";console.log(` ${String(n+1).padStart(2)}. ${de(o.name||"?",25).padEnd(25)} ${String(o.jobCount).padStart(2)} jobs | ${s.padEnd(10)}${l}`)}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")}}function di(){let e=qn(10);if(e.length!==0){console.log("\u2550\u2550\u2550 TOP JOBS TO APPLY \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let t=0;t<e.length;t++){let{score:n,job:o}=e[t],s=de(o.title||"?",30),i=de(o.company||"?",15),a=o.salary?` \u2014 ${de(o.salary,12)}`:"",l=o.location?` \u2014 ${de(o.location,15)}`:"",r=o.recruiterUrl?" \u{1F464}":"";console.log(` ${String(t+1).padStart(2)}. [${String(n).padStart(2)}] ${s} @ ${i}${a}${l}${r}`)}console.log(" Apply: npm run apply-queue"),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")}}function fi(){let e=Fn();e.totalJobs===0&&e.totalVisited===0||(console.log("\u2550\u2550\u2550 MARKET RESEARCH \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Scouted jobs: ${e.totalJobs}${e.lastScoutDate?` (last: ${e.lastScoutDate})`:""}`),console.log(` Discovered people: ${e.totalRecruiters}`),console.log(` Profile visits: ${e.totalVisited} unique (${e.todayVisited} today)`),e.topTech.length>0&&console.log(` Top tech: ${e.topTech.slice(0,5).join(", ")}`),e.topCompanies.length>0&&console.log(` Top companies: ${e.topCompanies.slice(0,5).join(", ")}`),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"))}function mi(){let e=jn();if(e.totalApplications!==0){if(console.log(`\u2550\u2550\u2550 FAQ STATS (${e.totalApplications} applications) \u2550\u2550`),console.log(` Unique questions: ${e.uniqueQuestions}`),e.topQuestions.length>0){console.log(" Top questions:");for(let t of e.topQuestions.slice(0,8)){let n=de(t.topAnswer,30);console.log(` "${de(t.question,40)}" \u2014 ${t.count}x \u2192 ${n}`)}}if(e.inconsistent.length>0){console.log(` Inconsistent answers: ${e.inconsistent.length} \u26A0`);for(let t of e.inconsistent.slice(0,3))console.log(` "${de(t.question,35)}" \u2014 ${t.answers.join(", ")}`)}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")}}function de(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function pi(){let e=Xe(),t=J(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(h=>h.profileUrl).filter(Boolean));console.log(`
|
|
349
349
|
\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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" TODAY'S PRIORITIES"),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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
350
|
-
`),console.log(
|
|
351
|
-
`);for(let
|
|
352
|
-
`);for(let[
|
|
353
|
-
`);for(let
|
|
354
|
-
`);for(let
|
|
355
|
-
`);for(let
|
|
356
|
-
`);for(let
|
|
357
|
-
`);for(let
|
|
350
|
+
`),console.log(so()),console.log(""),ci(t),console.log(""),ui(t),console.log(""),fi(),console.log(""),di(),console.log(""),mi(),console.log("");let s=Object.entries(e),i=s.filter(([,h])=>h.unread===!0).sort((h,p)=>(p[1].lastMessageTime||"").localeCompare(h[1].lastMessageTime||""));if(i.length>0){let h=i.slice(0,10);console.log(` UNREAD ON LINKEDIN (${i.length}) \u2014 bold in LinkedIn UI, not yet opened:
|
|
351
|
+
`);for(let p=0;p<h.length;p++){let[$,C]=h[p],A=C.category?` [${C.category}]`:"",R=C.summary||(C.personContext?.title?`${C.personContext.title}${C.personContext.company?` at ${C.personContext.company}`:""}`:null)||C.lastMessagePreview?.slice(0,60)||null;console.log(` ${p+1}. ${$}${A}${R?` \u2014 ${R}`:""}`)}i.length>10&&console.log(` ... +${i.length-10} more`),console.log()}let a=new Date().toISOString().slice(0,10),l=s.filter(([,h])=>h.followUpNote),r=l.filter(([,h])=>!h.followUpDate||h.followUpDate<=a),u=l.filter(([,h])=>h.followUpDate&&h.followUpDate>a);if(l.length>0){console.log(` FOLLOW-UPS (${r.length} due, ${u.length} scheduled):
|
|
352
|
+
`);for(let[h,p]of r){let $=p.followUpDate?` [due ${p.followUpDate}]`:" [no date]";console.log(` \u26A1 ${h}${$} \u2014 ${p.followUpNote}`)}for(let[h,p]of u.slice(0,5))console.log(` \u{1F4C5} ${h} [${p.followUpDate}] \u2014 ${p.followUpNote}`);u.length>5&&console.log(` ... +${u.length-5} more scheduled`),console.log()}let c=h=>h.actionNeeded&&h.actionNeeded!=="none"&&(!h.reviewedAtPreview||st(h.lastMessagePreview)!==st(h.reviewedAtPreview)),f=s.filter(([,h])=>c(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(f.length>0){let h=f.slice(0,20);console.log(` UNREVIEWED \u2014 NEW MESSAGES (${f.length}):
|
|
353
|
+
`);for(let p=0;p<h.length;p++){let[$,C]=h[p],A=C.priority||C.suggestedPriority||"",R=C.category?` [${C.category}]`:"",T=C.summary||"";console.log(` ${p+1}. ${A?`[${A}] `:""}${$}${R} \u2014 ${T}`)}f.length>20&&console.log(` ... +${f.length-20} more`),console.log()}let d=s.filter(([,h])=>h.actionNeeded==="schedule_call").sort((h,p)=>{let $={high:0,medium:1,low:2}[h[1].suggestedPriority]??3,C={high:0,medium:1,low:2}[p[1].suggestedPriority]??3;return $-C});if(d.length>0){let h=d.slice(0,5);console.log(` CALLS TO SCHEDULE (${d.length}):
|
|
354
|
+
`);for(let p=0;p<h.length;p++){let[$,C]=h[p],A=C.summary||C.personContext?.title||"";console.log(` ${p+1}. ${$} \u2014 ${A}`)}d.length>5&&console.log(` ... +${d.length-5} more`),console.log()}let m=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us"&&h.actionNeeded!=="schedule_call"&&(h.suggestedPriority==="high"||h.priority==="high")&&!c(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(m.length>0){let h=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
|
|
355
|
+
`);for(let p=0;p<h.length;p++){let[$,C]=h[p],A=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${$}${A} \u2014 ${R}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let y=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us"&&h.actionNeeded!=="schedule_call"&&h.suggestedPriority==="medium"&&h.priority!=="high"&&!c(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(y.length>0){let h=y.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${y.length}):
|
|
356
|
+
`);for(let p=0;p<h.length;p++){let[$,C]=h[p],A=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${$}${A} \u2014 ${R}`)}y.length>5&&console.log(` ... +${y.length-5} more`),console.log()}let g=Object.entries(t).filter(([h,p])=>p.connectionStatus==="connected"&&p.personActionNeeded==="initiate_contact"&&!o.has(h)&&!(p.name&&n.has(p.name))).sort((h,p)=>{let $={high:0,medium:1,low:2}[h[1].personPriority]??3,C={high:0,medium:1,low:2}[p[1].personPriority]??3;return $!==C?$-C:(p[1].connectionDate||"").localeCompare(h[1].connectionDate||"")});if(g.length>0){let h=g.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${g.length}):
|
|
357
|
+
`);for(let p=0;p<h.length;p++){let[,$]=h[p],C=$.personPriority?`[${$.personPriority.toUpperCase()}]`:"",A=$.connectionDate?gi($.connectionDate):"",R=$.title?`${$.title}${$.company?` at ${$.company}`:""}`:$.company||"";console.log(` ${p+1}. ${C} ${$.name||"Unknown"} \u2014 ${R}${A?` (${A})`:""}`)}g.length>10&&console.log(` ... +${g.length-10} more`),console.log()}let S=s.filter(([,h])=>Be(h));if(S.length>0){let h=S.filter(([,$])=>Be($)===V.CONFIRMED).length,p=S.filter(([,$])=>{let C=Be($);return C===V.DRAFT||C===V.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${S.length} (${h} confirmed, ${p} pending)`),h>0&&console.log(" Send: npm run messages -- --push-drafts"),p>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let w=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us").length,b=s.filter(([,h])=>h.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${i.length} unread on LinkedIn, ${f.length} unreviewed, ${w} need reply, ${g.length} new connections, ${b} ball in their court`),console.log(`
|
|
358
358
|
\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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
359
|
-
`)}function
|
|
359
|
+
`)}function gi(e){let t=new Date(e);if(isNaN(t))return"";let n=Math.floor((Date.now()-t.getTime())/864e5);return n===0?"today":n===1?"1d ago":`${n}d ago`}function hi(){let e=Xe();ln(e,null,null)}async function yi(){if(console.log(`
|
|
360
360
|
LinkedIn Sync-All
|
|
361
|
-
`),
|
|
362
|
-
\u26A0 Phase 1 CDP dead (attempt ${
|
|
363
|
-
\u26A0 Auto-enrich phase crashed: ${
|
|
364
|
-
`)}l.length>0&&
|
|
365
|
-
CDP page recoveries this run: ${
|
|
366
|
-
Error:`,a.message),
|
|
361
|
+
`),xo){pi();return}if(Co){let a=yt("sync-all","report");hi(),qe(a,"success");return}if(_o){let a=yt("sync-all","enrich");try{ai(),qe(a,"success")}catch(l){throw qe(a,"error",null,l.message),l}return}let e=Eo?"backfill":sn?"full":"incremental",t=yt("sync-all",e),n={scanned:0,toReRead:0,threadsRead:0,newMessages:0};W&&console.log(" [DRY RUN mode]"),console.log(` Mode: ${e} | Max threads to read: ${ct}`);let o=Xe(),s=await Wn(),i={browser:s.browser,page:s.page};try{await It(i.page);let a=null,l=[];if(Eo)l=await li(i,o);else{let r=0;for(;;)try{a=await oi(i.page,o);break}catch(d){if(!Ae(d))throw d;if(r++,r>=on)throw new Error(`Phase 1 failed ${on} times on CDP death \u2014 giving up. Last: ${d.message}`);console.log(`
|
|
362
|
+
\u26A0 Phase 1 CDP dead (attempt ${r}/${on}). Recovering and restarting Phase 1...`),await vt(i,`Phase 1 attempt ${r}`)}let u=new Set;l=await si(i,a.toReRead,o,u),n.scanned=a.totalCards||0,n.toReRead=a.toReRead?.size||0;let c=new Set(l.map(d=>d.name)),f=0;for(let[d,{card:m}]of a.toReRead){if(c.has(d)||u.has(d))continue;let y=o[d];y&&(y.lastMessageBy=m.lastMessageBy,y.lastMessageTime=m.lastMessageTime||y.lastMessageTime,y.unread=m.unread,f++)}f>0&&(console.log(` Pending re-read: ${f} threads (raise --max or re-run to drain).`),W||me(o))}n.threadsRead=l.length,n.newMessages=l.reduce((r,u)=>r+(u.newMessages||0),0);try{let r=await ri(i,o,l);r&&(n.autoEnriched=r.enriched,r.authWall&&(n.autoEnrichAuthWall=!0))}catch(r){console.log(`
|
|
363
|
+
\u26A0 Auto-enrich phase crashed: ${r.message?.slice(0,200)}`),console.log(` Continuing with post-processing \u2014 data integrity is unaffected.
|
|
364
|
+
`)}l.length>0&&ii(o,l),ln(o,a,l,{unreadCards:a?.unreadCards,readUnread:an}),Re.pageRecoveries>0&&console.log(`
|
|
365
|
+
CDP page recoveries this run: ${Re.pageRecoveries}`),W||Rt(),qe(t,"success",n)}catch(a){console.error(`
|
|
366
|
+
Error:`,a.message),rn&&console.error(a.stack),qe(t,"error",n,a.message)}finally{if(!W&&!Co&&!_o&&!xo)try{Rt()}catch{}await i.browser.close()}}yi();
|