ilml-plugin-linkedin 1.11.7 → 1.12.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 +18 -0
- package/README.md +7 -1
- package/dist/applyQueue.mjs +4 -4
- package/dist/daily.mjs +4 -4
- package/dist/enrichProfile.mjs +41 -0
- package/dist/enrichProfiles.mjs +84 -38
- package/dist/funnelRunner.mjs +46 -43
- package/dist/help.mjs +15 -0
- package/dist/messageBot.mjs +55 -55
- package/dist/profileHistory.mjs +5 -5
- package/dist/run.mjs +60 -57
- package/dist/scout.mjs +7 -7
- package/dist/syncAll.mjs +19 -19
- package/dist/verifyAbout.mjs +10 -7
- package/dist/viewers.mjs +9 -9
- package/dist/visit.mjs +43 -40
- package/ilml-plugin.json +53 -24
- package/package.json +3 -1
package/dist/funnelRunner.mjs
CHANGED
|
@@ -1,71 +1,74 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Bt=Object.defineProperty;var ze=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{for(var o in t)Bt(e,o,{get:t[o],enumerable:!0})};async function w(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(s=>setTimeout(s,o))}async function ie(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let s of t){let r=s.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),l=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||l||c){let n=s.querySelector('button[aria-label="Dismiss"]')||s.querySelector("button.artdeco-modal__dismiss")||s.querySelector("button[data-test-modal-close-btn]");if(n)return n.click(),{dismissed:!0,matched:r.substring(0,80)};let u=s.querySelectorAll("button");for(let a of u){let f=a.innerText?.trim().toLowerCase()||"",d=a.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return a.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let s=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(s)return s.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var $e=ze(()=>{});var mt={};ke(mt,{extractExperienceFromDetails:()=>ho});async function ho(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let r=0;for(;r<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});)r++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function l(a){let f=[];for(let d of a.querySelectorAll("div")){let p=Array.from(d.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let g=p.filter(m=>(m.textContent||"").trim().length>50);g.length<3||(d.textContent||"").length<500||f.push({el:d,count:g.length,totalText:(d.textContent||"").length})}return f.sort((d,p)=>p.count-d.count||d.totalText-p.totalText),f[0]?.el}let c=l(i);if(!c)return[];let n=Array.from(c.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function u(a){let f=a[0]||null,d=null,p=null;if(a[1]){let k=a[1].split("\xB7").map(_=>_.trim());d=k[0]||null,k[1]&&(p=k[1])}let g=a.findIndex(k=>/(\d{4}|present)/i.test(k)&&/(-|–|—)/i.test(k)&&k.length<80),m=null,S=null;if(g>=0){let k=a[g].split("\xB7").map(_=>_.trim());m=k[0]||null,k[1]&&(S=k[1])}let h=null,b=-1;if(g>=0&&a[g+1]){let k=a[g+1],_=/^[>*\-•]|^>/.test(k),re=/https?:\/\//.test(k),X=/\d{4}/.test(k),Y=/,/.test(k)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(k);!_&&!re&&!X&&k.length<100&&Y&&(h=k,b=g+1)}let A=null,$=-1,I=a[a.length-1];if(I&&/and\s+\+\d+\s+skills?$/i.test(I)){$=a.length-1;let k=I.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);k&&(A={listed:k[1].split(",").map(_=>_.trim()),additional:parseInt(k[2],10)})}let F=new Set([0,1,g,b,$].filter(k=>k>=0)),M=a.filter((k,_)=>!F.has(_)),L=M.length>0?M.join(`
|
|
2
|
+
|
|
3
|
+
`):null;return{title:f,company:d,employmentType:p,dates:m,duration:S,location:h,description:L,skills:A,_raw:a}}return n.map(a=>{let d=(a.innerText||"").trim().split(`
|
|
4
|
+
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return u(d)}).filter(a=>a.title)})}catch(s){if(/session expired|bounced to|authwall|checkpoint/i.test(s.message||""))throw s;return console.error(`extractExperienceFromDetails failed for ${t}: ${s.message?.slice(0,120)}`),[]}}var ht=ze(()=>{$e()});import gn from"puppeteer";import"dotenv/config";import*as J from"fs";import*as oe from"path";import{fileURLToPath as Gt}from"url";import"dotenv/config";import{createGraphClient as qt,resolveToken as Jt}from"@ilivemylife/graph-sdk";import{config as Ht}from"dotenv";Ht();var Ke=Jt()||process.env.TOKEN;Ke||(console.error(`
|
|
2
5
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
3
6
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
4
7
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
5
|
-
`),process.exit(1));var
|
|
8
|
+
`),process.exit(1));var Qe=qt({token:Ke});function Vt(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),s=t%60;return s?`${o}m ${s}s`:`${o}m`}function Wt({scriptName:e,mode:t,status:o,error:s,duration:r}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${Vt(r)}`:"",n=o==="error"?`error${s?`: ${String(s).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${n} \u2014 ${l}${c}`}async function Ze({scriptName:e,mode:t,status:o,summaryLines:s,error:r,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(s)||s.length===0)return;let n=`**${Wt({scriptName:e,mode:t,status:o,error:r,duration:i})}**
|
|
6
9
|
|
|
7
10
|
${s.join(`
|
|
8
|
-
`)}`;try{await Ye.addMessage(l,n)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Bt=Ut(import.meta.url),qt=Z.dirname(Z.dirname(Bt)),Ie=process.env.DATA_DIR?Z.resolve(process.env.DATA_DIR,"collected-profiles"):Z.join(qt,"collected-profiles"),xe=Z.join(Ie,"run-log.json");function Jt(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";B.writeFileSync(s,o);for(let r=0;r<3;r++)try{B.renameSync(s,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Ke(){try{if(!B.existsSync(xe))return{runs:[]};let e=JSON.parse(B.readFileSync(xe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Qe(e){B.existsSync(Ie)||B.mkdirSync(Ie,{recursive:!0});try{Jt(xe,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ze(e,t="default"){let o=Ke();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let s=new Date,r={timestamp:s.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>i),Qe(o),{script:e,mode:t,startTime:s.getTime(),runIndex:o.runs.length-1}}function De(e,t,o=null,s=null){if(!e)return;let r=null;try{let l=Ke(),c=l.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=s,r=c.duration;else{let n=l.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());n&&(n.status=t,n.result=t,n.duration=Date.now()-e.startTime,n.stats=o,n.error=s,r=n.duration)}Qe(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";ze({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:s,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}async function S(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(s=>setTimeout(s,o))}async function oe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let s of t){let r=s.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),l=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||l||c){let n=s.querySelector('button[aria-label="Dismiss"]')||s.querySelector("button.artdeco-modal__dismiss")||s.querySelector("button[data-test-modal-close-btn]");if(n)return n.click(),{dismissed:!0,matched:r.substring(0,80)};let a=s.querySelectorAll("button");for(let u of a){let f=u.innerText?.trim().toLowerCase()||"",p=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||p.includes("dismiss"))return u.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let s=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(s)return s.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import{getPluginConfig as Ht}from"@ilivemylife/graph-sdk";var Vt=await Ht();for(let[e,t]of Object.entries(Vt))process.env[e]===void 0&&(process.env[e]=t);var Cn=process.env.LINKEDIN_NAME,ne=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),An=Object.freeze(new Set([ne.DRAFT,ne.CONFIRMED,ne.NEEDS_REVIEW])),En=Object.freeze(new Set([ne.DRAFT,ne.CONFIRMED,ne.REJECTED,ne.NEEDS_REVIEW]));import"dotenv/config";import*as D from"fs";import*as _ from"path";import{fileURLToPath as Wt}from"url";var Gt=Wt(import.meta.url),Yt=_.dirname(_.dirname(Gt)),G=process.env.DATA_DIR?_.resolve(process.env.DATA_DIR,"collected-profiles"):_.join(Yt,"collected-profiles"),Oe=_.join(G,"people.json"),jn=_.join(G,"jobs.json"),tt=_.join(G,"quota.json"),_n=_.join(G,"conversations.json"),Tn=_.join(G,"sync-state.json"),Rn=_.join(G,"application-questions.json"),je=_.join(G,"profile-history"),de=20,pe=100,ae=null,zt=null,W=null,Kt=null,Qt=null,Zt=null;function ot(){ae=null,zt=null,W=null,Kt=null,Qt=null,Zt=null}function ke(){D.existsSync(G)||D.mkdirSync(G,{recursive:!0})}function _e(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";D.writeFileSync(s,o);for(let r=0;r<3;r++)try{D.renameSync(s,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Te(e,t){if(!D.existsSync(e))return null;try{let o=JSON.parse(D.readFileSync(e,"utf-8"));try{D.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${_.resolve(e)}`);let s=e+".backup";if(D.existsSync(s))try{let r=JSON.parse(D.readFileSync(s,"utf-8"));console.error(` Restored from ${s}`);try{D.copyFileSync(s,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{D.copyFileSync(e,e+".corrupted")}catch{}return null}}function me(){return new Date().toISOString().split("T")[0]}var Xt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections"],eo=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function Re(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function to(){D.existsSync(je)||D.mkdirSync(je,{recursive:!0})}function nt(e){let t=Re(e);return t?_.join(je,`${t}.json`):null}function oo(e){let t=nt(e);return t?Te(t,`profile-history/${Re(e)}.json`)||[]:[]}function no(e,t){let o=nt(e);if(!o)return;to();let s=oo(e);s.unshift(t);try{_e(o,s)}catch(r){console.error(`[!] Failed to append profile-history for ${Re(e)}: ${r.message}`)}}function Xe(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function et(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function so(e,t){if(!e)return[];let o=[];for(let s of eo){let r=e[s],i=t[s];Xe(r)||Xe(i)||et(r)!==et(i)&&o.push(s)}return o}function ro(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[s,r]of Object.entries(e))t.has(s)||(o[s]=r);return o}function X(){return ae||(ke(),ae=Te(Oe,"people.json")||{},ae)}function Ne(e){ke(),ae=e;try{_e(Oe,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${_.resolve(Oe)}`)}}function ve(e,t={}){if(!e)return null;let o=X(),s=me(),r=new Date().toISOString(),i=o[e];if(i){let l=so(i,t);l.length>0&&(no(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:ro(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=s,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let c of Xt)t[c]!=null&&(i[c]=t[c]);Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else o[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,firstSeen:s,lastSeen:s,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return Ne(o),o[e]}function st(e,t){if(!e||!t)return;let o=X(),s=o[e];if(!s)return;s.encounters||(s.encounters=[]);let i={date:me(),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),!s.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(s.encounters.push(i),s.lastUpdated=new Date().toISOString(),Ne(o))}function rt(e){return e&&X()[e]?.connectionStatus||null}function it(e,t,o={}){if(!e)return;o.profileInfo?ve(e,o.profileInfo):X()[e]||ve(e,{});let s=X(),r=s[e];r&&(r.connectionStatus=t,r.connectionDate=me(),r.connectionMethod=o.method||r.connectionMethod,r.messageSent=o.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),Ne(s))}function lt(){return W||(ke(),W=Te(tt,"quota.json"),(!W||!W.connections)&&(W={connections:[]}),W)}function io(e){ke(),W=e;try{_e(tt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function at(e,t="unknown"){let o=lt(),s=new Date;o.connections.push({date:s.toISOString().split("T")[0],time:s.toTimeString().split(" ")[0],profileUrl:e,source:t}),io(o)}function ct(){let e=lt(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(s=>s.date>=o)}function ut(){let e=ct(),t=me(),o=e.filter(n=>n.date===t).length,s=e.length,r=o>=de,i=s>=pe,l=!r&&!i,c={allowed:l,daily:{sent:o,max:de},weekly:{sent:s,max:pe}};return l||(c.reason=r?`Daily limit reached (${o}/${de})`:`Weekly limit reached (${s}/${pe})`),c}function Fe(){let e=ct(),t=me(),o=e.filter(r=>r.date===t).length,s=e.length;return{daily:{sent:o,max:de,remaining:de-o},weekly:{sent:s,max:pe,remaining:pe-s}}}async function dt(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let s=e.url();return s.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${s.slice(0,80)}`),!0}function ft(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(s=>o.includes(s.toLowerCase()))}async function lo(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await dt(e,t));let s=0;for(let i=0;i<2;i++){let l=await e.evaluate(()=>document.body.scrollHeight);for(let n=1;n<=6;n++)await e.evaluate(a=>window.scrollTo(0,a),l*n/6),await S(900);let c=await e.evaluate(()=>document.body.scrollHeight);if(c===s)break;s=c}await S(800);let r=await e.evaluate(()=>{let i=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"]),l=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=y=>{let $=(y||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test($)},n={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:[]},a=document.querySelector("main");if(!a)return n;let u=[...Array.from(a.querySelectorAll("h1")),...Array.from(a.querySelectorAll("h2"))],f=Array.from(a.querySelectorAll("h2")),p=u.find(y=>{let $=y.textContent&&y.textContent.trim(),C=($||"").replace(/\s*\(\d+\)$/,"").trim();return $&&$.length>1&&$.length<100&&!i.has(C)&&!l.has(C)}),m=p?p.textContent.trim():null,g=p?p.parentElement:null;for(;g&&g!==a&&!Array.from(g.children).filter($=>$.tagName==="P").some($=>{let C=$.textContent&&$.textContent.trim();return C&&C.length>5&&!c(C)});)g=g.parentElement;let d=null,b=null,w=null,v=null;if(g&&g!==a){let y=Array.from(g.children).filter(C=>C.tagName==="P").filter(C=>{let Q=C.textContent&&C.textContent.trim();return Q&&Q.length>5&&!c(Q)});if(y[0]&&(d=y[0].textContent.trim()),y[1]){let C=y[1].textContent.trim().split(/\s*[·•]\s*/);b=C[0]||null,C.length>1&&(w=C.slice(1).join(" \xB7 "))}let $=Array.from(g.children).filter(C=>C.tagName==="DIV");for(let C=$.length-1;C>=0;C--){let Q=$[C].textContent&&$[C].textContent.trim();if(Q&&!(m&&Q.startsWith(m))&&(v=Q.split(/[·•]/)[0].trim(),v))break}}let A=null;if(g){let y=g.querySelectorAll("p, span, div");for(let $ of y){let C=($.textContent||"").trim().replace(/^[·•]\s*/,"");if(C==="1st"||C==="2nd"||C==="3rd"){A=C;break}}}let k=!!a.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),O=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=O&&O.src||null,T=a.textContent||"",U=null,F=T.match(/(\d+\+?)\s+connections\b/i);F&&(U=F[1]+" connections");let te=null,ce=T.match(/(\d+)\s+mutual connection/i),le=T.match(/and\s+(\d+)\s+other mutual/i),we=T.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ce?te=parseInt(ce[1],10):le?te=2+parseInt(le[1],10):we&&(te=2);let K=null,ue=null,fe=f.find(y=>y.textContent&&y.textContent.trim()==="About");if(fe){let y=fe.parentElement;for(;y&&y.tagName!=="SECTION";)y=y.parentElement;if(y){let $=(y.textContent||"").trim();$=$.replace(/^About\s*/,"").trim();let C=$.match(/Top skills\s*(.+?)$/i);if(C){let Ae=C[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Tt=>Tt.trim()).filter(Boolean);Ae.length>0&&Ae.length<10&&(ue=Ae)}$=$.split(/\n?…\s*more/i)[0].trim(),$=$.split(/\n?\.\.\.\s*more/i)[0].trim(),$=$.split(/\bTop skills\b/i)[0].trim(),$=$.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),K=$||null}}let Se=null,be=f.find(y=>y.textContent&&y.textContent.trim()==="Activity");if(be){let y=be.parentElement;for(;y&&y.tagName!=="SECTION";)y=y.parentElement;if(y){let $=(y.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);$&&(Se=parseInt($[1].replace(/,/g,""),10))}}let I=[...new Set(f.map(y=>(y.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(y=>y&&y.length>1&&y.length<60&&y!==m).filter(y=>i.has(y)))],x=document.body.textContent||"",R=/#OpenToWork\b/i.test(x)||/\bOpen to work\b/.test(x),j=/#Hiring\b/i.test(x)||/\bI'?m hiring\b/i.test(x)||/\bWe are hiring\b/i.test(x);return{name:m,title:d,location:v,currentCompany:b,currentSchool:w,connectionDegree:A,hasVerifiedBadge:k,photoUrl:P,connectionsLevel:U,mutualConnectionsCount:te,followers:Se,openToWork:R,hiring:j,about:K,topSkills:ue,availableSections:I}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}return null}}async function he(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),s=Array.from(o).map(n=>n.getAttribute("aria-label")),r=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:s,hasMessageBtn:!!r,hasConnectBtn:!!i};return o.length>0?{status:"pending",debug:l}:r&&!i?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Me(e){let t=null,o=await e.evaluate(()=>{let n=document.querySelector("h1")?.textContent?.trim();if(n&&!n.includes("notification"))return n;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(n=a.textContent?.trim(),n&&!n.includes("notification")))return n;let u=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(u)return u.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let n=await e.evaluate(()=>{let u=document.querySelectorAll('a[href*="custom-invite"]');return{count:u.length,labels:Array.from(u).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});n.count>0&&console.log(` S0: ${n.count} custom-invite links: ${JSON.stringify(n.labels)}`),t=await e.evaluateHandle(u=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),p=u.toLowerCase().split(" ")[0],m=null,g=null;for(let d of f){let b=d.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((d.getAttribute("aria-label")||"").toLowerCase().includes(p)){m=d;break}g||(g=d)}return m||g||null},o);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:a,method:"connect_link"}}if(o){let n=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${n}"`);let a=await e.evaluate(f=>{let p=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(d=>{let b=d.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&p.test(b)}).map(d=>d.getAttribute("aria-label")?.slice(0,50))},n);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),t=await e.evaluateHandle(f=>{let p=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of p){let d=g.getAttribute("aria-label")||"";if((d.toLowerCase().includes("invite")||d.toLowerCase().includes("connect"))&&m.test(d))return g}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: button matching profile name"),{button:u,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let n=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),a=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(a)&&(console.log(` Skipping primary button: wrong person (${n})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let s=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');s.length===0&&(s=await e.$$('button[aria-label="Connect"]'));let r=o?o.split(" ")[0].toLowerCase():"",i=null;for(let n of s){let a=await e.evaluate((u,f)=>{let p=u.className.includes("muted"),m=u.className.includes("sticky-header")||u.className.includes("sticky"),g=u.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,d=(u.getAttribute("aria-label")||"").toLowerCase(),b=d.includes("invite"),w=f?d.includes(f):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:g,hasInvite:b,matchesName:w,ariaLabel:d}},n,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}i=n;break}}for(let n of s)n!==i&&await n.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let n of c){let a=await e.evaluate(u=>{let f=u.getBoundingClientRect(),p=f.width>0&&f.height>0,m=u.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:f.top}},n);if(a.isVisible&&!a.isInStickyHeader){l=n,console.log(" Found More button by ID pattern (main)");break}}for(let n of c)n!==l&&await n.dispose().catch(()=>{});if(!l&&c.length>0&&(l=c[c.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let n=await e.evaluateHandle(()=>{let u=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),g=p.getAttribute("aria-label")||"",d=p.getBoundingClientRect();return d.top<100||d.top>600||d.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!u)return null;let f=u.parentElement;for(let p=0;p<8&&f;p++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==u)return m;f=f.parentElement}return null});l=n?.asElement?.()||null,l||await n?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),l),await S(500),await e.evaluate(u=>u.click(),l),await S(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let a=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(a||(a=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),a||(a=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),a||(a=await e.$('div[role="button"][aria-label*="Invite"]')),a||(a=await e.$('div[role="button"][aria-label*="connect"]')),!a){let u=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let p of f){let m=p.querySelector('a[href*="custom-invite"]');if(m)return m;for(let g of p.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});a=u?.asElement?.()||null,a||await u?.dispose?.().catch(()=>{})}if(!a){let u=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of f)for(let g of m.querySelectorAll('[role="menuitem"], a, div')){let d=g.innerText?.trim();d&&d.length<40&&p.push(d)}return[...new Set(p)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(u)}`)}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(n){console.log(" More dropdown click failed:",n.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let n=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),a=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(a)&&(console.log(` Skipping generic button: wrong person (${n})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function ao(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let o=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),r=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV";if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(u=>u.click(),t)]),await S(2e3);let a=e.url();if(a.includes("premium")||a.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await S(2e3),"premium_redirect"}else i?(await e.evaluate(a=>a.click(),t),await S(3e3)):(await e.evaluate(a=>a.click(),t),await S(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 c=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),n=e.url();return console.log(c?` \u2713 Connect sent \u2014 ${n}`:` \u26A0 No modal after connect click \u2014 ${n}`),"success"}async function co(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 S(1500);let o=await Me(e);if(o){await e.evaluate(r=>r.click(),o),await S(2e3);let s=await e.$('button[aria-label="Send without a note"]');if(s){try{await s.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function uo(e,t,o={}){let{message:s=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:c=[]}=o,n={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let a=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
9
|
-
--- Connecting: ${a} ---`),c.length>0){let w=X()[t]?.location;if(ft(w,c))return console.log(` \u26A0 Excluded location (stored): ${w}`),n.reason="excluded_location",n.profileInfo={location:w},n}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await dt(e,t),await S(2e3)),n.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"]),v=I=>{let x=(I||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(x)},A={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},k=document.querySelector("main");if(!k)return A;let O=[...Array.from(k.querySelectorAll("h1")),...Array.from(k.querySelectorAll("h2"))],P=Array.from(k.querySelectorAll("h2")),T=O.find(I=>{let x=I.textContent&&I.textContent.trim();return x&&x.length>1&&x.length<100&&!w.has(x)&&x!=="0 notifications"}),U=T?T.textContent.trim():null,F=T?T.parentElement:null;for(;F&&F!==k&&!Array.from(F.children).filter(R=>R.tagName==="P").some(R=>{let j=R.textContent&&R.textContent.trim();return j&&j.length>5&&!v(j)});)F=F.parentElement;let te=null,ce=null,le=null;if(F&&F!==k){let I=Array.from(F.children),x=I.filter(j=>j.tagName==="P").filter(j=>{let y=j.textContent&&j.textContent.trim();return y&&y.length>5&&!v(y)});x[0]&&(te=x[0].textContent.trim()),x[1]&&(ce=x[1].textContent.trim());let R=I.filter(j=>j.tagName==="DIV");for(let j=R.length-1;j>=0;j--){let y=R[j].textContent&&R[j].textContent.trim();if(y&&!(U&&y.startsWith(U))&&(le=y.split(/[·•]/)[0].trim(),le))break}}let we=null;if(F){let I=F.querySelectorAll("p, span, div");for(let x of I){let R=(x.textContent||"").trim().replace(/^[·•]\s*/,"");if(R==="1st"||R==="2nd"||R==="3rd"){we=R;break}}}let K=null,ue=P.find(I=>I.textContent&&I.textContent.trim()==="About");if(ue){let I=ue.parentElement;for(;I&&I.tagName!=="SECTION";)I=I.parentElement;I&&(K=(I.textContent||"").trim().replace(/^About\s*/,"").trim()||null,K&&(K=K.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let fe=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Se=fe&&fe.src||null,be=!!k.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:U,title:te,location:le,about:K,company:ce,connectionDegree:we,connectionsCount:null,mutualConnections:null,photoUrl:Se,hasVerifiedBadge:be}}),c.length>0){let w=n.profileInfo?.location,v=X()[t]?.location,A=w||v;if(ft(A,c))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${A}`),n.reason="excluded_location",n;!w&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await he(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),n.reason="pending",n;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),n.reason="connected",n;await oe(e);let p=await Me(e);if(!p&&(await oe(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),p=await Me(e)),!p))return console.log(" \u2717 Connect not found"),n.reason="button_not_found",n;if(n.method=p.method,await ao(e,p.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let w=await he(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await oe(e),await S(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(k=>k.scrollIntoView({behavior:"smooth",block:"center"}),v),await S(500),await v.click().catch(()=>e.evaluate(k=>k.click(),v)),await S(2e3);let A=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(A){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(P=>P.click(),A),await S(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 S(3e3),n.reason="premium_required",n;if(await he(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.method="more_dropdown",n.withCustomMessage=!1,n;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await S(500),n.reason="premium_required",n}catch(A){return console.log(" More dropdown failed:",A.message),await e.keyboard.press("Escape").catch(()=>{}),n.reason="premium_required",n}else return console.log(" \u2717 No More button found \u2014 Premium required"),n.reason="premium_required",n}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await S(500),n.reason="email_required",n}let d=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!d&&!b){let w=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let A=v.querySelector('button[aria-label="Add a note"]'),k=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!A,sendWithout:!!k}});if(w.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));d=v?.asElement?.()||null,d||await v.dispose().catch(()=>{})}if(w.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=v?.asElement?.()||null,b||await v.dispose().catch(()=>{})}}if(r){if(d&&s){if(console.log(" Adding personalized note..."),await d.click(),await S(1500),await e.$("div.modal-upsell")){let A=await co(e);return n.success=A,n.connectionSent=A,n.reason=A?"sent_without_note_upsell":"upsell_failed",n.withCustomMessage=!1,n}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let A=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),k=s.replace("{name}",A);await v.type(k,{delay:20}),await S(500);let O=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(O){try{await O.evaluate(P=>P.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (with note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_with_note",n.withCustomMessage=!0,n.messageSent=k,n}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}else if(d&&!s){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(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}}else{console.log(" Sending without note (custom messages disabled)...");let w=b;if(w){try{await w.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}if(p.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 S(4e3)),await oe(e),await S(500);let v=await e.$$('button[id*="profile-overflow-action"]'),A=null;for(let k of v){let O=await e.evaluate(P=>{let T=P.getBoundingClientRect();return{visible:T.width>0&&T.height>0,inSticky:!!P.closest('.sticky-header, [class*="sticky"]')}},k);if(O.visible&&!O.inSticky){A=k;break}}!A&&v.length>0&&(A=v[v.length-1]);for(let k of v)k!==A&&await k.dispose().catch(()=>{});if(A)try{await e.evaluate(O=>O.scrollIntoView({behavior:"smooth",block:"center"}),A),await S(500),await A.click().catch(()=>e.evaluate(O=>O.click(),A)),await S(2e3);let k=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(k){console.log(" Found Connect in More dropdown, clicking..."),n.method="more_dropdown",await e.evaluate(U=>U.click(),k),await S(3e3);let O=e.url();if(O.includes("/premium/")||O.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await he(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n):(n.reason="premium_required",n);if(await he(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;let T=await e.$('button[aria-label="Send without a note"]');if(T){console.log(" Modal appeared via More dropdown, sending without note...");try{await T.evaluate(U=>U.click())}catch{}return await S(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(k){console.log(" More dropdown fallback failed:",k.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),n.reason="modal_failed",n}catch(a){console.error(` \u2717 Error: ${a.message}`),n.reason="error",n.error=a.message;let u=a.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return n.fatal=!0,n;try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{n.fatal=!0}return n}}async function pt(e,t,o={}){let{message:s=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:n=null,excludeLocations:a=[],source:u="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
10
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),
|
|
11
|
+
`)}`;try{await Qe.addMessage(l,n)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Yt=Gt(import.meta.url),zt=oe.dirname(oe.dirname(Yt)),De=process.env.DATA_DIR?oe.resolve(process.env.DATA_DIR,"collected-profiles"):oe.join(zt,"collected-profiles"),Oe=oe.join(De,"run-log.json");function Kt(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";J.writeFileSync(s,o);for(let r=0;r<3;r++)try{J.renameSync(s,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Xe(){try{if(!J.existsSync(Oe))return{runs:[]};let e=JSON.parse(J.readFileSync(Oe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function et(e){J.existsSync(De)||J.mkdirSync(De,{recursive:!0});try{Kt(Oe,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function tt(e,t="default"){let o=Xe();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let s=new Date,r={timestamp:s.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>i),et(o),{script:e,mode:t,startTime:s.getTime(),runIndex:o.runs.length-1}}function Te(e,t,o=null,s=null){if(!e)return;let r=null;try{let l=Xe(),c=l.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=s,r=c.duration;else{let n=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());n&&(n.status=t,n.result=t,n.duration=Date.now()-e.startTime,n.stats=o,n.error=s,r=n.duration)}et(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Ze({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:s,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}$e();$e();import{getPluginConfig as Qt}from"@ilivemylife/graph-sdk";var Zt=await Qt();for(let[e,t]of Object.entries(Zt))process.env[e]===void 0&&(process.env[e]=t);var _n=process.env.LINKEDIN_NAME,le=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),jn=Object.freeze(new Set([le.DRAFT,le.CONFIRMED,le.NEEDS_REVIEW])),Rn=Object.freeze(new Set([le.DRAFT,le.CONFIRMED,le.REJECTED,le.NEEDS_REVIEW]));import"dotenv/config";import*as O from"fs";import*as R from"path";import{fileURLToPath as Xt}from"url";var eo=Xt(import.meta.url),to=R.dirname(R.dirname(eo)),K=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(to,"collected-profiles"),_e=R.join(K,"people.json"),Ln=R.join(K,"jobs.json"),st=R.join(K,"quota.json"),Un=R.join(K,"conversations.json"),Bn=R.join(K,"sync-state.json"),qn=R.join(K,"application-questions.json"),je=R.join(K,"profile-history"),pe=20,me=100,fe=null,oo=null,z=null,no=null,so=null,ro=null;function rt(){fe=null,oo=null,z=null,no=null,so=null,ro=null}function Ae(){O.existsSync(K)||O.mkdirSync(K,{recursive:!0})}function Re(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";O.writeFileSync(s,o);for(let r=0;r<3;r++)try{O.renameSync(s,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Ne(e,t){if(!O.existsSync(e))return null;try{let o=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${R.resolve(e)}`);let s=e+".backup";if(O.existsSync(s))try{let r=JSON.parse(O.readFileSync(s,"utf-8"));console.error(` Restored from ${s}`);try{O.copyFileSync(s,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function he(){return new Date().toISOString().split("T")[0]}var io=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt"],lo=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function Fe(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function ao(){O.existsSync(je)||O.mkdirSync(je,{recursive:!0})}function it(e){let t=Fe(e);return t?R.join(je,`${t}.json`):null}function co(e){let t=it(e);return t?Ne(t,`profile-history/${Fe(e)}.json`)||[]:[]}function uo(e,t){let o=it(e);if(!o)return;ao();let s=co(e);s.unshift(t);try{Re(o,s)}catch(r){console.error(`[!] Failed to append profile-history for ${Fe(e)}: ${r.message}`)}}function ot(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function nt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function fo(e,t){if(!e)return[];let o=[];for(let s of lo){let r=e[s],i=t[s];ot(r)||ot(i)||nt(r)!==nt(i)&&o.push(s)}return o}function po(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[s,r]of Object.entries(e))t.has(s)||(o[s]=r);return o}function ne(){return fe||(Ae(),fe=Ne(_e,"people.json")||{},fe)}function Me(e){Ae(),fe=e;try{Re(_e,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${R.resolve(_e)}`)}}function Ce(e,t={}){if(!e)return null;let o=ne(),s=he(),r=new Date().toISOString(),i=o[e];if(i){let l=fo(i,t);l.length>0&&(uo(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:po(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=s,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let c of io)if(t[c]!=null){if(Array.isArray(t[c])&&t[c].length===0&&Array.isArray(i[c])&&i[c].length>0)continue;i[c]=t[c]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else o[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,firstSeen:s,lastSeen:s,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return Me(o),o[e]}function lt(e,t){if(!e||!t)return;let o=ne(),s=o[e];if(!s)return;s.encounters||(s.encounters=[]);let i={date:he(),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),!s.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(s.encounters.push(i),s.lastUpdated=new Date().toISOString(),Me(o))}function at(e){return e&&ne()[e]?.connectionStatus||null}function ct(e,t,o={}){if(!e)return;o.profileInfo?Ce(e,o.profileInfo):ne()[e]||Ce(e,{});let s=ne(),r=s[e];r&&(r.connectionStatus=t,r.connectionDate=he(),r.connectionMethod=o.method||r.connectionMethod,r.messageSent=o.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),Me(s))}function ut(){return z||(Ae(),z=Ne(st,"quota.json"),(!z||!z.connections)&&(z={connections:[]}),z)}function mo(e){Ae(),z=e;try{Re(st,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function ft(e,t="unknown"){let o=ut(),s=new Date;o.connections.push({date:s.toISOString().split("T")[0],time:s.toTimeString().split(" ")[0],profileUrl:e,source:t}),mo(o)}function dt(){let e=ut(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(s=>s.date>=o)}function pt(){let e=dt(),t=he(),o=e.filter(n=>n.date===t).length,s=e.length,r=o>=pe,i=s>=me,l=!r&&!i,c={allowed:l,daily:{sent:o,max:pe},weekly:{sent:s,max:me}};return l||(c.reason=r?`Daily limit reached (${o}/${pe})`:`Weekly limit reached (${s}/${me})`),c}function Pe(){let e=dt(),t=he(),o=e.filter(r=>r.date===t).length,s=e.length;return{daily:{sent:o,max:pe,remaining:pe-o},weekly:{sent:s,max:me,remaining:me-s}}}async function yt(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let s=e.url();return s.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${s.slice(0,80)}`),!0}function gt(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(s=>o.includes(s.toLowerCase()))}async function go(e,t,o={}){let{extractExperience:s=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await ie(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await yt(e,t));let i=0;for(let n=0;n<2;n++){let u=await e.evaluate(()=>document.body.scrollHeight);for(let f=1;f<=6;f++)await e.evaluate(d=>window.scrollTo(0,d),u*f/6),await w(900);let a=await e.evaluate(()=>document.body.scrollHeight);if(a===i)break;i=a}await w(800);let l=await e.evaluate(()=>{let n=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"]),u=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"]),a=v=>{let C=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(C)},f={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:[]},d=document.querySelector("main");if(!d)return f;let p=[...Array.from(d.querySelectorAll("h1")),...Array.from(d.querySelectorAll("h2"))],g=Array.from(d.querySelectorAll("h2")),m=p.find(v=>{let C=v.textContent&&v.textContent.trim(),E=(C||"").replace(/\s*\(\d+\)$/,"").trim();return C&&C.length>1&&C.length<100&&!n.has(E)&&!u.has(E)}),S=m?m.textContent.trim():null,h=m?m.parentElement:null;for(;h&&h!==d&&!Array.from(h.children).filter(C=>C.tagName==="P").some(C=>{let E=C.textContent&&C.textContent.trim();return E&&E.length>5&&!a(E)});)h=h.parentElement;let b=null,A=null,$=null,I=null;if(h&&h!==d){let v=Array.from(h.children).filter(E=>E.tagName==="P").filter(E=>{let te=E.textContent&&E.textContent.trim();return te&&te.length>5&&!a(te)});if(v[0]&&(b=v[0].textContent.trim()),v[1]){let E=v[1].textContent.trim().split(/\s*[·•]\s*/);A=E[0]||null,E.length>1&&($=E.slice(1).join(" \xB7 "))}let C=Array.from(h.children).filter(E=>E.tagName==="DIV");for(let E=C.length-1;E>=0;E--){let te=C[E].textContent&&C[E].textContent.trim();if(te&&!(S&&te.startsWith(S))&&(I=te.split(/[·•]/)[0].trim(),I))break}}let F=null;if(h){let v=h.querySelectorAll("p, span, div");for(let C of v){let E=(C.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){F=E;break}}}let M=!!d.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),k=L&&L.src||null,_=d.textContent||"",re=null,X=_.match(/(\d+\+?)\s+connections\b/i);X&&(re=X[1]+" connections");let Y=null,ee=_.match(/(\d+)\s+mutual connection/i),de=_.match(/and\s+(\d+)\s+other mutual/i),Se=_.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ee?Y=parseInt(ee[1],10):de?Y=2+parseInt(de[1],10):Se&&(Y=2);let be=null,ve=null,D=g.find(v=>v.textContent&&v.textContent.trim()==="About");if(D){let v=D.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let C=(v.textContent||"").trim();C=C.replace(/^About\s*/,"").trim();let E=C.match(/Top skills\s*(.+?)$/i);if(E){let Ie=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ut=>Ut.trim()).filter(Boolean);Ie.length>0&&Ie.length<10&&(ve=Ie)}C=C.split(/\n?…\s*more/i)[0].trim(),C=C.split(/\n?\.\.\.\s*more/i)[0].trim(),C=C.split(/\bTop skills\b/i)[0].trim(),C=C.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),be=C||null}}let T=null,N=g.find(v=>v.textContent&&v.textContent.trim()==="Activity");if(N){let v=N.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let C=(v.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);C&&(T=parseInt(C[1].replace(/,/g,""),10))}}let j=[...new Set(g.map(v=>(v.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(v=>v&&v.length>1&&v.length<60&&v!==S).filter(v=>n.has(v)))],U=document.body.textContent||"",Pt=/#OpenToWork\b/i.test(U)||/\bOpen to work\b/.test(U),Lt=/#Hiring\b/i.test(U)||/\bI'?m hiring\b/i.test(U)||/\bWe are hiring\b/i.test(U);return{name:S,title:b,location:I,currentCompany:A,currentSchool:$,connectionDegree:F,hasVerifiedBadge:M,photoUrl:k,connectionsLevel:re,mutualConnectionsCount:Y,followers:T,openToWork:Pt,hiring:Lt,about:be,topSkills:ve,availableSections:j}});console.log(`Viewed: ${l.name} - ${l.title}`);let c=null;if(s){let{extractExperienceFromDetails:n}=await Promise.resolve().then(()=>(ht(),mt));c=await n(e,t),console.log(` + Experience: ${c.length} entries`)}return{...l,profileUrl:t,...c!==null&&{experience:c}}}catch(r){console.error(`Error viewing profile ${t}:`,r.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(r.message||""))throw r;return null}}async function ge(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),s=Array.from(o).map(n=>n.getAttribute("aria-label")),r=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:s,hasMessageBtn:!!r,hasConnectBtn:!!i};return o.length>0?{status:"pending",debug:l}:r&&!i?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Le(e){let t=null,o=await e.evaluate(()=>{let n=document.querySelector("h1")?.textContent?.trim();if(n&&!n.includes("notification"))return n;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(n=u.textContent?.trim(),n&&!n.includes("notification")))return n;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let n=await e.evaluate(()=>{let a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});n.count>0&&console.log(` S0: ${n.count} custom-invite links: ${JSON.stringify(n.labels)}`),t=await e.evaluateHandle(a=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=a.toLowerCase().split(" ")[0],p=null,g=null;for(let m of f){let S=m.getBoundingClientRect();if(S.width===0||S.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(d)){p=m;break}g||(g=m)}return p||g||null},o);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(o){let n=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${n}"`);let u=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let S=m.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&d.test(S)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},n);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of d){let m=g.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return g}return null},n);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(u)&&(console.log(` Skipping primary button: wrong person (${n})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let s=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');s.length===0&&(s=await e.$$('button[aria-label="Connect"]'));let r=o?o.split(" ")[0].toLowerCase():"",i=null;for(let n of s){let u=await e.evaluate((a,f)=>{let d=a.className.includes("muted"),p=a.className.includes("sticky-header")||a.className.includes("sticky"),g=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(a.getAttribute("aria-label")||"").toLowerCase(),S=m.includes("invite"),h=f?m.includes(f):!0;return{isMuted:d,isStickyHeader:p,inRecommendations:g,hasInvite:S,matchesName:h,ariaLabel:m}},n,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=n;break}}for(let n of s)n!==i&&await n.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let n of c){let u=await e.evaluate(a=>{let f=a.getBoundingClientRect(),d=f.width>0&&f.height>0,p=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:p,top:f.top}},n);if(u.isVisible&&!u.isInStickyHeader){l=n,console.log(" Found More button by ID pattern (main)");break}}for(let n of c)n!==l&&await n.dispose().catch(()=>{});if(!l&&c.length>0&&(l=c[c.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let n=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(d=>{let p=d.innerText?.trim(),g=d.getAttribute("aria-label")||"",m=d.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!a)return null;let f=a.parentElement;for(let d=0;d<8&&f;d++){for(let p of f.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==a)return p;f=f.parentElement}return null});l=n?.asElement?.()||null,l||await n?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await w(500),await e.evaluate(a=>a.click(),l),await w(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 a=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let p=d.querySelector('a[href*="custom-invite"]');if(p)return p;for(let g of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=a?.asElement?.()||null,u||await a?.dispose?.().catch(()=>{})}if(!u){let a=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let p of f)for(let g of p.querySelectorAll('[role="menuitem"], a, div')){let m=g.innerText?.trim();m&&m.length<40&&d.push(m)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(n){console.log(" More dropdown click failed:",n.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(u)&&(console.log(` Skipping generic button: wrong person (${n})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function yo(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let o=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),r=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV";if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(a=>a.click(),t)]),await w(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await w(3e3)):(await e.evaluate(u=>u.click(),t),await w(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 c=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),n=e.url();return console.log(c?` \u2713 Connect sent \u2014 ${n}`:` \u26A0 No modal after connect click \u2014 ${n}`),"success"}async function wo(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 w(1500);let o=await Le(e);if(o){await e.evaluate(r=>r.click(),o),await w(2e3);let s=await e.$('button[aria-label="Send without a note"]');if(s){try{await s.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function So(e,t,o={}){let{message:s=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:c=[]}=o,n={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
12
|
+
--- Connecting: ${u} ---`),c.length>0){let h=ne()[t]?.location;if(gt(h,c))return console.log(` \u26A0 Excluded location (stored): ${h}`),n.reason="excluded_location",n.profileInfo={location:h},n}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await ie(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await yt(e,t),await w(2e3)),n.profileInfo=await e.evaluate(()=>{let h=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=D=>{let T=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(T)},A={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},$=document.querySelector("main");if(!$)return A;let I=[...Array.from($.querySelectorAll("h1")),...Array.from($.querySelectorAll("h2"))],F=Array.from($.querySelectorAll("h2")),M=I.find(D=>{let T=D.textContent&&D.textContent.trim();return T&&T.length>1&&T.length<100&&!h.has(T)&&T!=="0 notifications"}),L=M?M.textContent.trim():null,k=M?M.parentElement:null;for(;k&&k!==$&&!Array.from(k.children).filter(N=>N.tagName==="P").some(N=>{let j=N.textContent&&N.textContent.trim();return j&&j.length>5&&!b(j)});)k=k.parentElement;let _=null,re=null,X=null;if(k&&k!==$){let D=Array.from(k.children),T=D.filter(j=>j.tagName==="P").filter(j=>{let U=j.textContent&&j.textContent.trim();return U&&U.length>5&&!b(U)});T[0]&&(_=T[0].textContent.trim()),T[1]&&(re=T[1].textContent.trim());let N=D.filter(j=>j.tagName==="DIV");for(let j=N.length-1;j>=0;j--){let U=N[j].textContent&&N[j].textContent.trim();if(U&&!(L&&U.startsWith(L))&&(X=U.split(/[·•]/)[0].trim(),X))break}}let Y=null;if(k){let D=k.querySelectorAll("p, span, div");for(let T of D){let N=(T.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){Y=N;break}}}let ee=null,de=F.find(D=>D.textContent&&D.textContent.trim()==="About");if(de){let D=de.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;D&&(ee=(D.textContent||"").trim().replace(/^About\s*/,"").trim()||null,ee&&(ee=ee.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Se=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),be=Se&&Se.src||null,ve=!!$.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:L,title:_,location:X,about:ee,company:re,connectionDegree:Y,connectionsCount:null,mutualConnections:null,photoUrl:be,hasVerifiedBadge:ve}}),c.length>0){let h=n.profileInfo?.location,b=ne()[t]?.location,A=h||b;if(gt(A,c))return console.log(` \u26A0 Excluded location (${h?"live":"stored"}): ${A}`),n.reason="excluded_location",n;!h&&b==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await ge(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),n.reason="pending",n;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),n.reason="connected",n;await ie(e);let d=await Le(e);if(!d&&(await ie(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),d=await Le(e)),!d))return console.log(" \u2717 Connect not found"),n.reason="button_not_found",n;if(n.method=d.method,await yo(e,d.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let h=await ge(e);if(h==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;console.log(` Status after upsell: ${h} \u2014 trying More dropdown...`),await ie(e),await w(1e3);let b=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(b)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),b),await w(500),await b.click().catch(()=>e.evaluate($=>$.click(),b)),await w(2e3);let A=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(A){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(F=>F.click(),A),await w(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 w(3e3),n.reason="premium_required",n;if(await ge(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.method="more_dropdown",n.withCustomMessage=!1,n;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),n.reason="premium_required",n}catch(A){return console.log(" More dropdown failed:",A.message),await e.keyboard.press("Escape").catch(()=>{}),n.reason="premium_required",n}else return console.log(" \u2717 No More button found \u2014 Premium required"),n.reason="premium_required",n}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let h=await e.$('button[aria-label="Dismiss"]');return h&&await h.click(),await w(500),n.reason="email_required",n}let m=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!m&&!S){let h=await e.evaluate(()=>{let b=document.querySelector("#interop-outlet")?.shadowRoot;if(!b)return{addNote:!1,sendWithout:!1};let A=b.querySelector('button[aria-label="Add a note"]'),$=b.querySelector('button[aria-label="Send without a note"]');return{addNote:!!A,sendWithout:!!$}});if(h.addNote){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=b?.asElement?.()||null,m||await b.dispose().catch(()=>{})}if(h.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(r){if(m&&s){if(console.log(" Adding personalized note..."),await m.click(),await w(1500),await e.$("div.modal-upsell")){let A=await wo(e);return n.success=A,n.connectionSent=A,n.reason=A?"sent_without_note_upsell":"upsell_failed",n.withCustomMessage=!1,n}let b=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(b){let A=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),$=s.replace("{name}",A);await b.type($,{delay:20}),await w(500);let I=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(I){try{await I.evaluate(F=>F.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (with note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_with_note",n.withCustomMessage=!0,n.messageSent=$,n}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(h=>h.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}else if(m&&!s){console.log(" No message provided, sending without note...");let h=await e.$('button[aria-label="Send without a note"]');if(h){try{await h.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}}else{console.log(" Sending without note (custom messages disabled)...");let h=S;if(h){try{await h.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await ie(e),await w(500);let b=await e.$$('button[id*="profile-overflow-action"]'),A=null;for(let $ of b){let I=await e.evaluate(F=>{let M=F.getBoundingClientRect();return{visible:M.width>0&&M.height>0,inSticky:!!F.closest('.sticky-header, [class*="sticky"]')}},$);if(I.visible&&!I.inSticky){A=$;break}}!A&&b.length>0&&(A=b[b.length-1]);for(let $ of b)$!==A&&await $.dispose().catch(()=>{});if(A)try{await e.evaluate(I=>I.scrollIntoView({behavior:"smooth",block:"center"}),A),await w(500),await A.click().catch(()=>e.evaluate(I=>I.click(),A)),await w(2e3);let $=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($){console.log(" Found Connect in More dropdown, clicking..."),n.method="more_dropdown",await e.evaluate(L=>L.click(),$),await w(3e3);let I=e.url();if(I.includes("/premium/")||I.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await ge(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n):(n.reason="premium_required",n);if(await ge(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;let M=await e.$('button[aria-label="Send without a note"]');if(M){console.log(" Modal appeared via More dropdown, sending without note...");try{await M.evaluate(L=>L.click())}catch{}return await w(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch($){console.log(" More dropdown fallback failed:",$.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),n.reason="modal_failed",n}catch(u){console.error(` \u2717 Error: ${u.message}`),n.reason="error",n.error=u.message;let a=u.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return n.fatal=!0,n;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{n.fatal=!0}return n}}async function wt(e,t,o={}){let{message:s=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:n=null,excludeLocations:u=[],source:a="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
13
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let p=Pe();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let d=0;for(let p=0;p<t.length;p++){let g=t[p];try{if(e.isClosed()){console.log(`
|
|
11
14
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
12
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${
|
|
13
|
-
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(
|
|
14
|
-
\u26A0 ${
|
|
15
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!l){let m=Fe();console.log(` Quota remaining: today ${m.daily.remaining}/${m.daily.max} | week ${m.weekly.remaining}/${m.weekly.max}`)}return f}import"dotenv/config";import*as N from"fs";import*as Y from"path";import{fileURLToPath as fo}from"url";var po=fo(import.meta.url),mo=Y.dirname(Y.dirname(po)),ge=process.env.DATA_DIR?Y.resolve(process.env.DATA_DIR,"collected-profiles"):Y.join(mo,"collected-profiles");function Pe(){N.existsSync(ge)||N.mkdirSync(ge,{recursive:!0})}function ho(){return new Date().toISOString().split("T")[0]}function mt(e,t=null){let o=t||ho();return Y.join(ge,`${e}-${o}.json`)}function ht(e,t=null){Pe();let o=mt(e,t);try{if(N.existsSync(o)){let s=N.readFileSync(o,"utf-8"),r=JSON.parse(s);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${o}`),r.profiles}}catch(s){console.error(`Error loading profiles from ${o}:`,s.message)}return[]}function gt(e,t=null){return ht(e,t).filter(s=>!s.processed)}function yt(e,t,o,s=null){Pe();let r=mt(e,s);try{if(!N.existsSync(r))return;let i=JSON.parse(N.readFileSync(r,"utf-8")),l=i.profiles.find(c=>c.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let c=o.profileInfo;c.name&&(l.name=c.name),c.title&&(l.title=c.title),c.location&&(l.location=c.location),c.company&&(l.company=c.company),c.connectionDegree&&(l.connectionDegree=c.connectionDegree),c.connectionsCount&&(l.connectionsCount=c.connectionsCount),c.mutualConnections&&(l.mutualConnections=c.mutualConnections),c.photoUrl&&(l.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=c.hasVerifiedBadge)}l.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),N.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function wt(e){let t=ht(e),o=t.filter(r=>r.processed),s=t.filter(r=>!r.processed);return{total:t.length,processed:o.length,unprocessed:s.length,statuses:o.reduce((r,i)=>(r[i.status]=(r[i.status]||0)+1,r),{})}}function St(){Pe();try{return N.readdirSync(ge).filter(t=>t.endsWith(".json")).map(t=>{let[o,s]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(N.readFileSync(Y.join(ge,t),"utf-8"));return{file:t,source:o,date:s,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:s,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as h from"fs";import*as Ve from"os";import*as E from"path";import{fileURLToPath as Bo}from"url";var Be={};Ee(Be,{NAME:()=>yo,VERSION:()=>go,up:()=>bo});import*as q from"fs";import*as $e from"path";var go=1,yo="normalize-jobs-and-questions",wo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],So=50;function Le(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function Ue(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";try{q.writeFileSync(s,o)}catch(r){try{q.unlinkSync(s)}catch{}throw r}try{q.renameSync(s,e)}catch(r){try{q.unlinkSync(s)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function bo(e,t){let o=$e.join(e,"jobs.json"),s=$e.join(t,"scouted-jobs.json"),r=$e.join(e,"application-questions.json"),i=Le(o)||{},l=Le(s)||{},c=0,n=[];for(let u of Object.keys(i)){if(!l[u])continue;let f=l[u],p=i[u];for(let m of wo)f[m]!=null&&p[m]==null&&(p[m]=f[m]);n.push(u),c++}c>0?(Ue(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Le(r);if(a&&Array.isArray(a.applications)){let u={},f=0;for(let p of a.applications){let m=p.jobId||"unknown";u[m]||(u[m]={applications:[]});let g=(p.questions||[]).map(d=>{let b={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=So?b.options=d.options:(b.optionsOmitted=!0,f++)),d.page&&(b.page=d.page),d.wasPreFilled&&(b.wasPreFilled=!0),d.wasRetry&&(b.wasRetry=!0),b});u[m].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||g.length,questions:g})}Ue(r,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(n.length>0){for(let u of n)delete l[u];Ue(s,l),console.log(` Phase 3: Removed ${n.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var qe={};Ee(qe,{NAME:()=>ko,VERSION:()=>vo,up:()=>Ao});import*as J from"fs";import*as bt from"path";var vo=2,ko="reset-unread-flags";function $o(e){return J.existsSync(e)?JSON.parse(J.readFileSync(e,"utf-8")):null}function Co(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";try{J.writeFileSync(s,o)}catch(r){try{J.unlinkSync(s)}catch{}throw r}try{J.renameSync(s,e)}catch(r){try{J.unlinkSync(s)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ao(e){let t=bt.join(e,"conversations.json"),o=$o(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let s=0;for(let r of Object.keys(o))o[r].unread===!0&&(o[r].unread=!1,s++);if(s===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Co(t,o),console.log(` Reset unread=false on ${s} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Je={};Ee(Je,{NAME:()=>Io,VERSION:()=>Eo,up:()=>_o});import*as H from"fs";import*as vt from"path";var Eo=3,Io="recompute-last-message-by",xo=new Set(["draft","confirmed","rejected","needs_review"]);function Do(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function Oo(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";try{H.writeFileSync(s,o)}catch(r){try{H.unlinkSync(s)}catch{}throw r}try{H.renameSync(s,e)}catch(r){try{H.unlinkSync(s)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function jo(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!xo.has(i.status));if(o.length===0)return"them";let s=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,l)=>l.t-i.t).map(i=>i.m),r=s.length>0?s:[...o].reverse();for(let i of r){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function _o(e){let t=vt.join(e,"conversations.json"),o=Do(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let s=process.env.LINKEDIN_NAME;if(!s||typeof s!="string"||!s.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 r=0,i=0,l=0;for(let c of Object.keys(o)){let n=o[c];if(!n||typeof n!="object")continue;Object.prototype.hasOwnProperty.call(n,"_cardSynced")&&(delete n._cardSynced,i++);let a=Array.isArray(n.messages)?n.messages:[],u=jo(a,s),f=u==="me"?"awaiting_reply":"unanswered_by_us";n.lastMessageBy!==u&&l++,n.lastMessageBy=u,n.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}Oo(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} 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.")}import"dotenv/config";import*as L from"path";import{fileURLToPath as To}from"url";var Ro=To(import.meta.url),No=L.dirname(L.dirname(Ro)),ye=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"market-research"):L.join(No,"market-research"),Hn=L.join(ye,"scouted-jobs.json"),Vn=L.join(ye,"discovered-people.json"),Wn=L.join(ye,"visit-log.json"),Gn=L.join(ye,"companies.json"),Yn=L.join(ye,"job-decisions.json");function kt(){Fo=null,Mo=null,Po=null,Lo=null,Uo=null}var Fo=null;var Mo=null;var Po=null;var Lo=null;var Uo=null;var qo=Bo(import.meta.url),Jo=E.dirname(qo),Ho=E.dirname(E.dirname(Jo));function Vo(e){return e&&(e==="~"?Ve.homedir():e.startsWith("~/")||e.startsWith("~\\")?E.join(Ve.homedir(),e.slice(2)):e)}var V=process.env.DATA_DIR?E.resolve(Vo(process.env.DATA_DIR)):Ho,re=E.join(V,"collected-profiles"),ie=E.join(V,"market-research"),M=E.join(V,".schema-version"),$t=[E.join(re,".schema-version"),E.join(ie,".schema-version")],ee=3,z=[{version:1,module:Be},{version:2,module:qe},{version:3,module:Je}];(function(){z.sort((s,r)=>s.version-r.version);let t=new Set;for(let s of z){if(!Number.isInteger(s.version)||s.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(s.version)} (must be positive integer)`);if(t.has(s.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${s.version}`);t.add(s.version);let r=s.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${s.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==s.version)throw new Error(`MIGRATION_REGISTRY: v${s.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=z.length?z[z.length-1].version:0;if(o!==ee)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${ee}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let s=0;s<z.length;s++){let r=s+1;if(z[s].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${s} but found v${z[s].version}`)}})();function It(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
15
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=at(g.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,n&&await n(g,f,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl}`);let S=null;if(l){let h=await go(e,g.profileUrl);h?(Ce(g.profileUrl,{...h,source:a}),f.viewed++,S={success:!0,reason:"viewed",connectionSent:!1,profileInfo:h}):(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 h=pt();if(!h.allowed){console.log(` \u26A0 Global quota exhausted: ${h.reason}`);break}if(S=await So(e,g.profileUrl,{message:s,useCustomMessage:r,excludeLocations:u}),S.success)f.connectionsSent++,S.connectionSent&&ft(g.profileUrl,a);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(`
|
|
16
|
+
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(S?.reason==="error"){if(d++,d>=3){console.log(`
|
|
17
|
+
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(S&&S.reason&&(ct(g.profileUrl,S.reason,{method:S.method,messageSent:S.messageSent,profileInfo:S.profileInfo}),lt(g.profileUrl,{source:a||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:S.reason})),n&&await n(g,f,S),p<t.length-1){let h=c+Math.random()*2e3;await w(h)}}if(console.log(`
|
|
18
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!l){let p=Pe();console.log(` Quota remaining: today ${p.daily.remaining}/${p.daily.max} | week ${p.weekly.remaining}/${p.weekly.max}`)}return f}import"dotenv/config";import*as P from"fs";import*as Q from"path";import{fileURLToPath as bo}from"url";var vo=bo(import.meta.url),ko=Q.dirname(Q.dirname(vo)),ye=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"collected-profiles"):Q.join(ko,"collected-profiles");function Ue(){P.existsSync(ye)||P.mkdirSync(ye,{recursive:!0})}function $o(){return new Date().toISOString().split("T")[0]}function St(e,t=null){let o=t||$o();return Q.join(ye,`${e}-${o}.json`)}function bt(e,t=null){Ue();let o=St(e,t);try{if(P.existsSync(o)){let s=P.readFileSync(o,"utf-8"),r=JSON.parse(s);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${o}`),r.profiles}}catch(s){console.error(`Error loading profiles from ${o}:`,s.message)}return[]}function vt(e,t=null){return bt(e,t).filter(s=>!s.processed)}function kt(e,t,o,s=null){Ue();let r=St(e,s);try{if(!P.existsSync(r))return;let i=JSON.parse(P.readFileSync(r,"utf-8")),l=i.profiles.find(c=>c.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let c=o.profileInfo;c.name&&(l.name=c.name),c.title&&(l.title=c.title),c.location&&(l.location=c.location),c.company&&(l.company=c.company),c.connectionDegree&&(l.connectionDegree=c.connectionDegree),c.connectionsCount&&(l.connectionsCount=c.connectionsCount),c.mutualConnections&&(l.mutualConnections=c.mutualConnections),c.photoUrl&&(l.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=c.hasVerifiedBadge)}l.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),P.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function $t(e){let t=bt(e),o=t.filter(r=>r.processed),s=t.filter(r=>!r.processed);return{total:t.length,processed:o.length,unprocessed:s.length,statuses:o.reduce((r,i)=>(r[i.status]=(r[i.status]||0)+1,r),{})}}function Ct(){Ue();try{return P.readdirSync(ye).filter(t=>t.endsWith(".json")).map(t=>{let[o,s]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(P.readFileSync(Q.join(ye,t),"utf-8"));return{file:t,source:o,date:s,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:s,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as y from"fs";import*as Ge from"os";import*as x from"path";import{fileURLToPath as zo}from"url";var Je={};ke(Je,{NAME:()=>Ao,VERSION:()=>Co,up:()=>Io});import*as H from"fs";import*as Ee from"path";var Co=1,Ao="normalize-jobs-and-questions",Eo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],xo=50;function Be(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function qe(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";try{H.writeFileSync(s,o)}catch(r){try{H.unlinkSync(s)}catch{}throw r}try{H.renameSync(s,e)}catch(r){try{H.unlinkSync(s)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Io(e,t){let o=Ee.join(e,"jobs.json"),s=Ee.join(t,"scouted-jobs.json"),r=Ee.join(e,"application-questions.json"),i=Be(o)||{},l=Be(s)||{},c=0,n=[];for(let a of Object.keys(i)){if(!l[a])continue;let f=l[a],d=i[a];for(let p of Eo)f[p]!=null&&d[p]==null&&(d[p]=f[p]);n.push(a),c++}c>0?(qe(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Be(r);if(u&&Array.isArray(u.applications)){let a={},f=0;for(let d of u.applications){let p=d.jobId||"unknown";a[p]||(a[p]={applications:[]});let g=(d.questions||[]).map(m=>{let S={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=xo?S.options=m.options:(S.optionsOmitted=!0,f++)),m.page&&(S.page=m.page),m.wasPreFilled&&(S.wasPreFilled=!0),m.wasRetry&&(S.wasRetry=!0),S});a[p].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||g.length,questions:g})}qe(r,a),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(a).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(n.length>0){for(let a of n)delete l[a];qe(s,l),console.log(` Phase 3: Removed ${n.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var He={};ke(He,{NAME:()=>Oo,VERSION:()=>Do,up:()=>jo});import*as V from"fs";import*as At from"path";var Do=2,Oo="reset-unread-flags";function To(e){return V.existsSync(e)?JSON.parse(V.readFileSync(e,"utf-8")):null}function _o(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";try{V.writeFileSync(s,o)}catch(r){try{V.unlinkSync(s)}catch{}throw r}try{V.renameSync(s,e)}catch(r){try{V.unlinkSync(s)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function jo(e){let t=At.join(e,"conversations.json"),o=To(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let s=0;for(let r of Object.keys(o))o[r].unread===!0&&(o[r].unread=!1,s++);if(s===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}_o(t,o),console.log(` Reset unread=false on ${s} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ve={};ke(Ve,{NAME:()=>No,VERSION:()=>Ro,up:()=>Uo});import*as W from"fs";import*as Et from"path";var Ro=3,No="recompute-last-message-by",Fo=new Set(["draft","confirmed","rejected","needs_review"]);function Mo(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function Po(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";try{W.writeFileSync(s,o)}catch(r){try{W.unlinkSync(s)}catch{}throw r}try{W.renameSync(s,e)}catch(r){try{W.unlinkSync(s)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function Lo(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!Fo.has(i.status));if(o.length===0)return"them";let s=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,l)=>l.t-i.t).map(i=>i.m),r=s.length>0?s:[...o].reverse();for(let i of r){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Uo(e){let t=Et.join(e,"conversations.json"),o=Mo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let s=process.env.LINKEDIN_NAME;if(!s||typeof s!="string"||!s.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 r=0,i=0,l=0;for(let c of Object.keys(o)){let n=o[c];if(!n||typeof n!="object")continue;Object.prototype.hasOwnProperty.call(n,"_cardSynced")&&(delete n._cardSynced,i++);let u=Array.isArray(n.messages)?n.messages:[],a=Lo(u,s),f=a==="me"?"awaiting_reply":"unanswered_by_us";n.lastMessageBy!==a&&l++,n.lastMessageBy=a,n.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}Po(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} 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.")}import"dotenv/config";import*as q from"path";import{fileURLToPath as Bo}from"url";var qo=Bo(import.meta.url),Jo=q.dirname(q.dirname(qo)),we=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"market-research"):q.join(Jo,"market-research"),Xn=q.join(we,"scouted-jobs.json"),es=q.join(we,"discovered-people.json"),ts=q.join(we,"visit-log.json"),os=q.join(we,"companies.json"),ns=q.join(we,"job-decisions.json");function xt(){Ho=null,Vo=null,Wo=null,Go=null,Yo=null}var Ho=null;var Vo=null;var Wo=null;var Go=null;var Yo=null;var Ko=zo(import.meta.url),Qo=x.dirname(Ko),Zo=x.dirname(x.dirname(Qo));function Xo(e){return e&&(e==="~"?Ge.homedir():e.startsWith("~/")||e.startsWith("~\\")?x.join(Ge.homedir(),e.slice(2)):e)}var G=process.env.DATA_DIR?x.resolve(Xo(process.env.DATA_DIR)):Zo,ce=x.join(G,"collected-profiles"),ue=x.join(G,"market-research"),B=x.join(G,".schema-version"),It=[x.join(ce,".schema-version"),x.join(ue,".schema-version")],se=3,Z=[{version:1,module:Je},{version:2,module:He},{version:3,module:Ve}];(function(){Z.sort((s,r)=>s.version-r.version);let t=new Set;for(let s of Z){if(!Number.isInteger(s.version)||s.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(s.version)} (must be positive integer)`);if(t.has(s.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${s.version}`);t.add(s.version);let r=s.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${s.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==s.version)throw new Error(`MIGRATION_REGISTRY: v${s.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=Z.length?Z[Z.length-1].version:0;if(o!==se)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${se}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let s=0;s<Z.length;s++){let r=s+1;if(Z[s].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${s} but found v${Z[s].version}`)}})();function _t(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
16
19
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
17
|
-
`),process.exit(1));try{
|
|
18
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
19
|
-
`),process.exit(1))}let e;try{e=
|
|
20
|
-
[FATAL] DATA_DIR (${
|
|
20
|
+
`),process.exit(1));try{y.mkdirSync(G,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
21
|
+
[FATAL] Cannot create DATA_DIR (${G}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
22
|
+
`),process.exit(1))}let e;try{e=y.statSync(G)}catch(t){console.error(`
|
|
23
|
+
[FATAL] DATA_DIR (${G}) is not accessible: ${t.message}
|
|
21
24
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
22
|
-
[FATAL] DATA_DIR (${
|
|
23
|
-
`),process.exit(1));for(let t of[
|
|
25
|
+
[FATAL] DATA_DIR (${G}) 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.
|
|
26
|
+
`),process.exit(1));for(let t of[ce,ue]){let o;try{o=y.lstatSync(t)}catch(s){if(s.code==="ENOENT")continue;throw s}o.isSymbolicLink()&&(console.error(`
|
|
24
27
|
[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.
|
|
25
|
-
`),process.exit(1))}}var
|
|
26
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
28
|
+
`),process.exit(1))}}var ae=x.join(G,".migration-lock");function en(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return y.writeFileSync(ae,e,{flag:"wx"}),!0}catch(s){if(s.code!=="EEXIST")throw s}let t;try{t=JSON.parse(y.readFileSync(ae,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let s=!1;try{process.kill(t.pid,0),s=!0}catch(l){l.code==="EPERM"&&(s=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(i=Date.now()-l)}s&&i<r&&(console.error(`
|
|
29
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${ae}
|
|
27
30
|
`),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.
|
|
28
|
-
`),process.exit(1)),s&&i>=r&&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 o=
|
|
31
|
+
`),process.exit(1)),s&&i>=r&&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 o=ae+".tmp";try{return y.writeFileSync(o,e),y.renameSync(o,ae),!0}catch(s){try{y.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${s.message}`)}}function Ye(){try{if(JSON.parse(y.readFileSync(ae,"utf-8")).pid!==process.pid)return;y.unlinkSync(ae)}catch{}}var Dt=!1;function tn(){if(Dt)return;Dt=!0;let e=()=>{try{Ye()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function on(){if(y.existsSync(B))return;let e=[],t=[];for(let i of It)if(y.existsSync(i))try{e.push({file:i,schema:xe(i)})}catch(l){t.push({file:i,err:l.message})}if(t.length>0){console.error(`
|
|
29
32
|
[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(`
|
|
30
33
|
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.
|
|
31
34
|
`),process.exit(1)}if(e.length===0)return;let o=e.map(i=>i.schema.version);if(new Set(o).size>1){console.error(`
|
|
32
35
|
[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.
|
|
33
|
-
`),process.exit(1)}let s=e[0].schema,r=
|
|
34
|
-
[FATAL] ${
|
|
35
|
-
`),process.exit(1)}let t=
|
|
36
|
-
[FATAL] ${
|
|
37
|
-
`),process.exit(1)),t}function
|
|
38
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
39
|
-
`),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${
|
|
36
|
+
`),process.exit(1)}let s=e[0].schema,r=B+".tmp";try{y.writeFileSync(r,JSON.stringify(s,null,2)),y.renameSync(r,B)}catch(i){try{y.unlinkSync(r)}catch{}throw i}for(let i of It)if(y.existsSync(i))try{y.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${B}`)}function nn(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 xe(e){let t=y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ot(){if(on(),!y.existsSync(B))return{version:0,migrations:[]};let e;try{e=xe(B)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
37
|
+
[FATAL] ${B} is not valid JSON: ${o.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.
|
|
38
|
+
`),process.exit(1)}let t=nn(e);return t===null&&(console.error(`
|
|
39
|
+
[FATAL] ${B} 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.
|
|
40
|
+
`),process.exit(1)),t}function jt(e){try{y.chmodSync(e,384)}catch{}}function sn(e){if(_t(),y.existsSync(B))try{if(y.lstatSync(B).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${B}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=B+".tmp";try{y.writeFileSync(t,JSON.stringify(e,null,2)),jt(t),y.renameSync(t,B)}catch(o){try{y.unlinkSync(t)}catch{}throw o}}function Tt(e,t){if(!y.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,s=y.readdirSync(e).filter(c=>{let n=c.toLowerCase();if(n.includes(".backup")||n===".schema-version"||n.endsWith(".tmp"))return!1;try{return y.statSync(x.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,l=[];for(let c of s){let n=x.join(e,c),u=x.join(e,c+o);if(y.existsSync(u)){i++;continue}try{Nt(n,u),r++}catch(a){l.push({file:c,err:a.message})}}if(l.length>0){let c=new Error(`Failed to back up ${l.length} file(s) in ${x.basename(e)}/: `+l.map(n=>`${n.file} (${n.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${x.basename(e)}/ (${o})${c}`)}}var We=!1;async function Rt(){if(We)return;_t(),un();let t=Ot().version;if(t===se){We=!0;return}tn(),en(),process.on("exit",Ye),t>se&&(console.error(`
|
|
41
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${se}.`),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.
|
|
42
|
+
`),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${se}.
|
|
40
43
|
`),process.exit(1)),console.log(`
|
|
41
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
44
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${se}`);let o=fn();if(!o.ok){console.error(`
|
|
42
45
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of o.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
43
46
|
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'.
|
|
44
|
-
`),process.exit(1)}let s=
|
|
45
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{
|
|
47
|
+
`),process.exit(1)}let s=Z.filter(r=>r.version>t);for(let r of s){console.log(`
|
|
48
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{Tt(ce,r.version),Tt(ue,r.version)}catch(n){console.error(`
|
|
46
49
|
[FATAL] Pre-migration backup failed for ${i}: ${n.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
47
|
-
`),process.exit(1)}let c=r.module;try{await c.up(
|
|
48
|
-
[FATAL] Migration ${i} failed: ${n.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let
|
|
49
|
-
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${
|
|
50
|
-
`))}catch(
|
|
51
|
-
`)}process.exit(1)}try{let n=new Date().toISOString(),
|
|
50
|
+
`),process.exit(1)}let c=r.module;try{await c.up(ce,ue)}catch(n){console.error(`
|
|
51
|
+
[FATAL] Migration ${i} failed: ${n.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let u=dn(l);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.
|
|
52
|
+
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
53
|
+
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
54
|
+
`)}process.exit(1)}try{let n=new Date().toISOString(),u={version:r.version,name:c.NAME||i,appliedAt:n},a=Ot();a.version=r.version,a.migratedAt=n,a.migrations=a.migrations||[],a.migrations.push(u),sn(a)}catch(n){console.error(`
|
|
52
55
|
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${n.message}`),console.error(` Your data is in the v${r.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.
|
|
53
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{
|
|
54
|
-
\u2713 Schema is now at v${
|
|
55
|
-
`)}var
|
|
56
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{rt()}catch{}try{xt()}catch{}We=!0,Ye(),console.log(`
|
|
57
|
+
\u2713 Schema is now at v${se}
|
|
58
|
+
`)}var rn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ln(e){let t=e.toLowerCase();return rn.some(o=>o.test(t))}var an=6e4;function cn(){let e=Date.now(),t=[];for(let o of[G,ce,ue]){if(!y.existsSync(o))continue;let s;try{s=y.readdirSync(o)}catch{continue}for(let r of s){if(!ln(r))continue;let i=x.join(o,r);try{let l=y.statSync(i);if(!l.isFile()||e-l.mtimeMs<an)continue;t.push({dir:o,file:r,fullPath:i})}catch{}}}return t}function un({verbose:e=!1}={}){let t=cn();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let s of t)try{y.unlinkSync(s.fullPath),o++,e&&console.log(` Removed orphan: ${x.basename(s.dir)}/${s.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${s.fullPath}: ${r.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function fn(){let e=[];for(let t of[ce,ue]){if(!y.existsSync(t))continue;let o=y.readdirSync(t).filter(s=>{let r=s.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let s of o){let r=x.join(t,s);try{xe(r)}catch(i){e.push({dir:x.basename(t),file:s,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function dn(e){let t=[],o=[];for(let i of[ce,ue]){if(!y.existsSync(i))continue;let l=y.readdirSync(i).filter(c=>c.endsWith(e));for(let c of l){let n=x.join(i,c),u=c.slice(0,-e.length),a=x.join(i,u);try{u.toLowerCase().endsWith(".json")?xe(n):y.accessSync(n,y.constants.R_OK),t.push({backupPath:n,originalPath:a,fileName:c,dir:i})}catch(f){o.push(`${x.basename(i)}/${c}: ${f.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let s=0,r=[];for(let{backupPath:i,originalPath:l,fileName:c,dir:n}of t)try{Nt(i,l),s++}catch(u){r.push(`${x.basename(n)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:s}:{ok:!0,restored:s}}function Nt(e,t){let o=t+".tmp";try{y.copyFileSync(e,o),jt(o)}catch(s){try{y.unlinkSync(o)}catch{}throw s}try{y.renameSync(o,t)}catch(s){try{y.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${t} (${s.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 r.code=s.code,r}throw s}}import Ft from"fs";import pn from"path";var mn="cookies.json";function hn(){let e=process.env.ILML_SCOPE_DIR;return e?pn.join(e,"plugins-state","linkedin","cookies.json"):mn}function Mt(){let e=hn();if(!Ft.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Ft.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read cookies at ${e}: ${s.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}await Rt();function yn(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(o=>o.trim()).filter(Boolean));return e}async function wn(){let e=yn();if(e.list){console.log(`
|
|
56
59
|
\u{1F4C2} Available profile files:
|
|
57
|
-
`);let n=
|
|
60
|
+
`);let n=Ct();if(n.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let u of n)console.log(` ${u.file}`),console.log(` Total: ${u.count}, Unprocessed: ${u.unprocessed}`);console.log(""),process.exit(0)}console.log(`
|
|
58
61
|
========================================`),console.log("Profile Funnel Runner"),console.log(`========================================
|
|
59
|
-
`),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=
|
|
62
|
+
`),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=vt(e.source,e.date);console.log(`
|
|
60
63
|
Profiles to process: ${t.length}`),t.length===0&&(console.log(`
|
|
61
64
|
\u2705 No unprocessed profiles. Nothing to do!`),process.exit(0)),console.log(`
|
|
62
|
-
Profiles:`),t.slice(0,10).forEach((n,
|
|
65
|
+
Profiles:`),t.slice(0,10).forEach((n,u)=>{console.log(` ${u+1}. ${n.name||"Unknown"} - ${n.fromJob?.company||"N/A"}`)}),t.length>10&&console.log(` ... and ${t.length-10} more`),console.log(`
|
|
63
66
|
Press Enter to start, or Ctrl+C to cancel...`),await new Promise(n=>{process.stdin.once("data",()=>n())}),console.log(`
|
|
64
67
|
\u{1F680} Starting browser...
|
|
65
|
-
`);let o=await
|
|
68
|
+
`);let o=await gn.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),s=await o.newPage();try{let n=Mt();await s.setCookie(...n),console.log(`\u2713 Cookies loaded
|
|
66
69
|
`)}catch(n){console.error(`
|
|
67
70
|
[!] ${n.message}
|
|
68
|
-
`),await o.close(),process.exit(1)}let r=e.viewOnly?"view-only":"connect",i=
|
|
71
|
+
`),await o.close(),process.exit(1)}let r=e.viewOnly?"view-only":"connect",i=tt("funnel",r),l=await wt(s,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(n,u,a)=>{kt(e.source,n.profileUrl,{status:a.reason,connectionSent:a.connectionSent,withCustomMessage:a.withCustomMessage,message:a.messageSent,method:a.method,reason:a.reason,error:a.error,profileInfo:a.profileInfo})}});console.log(`
|
|
69
72
|
========================================`),console.log("Funnel Complete!"),console.log(`========================================
|
|
70
|
-
`);let c
|
|
71
|
-
Status breakdown:`);for(let[n,
|
|
73
|
+
`);let c=$t(e.source);if(console.log(`Processed: ${c.processed}/${c.total}`),console.log(`Remaining: ${c.unprocessed}`),Object.keys(c.statuses).length>0){console.log(`
|
|
74
|
+
Status breakdown:`);for(let[n,u]of Object.entries(c.statuses))console.log(` ${n}: ${u}`)}Te(i,"success",{sent:l.connectionsSent,viewed:l.viewed,errors:l.errors,skippedPending:l.skipped?.pending||0,skippedConnected:l.skipped?.connected||0}),await o.close(),process.exit(0)}wn().catch(e=>{console.error("Funnel failed:",e);try{Te(null,"error",null,e.message)}catch{}process.exit(1)});
|
package/dist/help.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import*as t from"fs";import*as a from"path";import{fileURLToPath as f}from"url";var p=f(import.meta.url),r=a.dirname(p);function d(){let o=r;for(let n=0;n<5;n++){let e=a.join(o,"ilml-plugin.json");if(t.existsSync(e))return e;let s=a.dirname(o);if(s===o)break;o=s}console.error("Could not find ilml-plugin.json near",r),process.exit(1)}var l=JSON.parse(t.readFileSync(d(),"utf8")),u=process.argv.slice(2),i=u[0];function h(o,n){if(console.log(`
|
|
2
|
+
ilml linkedin ${o}`),n.description&&console.log(`
|
|
3
|
+
${n.description}`),n.usage&&(console.log(`
|
|
4
|
+
USAGE`),console.log(` ${n.usage}`)),n.flags&&Object.keys(n.flags).length>0){console.log(`
|
|
5
|
+
FLAGS`);for(let[e,s]of Object.entries(n.flags))console.log(` ${e.padEnd(22)} ${s}`)}n.banRisk&&(console.log(`
|
|
6
|
+
BAN RISK`),console.log(` ${n.banRisk}`)),n.useWhen&&(console.log(`
|
|
7
|
+
WHEN TO USE`),console.log(` ${n.useWhen}`)),!n.description&&!n.usage&&!n.flags&&!n.banRisk&&!n.useWhen&&console.log(` (no metadata in manifest \u2014 try ${o} --help if the command supports it)`),console.log("")}if(i&&l.commands[i])h(i,l.commands[i]);else if(i)console.error(`
|
|
8
|
+
Unknown command: ${i}
|
|
9
|
+
`),console.error(` Available: ${Object.keys(l.commands).join(", ")}
|
|
10
|
+
`),process.exit(1);else{console.log(`
|
|
11
|
+
${l.name} v${l.version} \u2014 ${l.description}
|
|
12
|
+
`),console.log(` Available commands:
|
|
13
|
+
`);let o=Object.entries(l.commands),n=Math.max(...o.map(([e])=>e.length));for(let[e,s]of o){let c=s.description||"",g=c.length>90?c.slice(0,90)+"\u2026":c,m=s.banRisk?.startsWith("HIGH")?" \u26A0":"";console.log(` ${e.padEnd(n+2)}${g}${m}`)}console.log(`
|
|
14
|
+
For details on one command:`),console.log(" ilml linkedin help <command>"),console.log(" ilml linkedin <command> --help (new commands support this; older ones print usage on bad args)"),console.log(`
|
|
15
|
+
AI agents: machine-readable command metadata lives in ilml-plugin.json (commands{}.description / usage / flags / banRisk / useWhen).`),console.log("")}
|