ilml-plugin-linkedin 1.14.1 → 1.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +3 -0
- package/dist/connect.mjs +74 -74
- package/dist/version.mjs +1 -1
- package/ilml-plugin.json +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.14.2
|
|
4
|
+
- **`connect fill` now validates that a person's title actually matches the category before queueing them.** The `category` on your contacts is set automatically and is sometimes wrong (e.g. a "Software Developer" tagged `founder`), which meant `fill --category=founder` could queue the wrong people. `fill` now re-checks each person's stored title against the category and drops the ones that don't match; people with no stored title are held rather than queued (it never visits a profile to fetch one, so there's no added ban risk). Pass `--no-validate` for the old behaviour. The summary shows how many were filtered.
|
|
5
|
+
|
|
3
6
|
## 1.14.1
|
|
4
7
|
- **`ilml linkedin connect` sends without a note by default; notes are now opt-in.** LinkedIn caps personalised connection-request notes to a handful per month, and the "Add a note" dialog fails once you're out (which showed up as failed sends). So `connect run` now sends plain requests unless you add `--with-notes`, which sends the notes you saved with `connect note` — spend those few monthly notes deliberately. A saved note shows as 📝 in `connect list`.
|
|
5
8
|
- **connect stops itself after 3 failed sends in a row.** If sends keep failing — often LinkedIn's own (invisible) weekly invite limit — connect halts instead of hammering your account, and saves what LinkedIn showed on each failure to `<DATA_DIR>/collected-profiles/connect-diagnostics/` (the on-page message + a screenshot). That's so the exact limit wording can be recognised precisely in a later version, from real data rather than a guess.
|
package/dist/connect.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var Jn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{for(var n in t)Jn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Hn}from"@ilivemylife/graph-sdk";var Wn,Xr,Se,Zr,es,dt=re(async()=>{Wn=await Hn();for(let[e,t]of Object.entries(Wn))process.env[e]===void 0&&(process.env[e]=t);Xr=process.env.LINKEDIN_NAME,Se=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Zr=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.NEEDS_REVIEW])),es=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.REJECTED,Se.NEEDS_REVIEW]))});import"dotenv/config";import*as F from"fs";import*as U from"path";import{fileURLToPath as Yn}from"url";function Jt(){Ee=null,Kn=null,se=null,zn=null,Xn=null,Zn=null}function ze(){F.existsSync(ie)||F.mkdirSync(ie,{recursive:!0})}function Fe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";F.writeFileSync(o,n);for(let r=0;r<3;r++)try{F.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw i}}function Le(e,t){if(!F.existsSync(e))return null;try{let n=JSON.parse(F.readFileSync(e,"utf-8"));try{F.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${U.resolve(e)}`);let o=e+".backup";if(F.existsSync(o))try{let r=JSON.parse(F.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{F.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function Me(){return new Date().toISOString().split("T")[0]}function Q(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function no(){F.existsSync(pt)||F.mkdirSync(pt,{recursive:!0})}function Ht(e){let t=Q(e);return t?U.join(pt,`${t}.json`):null}function oo(e){let t=Ht(e);return t?Le(t,`profile-history/${Q(e)}.json`)||[]:[]}function ro(e,t){let n=Ht(e);if(!n)return;no();let o=oo(e);o.unshift(t);try{Fe(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${Q(e)}: ${r.message}`)}}function qt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Bt(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 n=[];for(let o of to){let r=e[o],i=t[o];qt(r)||qt(i)||Bt(r)!==Bt(i)&&n.push(o)}return n}function io(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function G(){return Ee||(ze(),Ee=Le(ft,"people.json")||{},Ee)}function mt(e){ze(),Ee=e;try{Fe(ft,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${U.resolve(ft)}`)}}function Ke(e,t={}){if(!e)return null;let n=G(),o=Me(),r=new Date().toISOString(),i=n[e];if(i){let a=so(i,t);a.length>0&&(ro(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:a,snapshot:io(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let u of eo)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(i[u])&&i[u].length>0)continue;i[u]=t[u]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return mt(n),n[e]}function Wt(e,t){if(!e||!t)return;let n=G(),o=n[e];if(!o)return;o.encounters||(o.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),!o.encounters.some(u=>u.date===i.date&&u.source===i.source&&u.action===i.action&&(u.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),mt(n))}function Yt(e){return e&&G()[e]?.connectionStatus||null}function Xe(e,t,n={}){if(!e)return;n.profileInfo?Ke(e,n.profileInfo):G()[e]||Ke(e,{});let o=G(),r=o[e];r&&(r.connectionStatus=t,r.connectionDate=Me(),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),mt(o))}function Gt(){return se||(ze(),se=Le(Ut,"quota.json"),(!se||!se.connections)&&(se={connections:[]}),se)}function lo(e){ze(),se=e;try{Fe(Ut,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Qt(e,t="unknown"){let n=Gt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),lo(n)}function Kt(){let e=Gt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Pe(){let e=Kt(),t=Me(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Oe,i=o>=je,a=!r&&!i,u={allowed:a,daily:{sent:n,max:Oe},weekly:{sent:o,max:je}};return a||(u.reason=r?`Daily limit reached (${n}/${Oe})`:`Weekly limit reached (${o}/${je})`),u}function be(){let e=Kt(),t=Me(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Oe,remaining:Oe-n},weekly:{sent:o,max:je,remaining:je-o}}}var Gn,Qn,ie,ft,ss,Ut,is,ls,as,pt,Vt,Oe,je,Ee,Kn,se,zn,Xn,Zn,eo,to,qe=re(async()=>{await dt();Gn=Yn(import.meta.url),Qn=U.dirname(U.dirname(Gn)),ie=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"collected-profiles"):U.join(Qn,"collected-profiles"),ft=U.join(ie,"people.json"),ss=U.join(ie,"jobs.json"),Ut=U.join(ie,"quota.json"),is=U.join(ie,"conversations.json"),ls=U.join(ie,"sync-state.json"),as=U.join(ie,"application-questions.json"),pt=U.join(ie,"profile-history"),Vt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Oe=Vt(process.env.CONNECT_MAX_DAILY,20),je=Vt(process.env.CONNECT_MAX_WEEKLY,100),Ee=null,Kn=null,se=null,zn=null,Xn=null,Zn=null;eo=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],to=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var pn={};fe(pn,{cookiesExist:()=>ir,getCookiesPath:()=>ot,loadCookies:()=>sr,saveCookies:()=>rr});import Ie from"fs";import fn from"path";function ot(){let e=process.env.ILML_SCOPE_DIR;return e?fn.join(e,"plugins-state","linkedin","cookies.json"):nr}function or(){let e=ot(),t=fn.dirname(e);return t&&t!=="."&&!Ie.existsSync(t)&&Ie.mkdirSync(t,{recursive:!0}),e}function rr(e){let t=or();return Ie.writeFileSync(t,JSON.stringify(e)),t}function sr(){let e=ot();if(!Ie.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Ie.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function ir(){return Ie.existsSync(ot())}var nr,mn=re(()=>{nr="cookies.json"});var hn={};fe(hn,{cleanSearchName:()=>fr,delayed:()=>S,dismissPremiumOverlay:()=>ye,ensureInboxPage:()=>ur,parseLinkedInTime:()=>cr,safeParseInt:()=>dr,stripDesignations:()=>pr,utilityFunction:()=>lr});function lr(){console.log("Utility function called...")}function Ve(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function cr(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let u=Ve(n),s=new Date(t);return u?s.setHours(u.hours,u.minutes,0,0):s.setHours(0,0,0,0),s.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let u=ar[o[1].toLowerCase()],s=Ve(o[2]||""),l=new Date(t),d=l.getDay()-u;return d<=0&&(d+=7),l.setDate(l.getDate()-d),s?l.setHours(s.hours,s.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let u=At[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(r[2],10),l=parseInt(r[3],10),c=Ve(r[4]||"");return new Date(l,u,s,c?.hours||0,c?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let u=At[i[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(i[2],10),l=Ve(i[3]||""),c=t.getFullYear(),d=new Date(c,u,s,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}let a=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(a){let u=At[a[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(a[2],10),l=Ve(a[3]||""),c=t.getFullYear(),d=new Date(c,u,s,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}return null}async function S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ur(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function dr(e){return parseInt(e,10)||0}async function ye(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),a=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),u=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||a||u){let s=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:r.substring(0,80)};let l=o.querySelectorAll("button");for(let c of l){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function fr(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function pr(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var At,ar,rt=re(()=>{At={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},ar={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var gn={};fe(gn,{extractCertificationsFromDetails:()=>wr,extractEducationFromDetails:()=>gr,extractExperienceFromDetails:()=>mr,extractFeaturedFromDetails:()=>hr,extractRecommendationsFromDetails:()=>Sr,extractSkillsFromDetails:()=>yr});async function mr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)r++,await S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function a(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(h=>h.tagName==="DIV");if(p.length<3)continue;let g=p.filter(h=>(h.textContent||"").trim().length>50);g.length<3||(f.textContent||"").length<500||d.push({el:f,count:g.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let u=a(i);if(!u)return[];let s=Array.from(u.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function l(c){let d=c[0]||null,f=null,p=null;if(c[1]){let v=c[1].split("\xB7").map(O=>O.trim());f=v[0]||null,v[1]&&(p=v[1])}let g=c.findIndex(v=>/(\d{4}|present)/i.test(v)&&/(-|–|—)/i.test(v)&&v.length<80),h=null,w=null;if(g>=0){let v=c[g].split("\xB7").map(O=>O.trim());h=v[0]||null,v[1]&&(w=v[1])}let m=null,y=-1;if(g>=0&&c[g+1]){let v=c[g+1],O=/^[>*\-•]|^>/.test(v),V=/https?:\/\//.test(v),N=/\d{4}/.test(v),j=/,/.test(v)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(v);!O&&!V&&!N&&v.length<100&&j&&(m=v,y=g+1)}let k=null,$=-1,D=c[c.length-1];if(D&&/and\s+\+\d+\s+skills?$/i.test(D)){$=c.length-1;let v=D.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);v&&(k={listed:v[1].split(",").map(O=>O.trim()),additional:parseInt(v[2],10)})}let C=new Set([0,1,g,y,$].filter(v=>v>=0)),I=c.filter((v,O)=>!C.has(O)),M=I.length>0?I.join(`
|
|
1
|
+
var Hn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{for(var n in t)Hn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Wn}from"@ilivemylife/graph-sdk";var Gn,Yn,pe,Kn,Qn,Qe=re(async()=>{Gn=await Wn();for(let[e,t]of Object.entries(Gn))process.env[e]===void 0&&(process.env[e]=t);Yn=process.env.LINKEDIN_NAME,pe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Kn=Object.freeze(new Set([pe.DRAFT,pe.CONFIRMED,pe.NEEDS_REVIEW])),Qn=Object.freeze(new Set([pe.DRAFT,pe.CONFIRMED,pe.REJECTED,pe.NEEDS_REVIEW]))});import"dotenv/config";import*as M from"fs";import*as B from"path";import{fileURLToPath as zn}from"url";function Vt(){Ee=null,eo=null,ie=null,to=null,no=null,oo=null}function Xe(){M.existsSync(se)||M.mkdirSync(se,{recursive:!0})}function Fe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";M.writeFileSync(o,n);for(let r=0;r<3;r++)try{M.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Le(e,t){if(!M.existsSync(e))return null;try{let n=JSON.parse(M.readFileSync(e,"utf-8"));try{M.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(M.existsSync(o))try{let r=JSON.parse(M.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{M.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{M.copyFileSync(e,e+".corrupted")}catch{}return null}}function Pe(){return new Date().toISOString().split("T")[0]}function K(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function so(){M.existsSync(pt)||M.mkdirSync(pt,{recursive:!0})}function Ht(e){let t=K(e);return t?B.join(pt,`${t}.json`):null}function ao(e){let t=Ht(e);return t?Le(t,`profile-history/${K(e)}.json`)||[]:[]}function lo(e,t){let n=Ht(e);if(!n)return;so();let o=ao(e);o.unshift(t);try{Fe(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${K(e)}: ${r.message}`)}}function qt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ut(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function co(e,t){if(!e)return[];let n=[];for(let o of io){let r=e[o],s=t[o];qt(r)||qt(s)||Ut(r)!==Ut(s)&&n.push(o)}return n}function uo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function Y(){return Ee||(Xe(),Ee=Le(ft,"people.json")||{},Ee)}function mt(e){Xe(),Ee=e;try{Fe(ft,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(ft)}`)}}function ze(e,t={}){if(!e)return null;let n=Y(),o=Pe(),r=new Date().toISOString(),s=n[e];if(s){let l=co(s,t);l.length>0&&(lo(e,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:l,snapshot:uo(s)}),s.lastSnapshotAt=r),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=r,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let u of ro)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(s[u])&&s[u].length>0)continue;s[u]=t[u]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=r)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return mt(n),n[e]}function Wt(e,t){if(!e||!t)return;let n=Y(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let s={date:Pe(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(s.jobId=String(t.jobId)),t.jobTitle&&(s.jobTitle=t.jobTitle),t.jobCompany&&(s.jobCompany=t.jobCompany),!o.encounters.some(u=>u.date===s.date&&u.source===s.source&&u.action===s.action&&(u.jobId||"")===(s.jobId||""))&&(o.encounters.push(s),o.lastUpdated=new Date().toISOString(),mt(n))}function Gt(e){return e&&Y()[e]?.connectionStatus||null}function Ze(e,t,n={}){if(!e)return;n.profileInfo?ze(e,n.profileInfo):Y()[e]||ze(e,{});let o=Y(),r=o[e];r&&(r.connectionStatus=t,r.connectionDate=Pe(),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),mt(o))}function Yt(){return ie||(Xe(),ie=Le(Bt,"quota.json"),(!ie||!ie.connections)&&(ie={connections:[]}),ie)}function fo(e){Xe(),ie=e;try{Fe(Bt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Kt(e,t="unknown"){let n=Yt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),fo(n)}function Qt(){let e=Yt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function qe(){let e=Qt(),t=Pe(),n=e.filter(i=>i.date===t).length,o=e.length,r=n>=Oe,s=o>=Me,l=!r&&!s,u={allowed:l,daily:{sent:n,max:Oe},weekly:{sent:o,max:Me}};return l||(u.reason=r?`Daily limit reached (${n}/${Oe})`:`Weekly limit reached (${o}/${Me})`),u}function Se(){let e=Qt(),t=Pe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Oe,remaining:Oe-n},weekly:{sent:o,max:Me,remaining:Me-o}}}var Xn,Zn,se,ft,ai,Bt,li,ci,ui,pt,Jt,Oe,Me,Ee,eo,ie,to,no,oo,ro,io,Ue=re(async()=>{await Qe();Xn=zn(import.meta.url),Zn=B.dirname(B.dirname(Xn)),se=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Zn,"collected-profiles"),ft=B.join(se,"people.json"),ai=B.join(se,"jobs.json"),Bt=B.join(se,"quota.json"),li=B.join(se,"conversations.json"),ci=B.join(se,"sync-state.json"),ui=B.join(se,"application-questions.json"),pt=B.join(se,"profile-history"),Jt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Oe=Jt(process.env.CONNECT_MAX_DAILY,20),Me=Jt(process.env.CONNECT_MAX_WEEKLY,100),Ee=null,eo=null,ie=null,to=null,no=null,oo=null;ro=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],io=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var mn={};fe(mn,{cookiesExist:()=>dr,getCookiesPath:()=>rt,loadCookies:()=>ur,saveCookies:()=>cr});import _e from"fs";import pn from"path";function rt(){let e=process.env.ILML_SCOPE_DIR;return e?pn.join(e,"plugins-state","linkedin","cookies.json"):ar}function lr(){let e=rt(),t=pn.dirname(e);return t&&t!=="."&&!_e.existsSync(t)&&_e.mkdirSync(t,{recursive:!0}),e}function cr(e){let t=lr();return _e.writeFileSync(t,JSON.stringify(e)),t}function ur(){let e=rt();if(!_e.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=_e.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function dr(){return _e.existsSync(rt())}var ar,hn=re(()=>{ar="cookies.json"});var gn={};fe(gn,{cleanSearchName:()=>yr,delayed:()=>w,dismissPremiumOverlay:()=>we,ensureInboxPage:()=>hr,parseLinkedInTime:()=>mr,safeParseInt:()=>gr,stripDesignations:()=>wr,utilityFunction:()=>fr});function fr(){console.log("Utility function called...")}function Ve(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function mr(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let u=Ve(n),i=new Date(t);return u?i.setHours(u.hours,u.minutes,0,0):i.setHours(0,0,0,0),i.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let u=pr[o[1].toLowerCase()],i=Ve(o[2]||""),a=new Date(t),d=a.getDay()-u;return d<=0&&(d+=7),a.setDate(a.getDate()-d),i?a.setHours(i.hours,i.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let u=At[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let i=parseInt(r[2],10),a=parseInt(r[3],10),c=Ve(r[4]||"");return new Date(a,u,i,c?.hours||0,c?.minutes||0,0,0).toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(s){let u=At[s[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let i=parseInt(s[2],10),a=Ve(s[3]||""),c=t.getFullYear(),d=new Date(c,u,i,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}let l=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(l){let u=At[l[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let i=parseInt(l[2],10),a=Ve(l[3]||""),c=t.getFullYear(),d=new Date(c,u,i,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}return null}async function w(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function hr(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function gr(e){return parseInt(e,10)||0}async function we(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=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"),u=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||l||u){let i=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:r.substring(0,80)};let a=o.querySelectorAll("button");for(let c of a){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function yr(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function wr(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var At,pr,it=re(()=>{At={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},pr={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var yn={};fe(yn,{extractCertificationsFromDetails:()=>$r,extractEducationFromDetails:()=>kr,extractExperienceFromDetails:()=>br,extractFeaturedFromDetails:()=>Sr,extractRecommendationsFromDetails:()=>Cr,extractSkillsFromDetails:()=>vr});async function br(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let s=0;s<5;s++)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 s=document.querySelector("main");if(!s)return[];function l(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(f.textContent||"").length<500||d.push({el:f,count:h.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let u=l(s);if(!u)return[];let i=Array.from(u.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function a(c){let d=c[0]||null,f=null,p=null;if(c[1]){let x=c[1].split("\xB7").map(j=>j.trim());f=x[0]||null,x[1]&&(p=x[1])}let h=c.findIndex(x=>/(\d{4}|present)/i.test(x)&&/(-|–|—)/i.test(x)&&x.length<80),m=null,S=null;if(h>=0){let x=c[h].split("\xB7").map(j=>j.trim());m=x[0]||null,x[1]&&(S=x[1])}let y=null,k=-1;if(h>=0&&c[h+1]){let x=c[h+1],j=/^[>*\-•]|^>/.test(x),J=/https?:\/\//.test(x),R=/\d{4}/.test(x),O=/,/.test(x)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(x);!j&&!J&&!R&&x.length<100&&O&&(y=x,k=h+1)}let v=null,C=-1,$=c[c.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){C=c.length-1;let x=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);x&&(v={listed:x[1].split(",").map(j=>j.trim()),additional:parseInt(x[2],10)})}let g=new Set([0,1,h,k,C].filter(x=>x>=0)),E=c.filter((x,j)=>!g.has(j)),L=E.length>0?E.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:d,company:f,employmentType:p,dates:
|
|
4
|
-
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return
|
|
5
|
-
${
|
|
3
|
+
`):null;return{title:d,company:f,employmentType:p,dates:m,duration:S,location:y,description:L,skills:v,_raw:c}}return i.map(c=>{let f=(c.innerText||"").trim().split(`
|
|
4
|
+
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return a(f)}).filter(c=>c.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function He(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let u of document.querySelectorAll("button"))if(/^Load more$/i.test((u.textContent||"").trim()))return u.click(),!0;return!1});)s++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function Ge(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw r;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function Sr(e,t){return Ge(t,"featured","extractFeaturedFromDetails",async()=>(await He(e,t,"featured"),await e.evaluate(`(() => {
|
|
5
|
+
${We}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
8
8
|
if (!main) return [];
|
|
@@ -42,8 +42,8 @@ var Jn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{
|
|
|
42
42
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
43
43
|
return true;
|
|
44
44
|
});
|
|
45
|
-
})()`)))}async function
|
|
46
|
-
${
|
|
45
|
+
})()`)))}async function kr(e,t){return Ge(t,"education","extractEducationFromDetails",async()=>(await He(e,t,"education"),await e.evaluate(`(() => {
|
|
46
|
+
${We}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
49
49
|
if (!main) return [];
|
|
@@ -79,8 +79,8 @@ var Jn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{
|
|
|
79
79
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
80
80
|
return true;
|
|
81
81
|
});
|
|
82
|
-
})()`)))}async function
|
|
83
|
-
${
|
|
82
|
+
})()`)))}async function vr(e,t){return Ge(t,"skills","extractSkillsFromDetails",async()=>(await He(e,t,"skills"),await e.evaluate(`(() => {
|
|
83
|
+
${We}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
86
86
|
if (!main) return [];
|
|
@@ -111,8 +111,8 @@ var Jn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
115
|
-
${
|
|
114
|
+
})()`)))}async function $r(e,t){return Ge(t,"certifications","extractCertificationsFromDetails",async()=>(await He(e,t,"certifications"),await e.evaluate(`(() => {
|
|
115
|
+
${We}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
118
118
|
if (!main) return [];
|
|
@@ -136,8 +136,8 @@ var Jn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{
|
|
|
136
136
|
|
|
137
137
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
138
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function
|
|
140
|
-
${
|
|
139
|
+
})()`)))}async function Cr(e,t){return Ge(t,"recommendations","extractRecommendationsFromDetails",async()=>(await He(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
140
|
+
${We}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
143
143
|
if (!main) return [];
|
|
@@ -172,7 +172,7 @@ var Jn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{
|
|
|
172
172
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
173
173
|
return true;
|
|
174
174
|
});
|
|
175
|
-
})()`)))}var
|
|
175
|
+
})()`)))}var We,wn=re(()=>{it();We=`
|
|
176
176
|
function findEntryContainer(root) {
|
|
177
177
|
const candidates = [];
|
|
178
178
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,22 +235,22 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});var bn={};fe(bn,{clickConnectButton:()=>It,default:()=>vr,detectConnectionStatus:()=>Ae,findConnectButton:()=>Ye,runFunnel:()=>Sn,sendConnectionRequest:()=>Dt,shouldExcludeLocation:()=>st,viewProfile:()=>Et});async function wn(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function st(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Et(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:a=!1,extractRecommendations:u=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await wn(e,t));let c=0;for(let k=0;k<2;k++){let $=await e.evaluate(()=>document.body.scrollHeight);for(let C=1;C<=6;C++)await e.evaluate(I=>window.scrollTo(0,I),$*C/6),await S(900);let D=await e.evaluate(()=>document.body.scrollHeight);if(D===c)break;c=D}await S(800);let d=await e.evaluate(()=>{let k=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),$=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),D=x=>{let A=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(A)},C={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},I=document.querySelector("main");if(!I)return C;let M=[...Array.from(I.querySelectorAll("h1")),...Array.from(I.querySelectorAll("h2"))],v=Array.from(I.querySelectorAll("h2")),O=M.find(x=>{let A=x.textContent&&x.textContent.trim(),E=(A||"").replace(/\s*\(\d+\)$/,"").trim();return A&&A.length>1&&A.length<100&&!k.has(E)&&!$.has(E)}),V=O?O.textContent.trim():null,N=O?O.parentElement:null;for(;N&&N!==I&&!Array.from(N.children).filter(A=>A.tagName==="P").some(A=>{let E=A.textContent&&A.textContent.trim();return E&&E.length>5&&!D(E)});)N=N.parentElement;let j=null,W=null,_=null,J=null;if(N&&N!==I){let x=Array.from(N.children).filter(E=>E.tagName==="P").filter(E=>{let de=E.textContent&&E.textContent.trim();return de&&de.length>5&&!D(de)});if(x[0]&&(j=x[0].textContent.trim()),x[1]){let E=x[1].textContent.trim().split(/\s*[·•]\s*/);W=E[0]||null,E.length>1&&(_=E.slice(1).join(" \xB7 "))}let A=Array.from(N.children).filter(E=>E.tagName==="DIV");for(let E=A.length-1;E>=0;E--){let de=A[E].textContent&&A[E].textContent.trim();if(de&&!(V&&de.startsWith(V))&&(J=de.split(/[·•]/)[0].trim(),J))break}}let H=null;if(N){let x=N.querySelectorAll("p, span, div");for(let A of x){let E=(A.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){H=E;break}}}let ue=!!I.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=T&&T.src||null,q=I.textContent||"",B=null,te=q.match(/(\d+\+?)\s+connections\b/i);te&&(B=te[1]+" connections");let Qe=null,_t=q.match(/(\d+)\s+mutual connection/i),Ot=q.match(/and\s+(\d+)\s+other mutual/i),Pn=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);_t?Qe=parseInt(_t[1],10):Ot?Qe=2+parseInt(Ot[1],10):Pn&&(Qe=2);let jt=null,Ft=null,Lt=v.find(x=>x.textContent&&x.textContent.trim()==="About");if(Lt){let x=Lt.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let A=(x.textContent||"").trim();A=A.replace(/^About\s*/,"").trim();let E=A.match(/Top skills\s*(.+?)$/i);if(E){let ut=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Vn=>Vn.trim()).filter(Boolean);ut.length>0&&ut.length<10&&(Ft=ut)}A=A.split(/\n?…\s*more/i)[0].trim(),A=A.split(/\n?\.\.\.\s*more/i)[0].trim(),A=A.split(/\bTop skills\b/i)[0].trim(),A=A.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),jt=A||null}}let Mt=null,Pt=v.find(x=>x.textContent&&x.textContent.trim()==="Activity");if(Pt){let x=Pt.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let A=(x.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);A&&(Mt=parseInt(A[1].replace(/,/g,""),10))}}let qn=[...new Set(v.map(x=>(x.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(x=>x&&x.length>1&&x.length<60&&x!==V).filter(x=>k.has(x)))],_e=document.body.textContent||"",Bn=/#OpenToWork\b/i.test(_e)||/\bOpen to work\b/.test(_e),Un=/#Hiring\b/i.test(_e)||/\bI'?m hiring\b/i.test(_e)||/\bWe are hiring\b/i.test(_e);return{name:V,title:j,location:J,currentCompany:W,currentSchool:_,connectionDegree:H,hasVerifiedBadge:ue,photoUrl:P,connectionsLevel:B,mutualConnectionsCount:Qe,followers:Mt,openToWork:Bn,hiring:Un,about:jt,topSkills:Ft,availableSections:qn}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,g=null,h=null,w=null,m=null;if(o||r||i||a||u||s){let k=await Promise.resolve().then(()=>(yn(),gn));o&&(f=await k.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(p=await k.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(g=await k.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),a&&(h=await k.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),u&&(w=await k.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.length} entries`)),s&&(m=await k.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${m.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...g!==null&&{education:g},...h!==null&&{skillsFull:h},...w!==null&&{recommendations:w},...m!==null&&{certifications:m}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function Ae(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(s=>s.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"]'),a={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!r,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:a}:r&&!i?{status:"connected",debug:a}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:a}:{status:"not_connected",debug:a}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Ye(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let l=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(l&&(s=l.textContent?.trim(),s&&!s.includes("notification")))return s;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p=null,g=null;for(let h of d){let w=h.getBoundingClientRect();if(w.width===0||w.height===0)continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=h;break}g||(g=h)}return p||g||null},n);let l=t?.asElement?.()||null;if(l||await t?.dispose?.().catch(()=>{}),l)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:l,method:"connect_link"}}if(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let l=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(h=>{let w=h.getAttribute("aria-label")||"";return(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&f.test(w)}).map(h=>h.getAttribute("aria-label")?.slice(0,50))},s);l.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(l)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of f){let h=g.getAttribute("aria-label")||"";if((h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&p.test(h))return g}return null},s);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),l=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(l)&&(console.log(` Skipping primary button: wrong person (${s})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of o){let l=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),g=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(c.getAttribute("aria-label")||"").toLowerCase(),w=h.includes("invite"),m=d?h.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:g,hasInvite:w,matchesName:m,ariaLabel:h}},s,r);if(!l.isMuted&&!l.isStickyHeader&&!l.inRecommendations){if(l.hasInvite&&!l.matchesName){console.log(` Skipping secondary button: wrong person (${l.ariaLabel})`);continue}i=s;break}}for(let s of o)s!==i&&await s.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let a=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let s of u){let l=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},s);if(l.isVisible&&!l.isInStickyHeader){a=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of u)s!==a&&await s.dispose().catch(()=>{});if(!a&&u.length>0&&(a=u[u.length-1],console.log(" Found More button by ID pattern (last)")),a||(a=await e.$('button[aria-label="More actions"]'),a&&console.log(" Found More button by aria-label")),!a){let s=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),g=f.getAttribute("aria-label")||"",h=f.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});a=s?.asElement?.()||null,a||await s?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),a),await S(500),await e.evaluate(c=>c.click(),a),await S(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let l=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(l||(l=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),l||(l=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),l||(l=await e.$('div[role="button"][aria-label*="Invite"]')),l||(l=await e.$('div[role="button"][aria-label*="connect"]')),!l){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let g of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});l=c?.asElement?.()||null,l||await c?.dispose?.().catch(()=>{})}if(!l){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let g of p.querySelectorAll('[role="menuitem"], a, div')){let h=g.innerText?.trim();h&&h.length<40&&f.push(h)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(l)return console.log(" Found: More dropdown"),{button:l,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),l=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(l)&&(console.log(` Skipping generic button: wrong person (${s})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function It(e,t){await e.evaluate(l=>l.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let n=await e.evaluate(l=>({tag:l.tagName,ariaLabel:l.getAttribute("aria-label"),href:l.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV";if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(c=>c.click(),t)]),await S(2e3);let l=e.url();if(l.includes("premium")||l.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(l=>l.click(),t),await S(3e3)):(await e.evaluate(l=>l.click(),t),await S(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let u=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),s=e.url();return console.log(u?` \u2713 Connect sent \u2014 ${s}`:` \u26A0 No modal after connect click \u2014 ${s}`),"success"}async function br(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 n=await Ye(e);if(n){await e.evaluate(r=>r.click(),n),await S(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.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 Dt(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let u=Pe();if(!u.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${u.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:u.reason,profileInfo:null}}let a=await kr(e,t,n);return a.connectionSent&&!i&&Qt(t,o),a}async function kr(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:a=!0,excludeLocations:u=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
239
|
-
--- Connecting: ${l} ---`),u.length>0){let m=G()[t]?.location;if(st(m,u))return console.log(` \u26A0 Excluded location (stored): ${m}`),s.reason="excluded_location",s.profileInfo={location:m},s}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await wn(e,t),await S(2e3)),s.profileInfo=await e.evaluate(()=>{let m=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"]),y=T=>{let P=(T||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},k={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 k;let D=[...Array.from($.querySelectorAll("h1")),...Array.from($.querySelectorAll("h2"))],C=Array.from($.querySelectorAll("h2")),I=D.find(T=>{let P=T.textContent&&T.textContent.trim();return P&&P.length>1&&P.length<100&&!m.has(P)&&P!=="0 notifications"}),M=I?I.textContent.trim():null,v=I?I.parentElement:null;for(;v&&v!==$&&!Array.from(v.children).filter(q=>q.tagName==="P").some(q=>{let B=q.textContent&&q.textContent.trim();return B&&B.length>5&&!y(B)});)v=v.parentElement;let O=null,V=null,N=null;if(v&&v!==$){let T=Array.from(v.children),P=T.filter(B=>B.tagName==="P").filter(B=>{let te=B.textContent&&B.textContent.trim();return te&&te.length>5&&!y(te)});P[0]&&(O=P[0].textContent.trim()),P[1]&&(V=P[1].textContent.trim());let q=T.filter(B=>B.tagName==="DIV");for(let B=q.length-1;B>=0;B--){let te=q[B].textContent&&q[B].textContent.trim();if(te&&!(M&&te.startsWith(M))&&(N=te.split(/[·•]/)[0].trim(),N))break}}let j=null;if(v){let T=v.querySelectorAll("p, span, div");for(let P of T){let q=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(q==="1st"||q==="2nd"||q==="3rd"){j=q;break}}}let W=null,_=C.find(T=>T.textContent&&T.textContent.trim()==="About");if(_){let T=_.parentElement;for(;T&&T.tagName!=="SECTION";)T=T.parentElement;T&&(W=(T.textContent||"").trim().replace(/^About\s*/,"").trim()||null,W&&(W=W.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let J=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),H=J&&J.src||null,ue=!!$.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:M,title:O,location:N,about:W,company:V,connectionDegree:j,connectionsCount:null,mutualConnections:null,photoUrl:H,hasVerifiedBadge:ue}}),u.length>0){let m=s.profileInfo?.location,y=G()[t]?.location,k=m||y;if(st(k,u))return console.log(` \u26A0 Excluded location (${m?"live":"stored"}): ${k}`),s.reason="excluded_location",s;!m&&y==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ae(e);if(d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await ye(e);let f=await Ye(e);if(!f&&(await ye(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),f=await Ye(e)),!f))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;if(s.method=f.method,await It(e,f.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 m=await Ae(e);if(m==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${m} \u2014 trying More dropdown...`),await ye(e),await S(1e3);let y=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(y)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),y),await S(500),await y.click().catch(()=>e.evaluate($=>$.click(),y)),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..."),await e.evaluate(C=>C.click(),k),await S(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 S(3e3),s.reason="premium_required",s;if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await S(500),s.reason="premium_required",s}catch(k){return console.log(" More dropdown failed:",k.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let m=await e.$('button[aria-label="Dismiss"]');return m&&await m.click(),await S(500),s.reason="email_required",s}let h=await e.$('button[aria-label="Add a note"]'),w=await e.$('button[aria-label="Send without a note"]');if(!h&&!w){let m=await e.evaluate(()=>{let y=document.querySelector("#interop-outlet")?.shadowRoot;if(!y)return{addNote:!1,sendWithout:!1};let k=y.querySelector('button[aria-label="Add a note"]'),$=y.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!$}});if(m.addNote){let y=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=y?.asElement?.()||null,h||await y.dispose().catch(()=>{})}if(m.sendWithout){let y=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));w=y?.asElement?.()||null,w||await y.dispose().catch(()=>{})}}if(r){if(h&&o){if(console.log(" Adding personalized note..."),await h.click(),await S(1500),await e.$("div.modal-upsell")){let k=await br(e);return s.success=k,s.connectionSent=k,s.reason=k?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let y=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(y){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),$=o.replace("{name}",k);await y.type($,{delay:20}),await S(500);let D=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(D){try{await D.evaluate(C=>C.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=$,s}}}else if(w){console.log(" Sending without note...");try{await w.evaluate(m=>m.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(h&&!o){console.log(" No message provided, sending without note...");let m=await e.$('button[aria-label="Send without a note"]');if(m){try{await m.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let m=w;if(m){try{await m.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(f.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 ye(e),await S(500);let y=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let $ of y){let D=await e.evaluate(C=>{let I=C.getBoundingClientRect();return{visible:I.width>0&&I.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},$);if(D.visible&&!D.inSticky){k=$;break}}!k&&y.length>0&&(k=y[y.length-1]);for(let $ of y)$!==k&&await $.dispose().catch(()=>{});if(k)try{await e.evaluate(D=>D.scrollIntoView({behavior:"smooth",block:"center"}),k),await S(500),await k.click().catch(()=>e.evaluate(D=>D.click(),k)),await S(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..."),s.method="more_dropdown",await e.evaluate(M=>M.click(),$),await S(3e3);let D=e.url();if(D.includes("/premium/")||D.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await Ae(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let I=await e.$('button[aria-label="Send without a note"]');if(I){console.log(" Modal appeared via More dropdown, sending without note...");try{await I.evaluate(M=>M.click())}catch{}return await S(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch($){console.log(" More dropdown fallback failed:",$.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(l){console.error(` \u2717 Error: ${l.message}`),s.reason="error",s.error=l.message;let c=l.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{s.fatal=!0}return s}}async function Sn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:a=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:s=null,excludeLocations:l=[],source:c="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
240
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${
|
|
238
|
+
`});var kn={};fe(kn,{clickConnectButton:()=>_t,default:()=>Er,detectConnectionStatus:()=>Ae,findConnectButton:()=>Ye,runFunnel:()=>Sn,sendConnectionRequest:()=>It,shouldExcludeLocation:()=>st,viewProfile:()=>Et});async function bn(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function st(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Et(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:l=!1,extractRecommendations:u=!1,extractCertifications:i=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await we(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await bn(e,t));let c=0;for(let v=0;v<2;v++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let g=1;g<=6;g++)await e.evaluate(E=>window.scrollTo(0,E),C*g/6),await w(900);let $=await e.evaluate(()=>document.body.scrollHeight);if($===c)break;c=$}await w(800);let d=await e.evaluate(()=>{let v=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"]),C=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=>{let _=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(_)},g={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:[]},E=document.querySelector("main");if(!E)return g;let L=[...Array.from(E.querySelectorAll("h1")),...Array.from(E.querySelectorAll("h2"))],x=Array.from(E.querySelectorAll("h2")),j=L.find(A=>{let _=A.textContent&&A.textContent.trim(),I=(_||"").replace(/\s*\(\d+\)$/,"").trim();return _&&_.length>1&&_.length<100&&!v.has(I)&&!C.has(I)}),J=j?j.textContent.trim():null,R=j?j.parentElement:null;for(;R&&R!==E&&!Array.from(R.children).filter(_=>_.tagName==="P").some(_=>{let I=_.textContent&&_.textContent.trim();return I&&I.length>5&&!$(I)});)R=R.parentElement;let O=null,W=null,N=null,V=null;if(R&&R!==E){let A=Array.from(R.children).filter(I=>I.tagName==="P").filter(I=>{let de=I.textContent&&I.textContent.trim();return de&&de.length>5&&!$(de)});if(A[0]&&(O=A[0].textContent.trim()),A[1]){let I=A[1].textContent.trim().split(/\s*[·•]\s*/);W=I[0]||null,I.length>1&&(N=I.slice(1).join(" \xB7 "))}let _=Array.from(R.children).filter(I=>I.tagName==="DIV");for(let I=_.length-1;I>=0;I--){let de=_[I].textContent&&_[I].textContent.trim();if(de&&!(J&&de.startsWith(J))&&(V=de.split(/[·•]/)[0].trim(),V))break}}let H=null;if(R){let A=R.querySelectorAll("p, span, div");for(let _ of A){let I=(_.textContent||"").trim().replace(/^[·•]\s*/,"");if(I==="1st"||I==="2nd"||I==="3rd"){H=I;break}}}let ue=!!E.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=T&&T.src||null,q=E.textContent||"",U=null,te=q.match(/(\d+\+?)\s+connections\b/i);te&&(U=te[1]+" connections");let Ke=null,Nt=q.match(/(\d+)\s+mutual connection/i),jt=q.match(/and\s+(\d+)\s+other mutual/i),qn=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Nt?Ke=parseInt(Nt[1],10):jt?Ke=2+parseInt(jt[1],10):qn&&(Ke=2);let Ot=null,Mt=null,Ft=x.find(A=>A.textContent&&A.textContent.trim()==="About");if(Ft){let A=Ft.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let _=(A.textContent||"").trim();_=_.replace(/^About\s*/,"").trim();let I=_.match(/Top skills\s*(.+?)$/i);if(I){let dt=I[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Vn=>Vn.trim()).filter(Boolean);dt.length>0&&dt.length<10&&(Mt=dt)}_=_.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(),Ot=_||null}}let Lt=null,Pt=x.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(Pt){let A=Pt.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let _=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);_&&(Lt=parseInt(_[1].replace(/,/g,""),10))}}let Un=[...new Set(x.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==J).filter(A=>v.has(A)))],je=document.body.textContent||"",Bn=/#OpenToWork\b/i.test(je)||/\bOpen to work\b/.test(je),Jn=/#Hiring\b/i.test(je)||/\bI'?m hiring\b/i.test(je)||/\bWe are hiring\b/i.test(je);return{name:J,title:O,location:V,currentCompany:W,currentSchool:N,connectionDegree:H,hasVerifiedBadge:ue,photoUrl:P,connectionsLevel:U,mutualConnectionsCount:Ke,followers:Lt,openToWork:Bn,hiring:Jn,about:Ot,topSkills:Mt,availableSections:Un}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,h=null,m=null,S=null,y=null;if(o||r||s||l||u||i){let v=await Promise.resolve().then(()=>(wn(),yn));o&&(f=await v.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(p=await v.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),s&&(h=await v.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(m=await v.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),u&&(S=await v.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),i&&(y=await v.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${y.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...S!==null&&{recommendations:S},...y!==null&&{certifications:y}}}catch(a){console.error(`Error viewing profile ${t}:`,a.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(a.message||""))throw a;return null}}async function Ae(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(i=>i.getAttribute("aria-label")),r=document.querySelector('button[aria-label*="Message"]'),s=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!r,hasConnectBtn:!!s};return n.length>0?{status:"pending",debug:l}:r&&!s?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Ye(e){let t=null,n=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(i=a.textContent?.trim(),i&&!i.includes("notification")))return i;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let i=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p=null,h=null;for(let m of d){let S=m.getBoundingClientRect();if(S.width===0||S.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=m;break}h||(h=m)}return p||h||null},n);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(n){let i=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let a=await e.evaluate(d=>{let f=new RegExp("\\b"+d.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"))&&f.test(S)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},i);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},i);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(a)&&(console.log(` Skipping primary button: wrong person (${i})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",s=null;for(let i of o){let a=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(c.getAttribute("aria-label")||"").toLowerCase(),S=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:S,matchesName:y,ariaLabel:m}},i,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}s=i;break}}for(let i of o)i!==s&&await i.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let i of u){let a=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},i);if(a.isVisible&&!a.isInStickyHeader){l=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of u)i!==l&&await i.dispose().catch(()=>{});if(!l&&u.length>0&&(l=u[u.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let i=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),l),await w(500),await e.evaluate(c=>c.click(),l),await w(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 c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});a=c?.asElement?.()||null,a||await c?.dispose?.().catch(()=>{})}if(!a){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(a)&&(console.log(` Skipping generic button: wrong person (${i})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function _t(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let n=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),s=n.tag==="DIV";if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(c=>c.click(),t)]),await w(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 w(2e3),"premium_redirect"}else s?(await e.evaluate(a=>a.click(),t),await w(3e3)):(await e.evaluate(a=>a.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 u=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),i=e.url();return console.log(u?` \u2713 Connect sent \u2014 ${i}`:` \u26A0 No modal after connect click \u2014 ${i}`),"success"}async function xr(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 n=await Ye(e);if(n){await e.evaluate(r=>r.click(),n),await w(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.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 It(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:s=!1}=n;if(!r){let u=qe();if(!u.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${u.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:u.reason,profileInfo:null}}let l=await Ar(e,t,n);return l.connectionSent&&!s&&Kt(t,o),l}async function Ar(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:s=!0,skipIfConnected:l=!0,excludeLocations:u=[]}=n,i={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(`
|
|
239
|
+
--- Connecting: ${a} ---`),u.length>0){let y=Y()[t]?.location;if(st(y,u))return console.log(` \u26A0 Excluded location (stored): ${y}`),i.reason="excluded_location",i.profileInfo={location:y},i}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await we(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await bn(e,t),await w(2e3)),i.profileInfo=await e.evaluate(()=>{let y=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"]),k=T=>{let P=(T||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},C=document.querySelector("main");if(!C)return v;let $=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],g=Array.from(C.querySelectorAll("h2")),E=$.find(T=>{let P=T.textContent&&T.textContent.trim();return P&&P.length>1&&P.length<100&&!y.has(P)&&P!=="0 notifications"}),L=E?E.textContent.trim():null,x=E?E.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(q=>q.tagName==="P").some(q=>{let U=q.textContent&&q.textContent.trim();return U&&U.length>5&&!k(U)});)x=x.parentElement;let j=null,J=null,R=null;if(x&&x!==C){let T=Array.from(x.children),P=T.filter(U=>U.tagName==="P").filter(U=>{let te=U.textContent&&U.textContent.trim();return te&&te.length>5&&!k(te)});P[0]&&(j=P[0].textContent.trim()),P[1]&&(J=P[1].textContent.trim());let q=T.filter(U=>U.tagName==="DIV");for(let U=q.length-1;U>=0;U--){let te=q[U].textContent&&q[U].textContent.trim();if(te&&!(L&&te.startsWith(L))&&(R=te.split(/[·•]/)[0].trim(),R))break}}let O=null;if(x){let T=x.querySelectorAll("p, span, div");for(let P of T){let q=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(q==="1st"||q==="2nd"||q==="3rd"){O=q;break}}}let W=null,N=g.find(T=>T.textContent&&T.textContent.trim()==="About");if(N){let T=N.parentElement;for(;T&&T.tagName!=="SECTION";)T=T.parentElement;T&&(W=(T.textContent||"").trim().replace(/^About\s*/,"").trim()||null,W&&(W=W.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let V=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),H=V&&V.src||null,ue=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:L,title:j,location:R,about:W,company:J,connectionDegree:O,connectionsCount:null,mutualConnections:null,photoUrl:H,hasVerifiedBadge:ue}}),u.length>0){let y=i.profileInfo?.location,k=Y()[t]?.location,v=y||k;if(st(v,u))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),i.reason="excluded_location",i;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ae(e);if(d==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await we(e);let f=await Ye(e);if(!f&&(await we(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),f=await Ye(e)),!f))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=f.method,await _t(e,f.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 y=await Ae(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await we(e),await w(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),k),await w(500),await k.click().catch(()=>e.evaluate(C=>C.click(),k)),await w(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(v){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(g=>g.click(),v),await w(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),i.reason="premium_required",i;if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),i.reason="premium_required",i}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await w(500),i.reason="email_required",i}let m=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!m&&!S){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let v=k.querySelector('button[aria-label="Add a note"]'),C=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!C}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=k?.asElement?.()||null,S||await k.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await w(1500),await e.$("div.modal-upsell")){let v=await xr(e);return i.success=v,i.connectionSent=v,i.reason=v?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",v);await k.type(C,{delay:20}),await w(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(g=>g.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=C,i}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(m&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let y=S;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(f.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 we(e),await w(500);let k=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let C of k){let $=await e.evaluate(g=>{let E=g.getBoundingClientRect();return{visible:E.width>0&&E.height>0,inSticky:!!g.closest('.sticky-header, [class*="sticky"]')}},C);if($.visible&&!$.inSticky){v=C;break}}!v&&k.length>0&&(v=k[k.length-1]);for(let C of k)C!==v&&await C.dispose().catch(()=>{});if(v)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),v),await w(500),await v.click().catch(()=>e.evaluate($=>$.click(),v)),await w(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(C){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(L=>L.click(),C),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),await Ae(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let E=await e.$('button[aria-label="Send without a note"]');if(E){console.log(" Modal appeared via More dropdown, sending without note...");try{await E.evaluate(L=>L.click())}catch{}return await w(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(a){console.error(` \u2717 Error: ${a.message}`),i.reason="error",i.error=a.message;let c=a.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{i.fatal=!0}return i}}async function Sn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:i=null,excludeLocations:a=[],source:c="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
240
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${s})`}`),l||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!l){let p=Se();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let f=0;for(let p=0;p<t.length;p++){let h=t[p];try{if(e.isClosed()){console.log(`
|
|
241
241
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
242
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!
|
|
243
|
-
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(
|
|
244
|
-
\u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(
|
|
245
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!
|
|
242
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=Gt(h.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}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,i&&await i(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl}`);let S=null;if(l){let y=await Et(e,h.profileUrl);y?(ze(h.profileUrl,{...y,source:c}),d.viewed++,S={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y}):(d.errors++,S={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let y=qe();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(S=await It(e,h.profileUrl,{message:o,useCustomMessage:r,excludeLocations:a,source:c,skipQuotaGate:!0}),S.success)d.connectionsSent++;else switch(S.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(S?.fatal){console.log(`
|
|
243
|
+
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(S?.reason==="error"){if(f++,f>=3){console.log(`
|
|
244
|
+
\u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(S&&S.reason&&(Ze(h.profileUrl,S.reason,{method:S.method,messageSent:S.messageSent,profileInfo:S.profileInfo}),Wt(h.profileUrl,{source:c||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:S.reason})),i&&await i(h,d,S),p<t.length-1){let y=u+Math.random()*2e3;await w(y)}}if(console.log(`
|
|
245
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let p=Se();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}var Er,vn=re(async()=>{it();await Ue();Er={viewProfile:Et,detectConnectionStatus:Ae,findConnectButton:Ye,clickConnectButton:_t,sendConnectionRequest:It,runFunnel:Sn,shouldExcludeLocation:st}});import{createGraphClient as _r,resolveToken as Ir}from"@ilivemylife/graph-sdk";import{config as Dr}from"dotenv";var $n,Cn,xn=re(()=>{Dr();$n=Ir()||process.env.TOKEN;$n||(console.error(`
|
|
246
246
|
[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.
|
|
247
247
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
248
248
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
249
|
-
`),process.exit(1))
|
|
249
|
+
`),process.exit(1));Cn=_r({token:$n})});import"dotenv/config";function Tr(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Rr({scriptName:e,mode:t,status:n,error:o,duration:r}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),u=r?` ${Tr(r)}`:"",i=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${a} \u2014 ${i} \u2014 ${l}${u}`}async function An({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(o)||o.length===0)return;let i=`**${Rr({scriptName:e,mode:t,status:n,error:r,duration:s})}**
|
|
250
250
|
|
|
251
251
|
${o.join(`
|
|
252
|
-
`)}`;try{await
|
|
253
|
-
`)}var Dr,Rr,Rt,Tt,Tn=re(()=>{An();Dr=Ir(import.meta.url),Rr=we.dirname(we.dirname(Dr)),Rt=process.env.DATA_DIR?we.resolve(process.env.DATA_DIR,"collected-profiles"):we.join(Rr,"collected-profiles"),Tt=we.join(Rt,"run-log.json")});import*as at from"fs";import*as Re from"path";await dt();await qe();import"dotenv/config";import*as Ze from"fs";import*as pe from"path";import{fileURLToPath as ao}from"url";var co=ao(import.meta.url),uo=pe.dirname(pe.dirname(co)),ht=process.env.DATA_DIR?pe.resolve(process.env.DATA_DIR,"collected-profiles"):pe.join(uo,"collected-profiles"),Xt=pe.join(ht,"connect-queue.json"),fo=1,ke=300,et=["queued","approved","sent","skipped","failed"],me=["high","normal","low"],zt={high:0,normal:1,low:2};function po(){Ze.existsSync(ht)||Ze.mkdirSync(ht,{recursive:!0})}function gt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=ke?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:me.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:et.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function ne(){let e=Le(Xt,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(gt).filter(n=>n.url):[]}function he(e){po(),Fe(Xt,{version:fo,entries:e.map(gt)})}function le(e){return Q(e)||(e||"").trim().toLowerCase()}function Be(e,t){let n=le(t);return e.find(o=>le(o.url)===n)||null}function yt(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:i=()=>!1,nowIso:a}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},s=new Set(e.map(l=>le(l.url)));for(let l of t){let c=l?.url;if(!c){u.skippedNoUrl++;continue}let d=le(c);if(s.has(d)){u.skippedDup++;continue}if(i(c)){u.skippedEngaged++;continue}let f=typeof l.note=="string"?l.note.trim():"";f.length>ke&&u.notesTooLong++;let p=f.length>0&&f.length<=ke;e.push(gt({url:c,tag:l.tag||o,priority:l.priority||r,withNote:p,note:p?f:null,status:"queued",addedAt:a||null})),s.add(d),u.added++}return u}function Zt(e){return[...e].sort((t,n)=>{let o=(zt[t.priority]??1)-(zt[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function ve(e,t){return e.filter(n=>n.status===t)}await qe();import"dotenv/config";import*as b from"fs";import*as Ct from"os";import*as R from"path";import{fileURLToPath as Po}from"url";var bt={};fe(bt,{NAME:()=>ho,VERSION:()=>mo,up:()=>wo});import*as z from"fs";import*as tt from"path";var mo=1,ho="normalize-jobs-and-questions",go=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],yo=50;function wt(e){return z.existsSync(e)?JSON.parse(z.readFileSync(e,"utf-8")):null}function St(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{z.writeFileSync(o,n)}catch(r){try{z.unlinkSync(o)}catch{}throw r}try{z.renameSync(o,e)}catch(r){try{z.unlinkSync(o)}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 wo(e,t){let n=tt.join(e,"jobs.json"),o=tt.join(t,"scouted-jobs.json"),r=tt.join(e,"application-questions.json"),i=wt(n)||{},a=wt(o)||{},u=0,s=[];for(let c of Object.keys(i)){if(!a[c])continue;let d=a[c],f=i[c];for(let p of go)d[p]!=null&&f[p]==null&&(f[p]=d[p]);s.push(c),u++}u>0?(St(n,i),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=wt(r);if(l&&Array.isArray(l.applications)){let c={},d=0;for(let f of l.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let g=(f.questions||[]).map(h=>{let w={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=yo?w.options=h.options:(w.optionsOmitted=!0,d++)),h.page&&(w.page=h.page),h.wasPreFilled&&(w.wasPreFilled=!0),h.wasRetry&&(w.wasRetry=!0),w});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||g.length,questions:g})}St(r,c),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else l&&!l.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(s.length>0){for(let c of s)delete a[c];St(o,a),console.log(` Phase 3: Removed ${s.length} merged entries from scouted-jobs.json (${Object.keys(a).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var kt={};fe(kt,{NAME:()=>bo,VERSION:()=>So,up:()=>$o});import*as X from"fs";import*as en from"path";var So=2,bo="reset-unread-flags";function ko(e){return X.existsSync(e)?JSON.parse(X.readFileSync(e,"utf-8")):null}function vo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{X.writeFileSync(o,n)}catch(r){try{X.unlinkSync(o)}catch{}throw r}try{X.renameSync(o,e)}catch(r){try{X.unlinkSync(o)}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 $o(e){let t=en.join(e,"conversations.json"),n=ko(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}vo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var vt={};fe(vt,{NAME:()=>xo,VERSION:()=>Co,up:()=>Ro});import*as Z from"fs";import*as tn from"path";var Co=3,xo="recompute-last-message-by",Ao=new Set(["draft","confirmed","rejected","needs_review"]);function Eo(e){return Z.existsSync(e)?JSON.parse(Z.readFileSync(e,"utf-8")):null}function Io(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Z.writeFileSync(o,n)}catch(r){try{Z.unlinkSync(o)}catch{}throw r}try{Z.renameSync(o,e)}catch(r){try{Z.unlinkSync(o)}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 Do(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Ao.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,a)=>a.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let a=i.sender;if(a===t)return"me";if(a!=="Unknown"&&a!=="")return"them"}return"them"}async function Ro(e){let t=tn.join(e,"conversations.json"),n=Eo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,a=0;for(let u of Object.keys(n)){let s=n[u];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let l=Array.isArray(s.messages)?s.messages:[],c=Do(l,o),d=c==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==c&&a++,s.lastMessageBy=c,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}Io(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${a} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}await qe();import"dotenv/config";import*as K from"path";import{fileURLToPath as To}from"url";var No=To(import.meta.url),_o=K.dirname(K.dirname(No)),Ue=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(_o,"market-research"),ys=K.join(Ue,"scouted-jobs.json"),ws=K.join(Ue,"discovered-people.json"),Ss=K.join(Ue,"visit-log.json"),bs=K.join(Ue,"companies.json"),ks=K.join(Ue,"job-decisions.json");function nn(){Oo=null,jo=null,Fo=null,Lo=null,Mo=null}var Oo=null;var jo=null;var Fo=null;var Lo=null;var Mo=null;var qo=Po(import.meta.url),Bo=R.dirname(qo),Uo=R.dirname(R.dirname(Bo));function Vo(e){return e&&(e==="~"?Ct.homedir():e.startsWith("~/")||e.startsWith("~\\")?R.join(Ct.homedir(),e.slice(2)):e)}var oe=process.env.DATA_DIR?R.resolve(Vo(process.env.DATA_DIR)):Uo,Ce=R.join(oe,"collected-profiles"),xe=R.join(oe,"market-research"),Y=R.join(oe,".schema-version"),on=[R.join(Ce,".schema-version"),R.join(xe,".schema-version")],ge=3,ae=[{version:1,module:bt},{version:2,module:kt},{version:3,module:vt}];(function(){ae.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ae){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ae.length?ae[ae.length-1].version:0;if(n!==ge)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${ge}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ae.length;o++){let r=o+1;if(ae[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ae[o].version}`)}})();function an(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
252
|
+
`)}`;try{await Cn.addMessage(l,i)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var En=re(()=>{xn()});var Tn={};fe(Tn,{endRun:()=>Lr,formatScriptStatus:()=>Ur,getLastRun:()=>qr,getRunHistory:()=>Pr,getTodayRunSummary:()=>In,startRun:()=>Fr,timeAgo:()=>Dn});import"dotenv/config";import*as ee from"fs";import*as be from"path";import{fileURLToPath as Nr}from"url";function Mr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ee.writeFileSync(o,n);for(let r=0;r<3;r++)try{ee.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Ie(){try{if(!ee.existsSync(Tt))return{runs:[]};let e=JSON.parse(ee.readFileSync(Tt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function _n(e){ee.existsSync(Dt)||ee.mkdirSync(Dt,{recursive:!0});try{Mr(Tt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Fr(e,t="default"){let n=Ie();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>s),_n(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Lr(e,t,n=null,o=null){if(!e)return;let r=null;try{let l=Ie(),u=l.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=n,u.error=o,r=u.duration;else{let i=l.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());i&&(i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=n,i.error=o,r=i.duration)}_n(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";An({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}function Pr(e=7){let t=Ie(),n=Date.now()-e*24*60*60*1e3;return t.runs.filter(o=>new Date(o.timestamp).getTime()>n).sort((o,r)=>r.timestamp.localeCompare(o.timestamp))}function qr(e=null){let t=Ie(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function In(){let e=new Date().toISOString().slice(0,10),t=Ie(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let r=n[o.script];r.total++,o.status==="success"?r.success++:o.status==="error"?r.error++:o.status==="interrupted"?r.interrupted++:o.status==="partial"?r.partial++:o.status==="running"&&r.running++,r.lastRun=o}return n}function Dn(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),r=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:r===1?"yesterday":`${r} days ago`}function Ur(){let e=["sync-all","messages","funnel","sync","apply"],t=Ie(),n=In(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let s of e){let l=t.runs.filter(m=>m.script===s),u=[...l].reverse().find(m=>m.status==="success"),i=l[l.length-1],a=u||i,c=a?Dn(a.timestamp):"never",f=(a?Math.floor((Date.now()-new Date(a.timestamp).getTime())/864e5):1/0)>1?" \u26A0":a?.status==="error"?" \u2717":" \u2713",p="";if(a?.stats){let m=a.stats,S=Object.entries(m).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,k])=>`${k} ${y}`);S.length&&(p=` (${S.join(", ")})`)}let h=a?.duration?` ${Math.round(a.duration/1e3)}s`:"";o.push(` ${s.padEnd(14)} ${c.padEnd(16)}${h}${p}${f}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[s,l]of r){let u=[];l.success&&u.push(`${l.success} success`),l.error&&u.push(`${l.error} error`),l.interrupted&&u.push(`${l.interrupted} interrupted`),l.running&&u.push(`${l.running} running`),o.push(` Today: ${s} \xD7${l.total} (${u.join(", ")})`)}}return o.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),o.join(`
|
|
253
|
+
`)}var jr,Or,Dt,Tt,Rn=re(()=>{En();jr=Nr(import.meta.url),Or=be.dirname(be.dirname(jr)),Dt=process.env.DATA_DIR?be.resolve(process.env.DATA_DIR,"collected-profiles"):be.join(Or,"collected-profiles"),Tt=be.join(Dt,"run-log.json")});import*as ct from"fs";import*as Te from"path";await Qe();await Ue();import"dotenv/config";import*as et from"fs";import*as me from"path";import{fileURLToPath as po}from"url";var mo=po(import.meta.url),ho=me.dirname(me.dirname(mo)),ht=process.env.DATA_DIR?me.resolve(process.env.DATA_DIR,"collected-profiles"):me.join(ho,"collected-profiles"),Xt=me.join(ht,"connect-queue.json"),go=1,ke=300,tt=["queued","approved","sent","skipped","failed"],he=["high","normal","low"],zt={high:0,normal:1,low:2};function yo(){et.existsSync(ht)||et.mkdirSync(ht,{recursive:!0})}function gt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=ke?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:he.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:tt.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function ne(){let e=Le(Xt,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(gt).filter(n=>n.url):[]}function ge(e){yo(),Fe(Xt,{version:go,entries:e.map(gt)})}function ae(e){return K(e)||(e||"").trim().toLowerCase()}function Be(e,t){let n=ae(t);return e.find(o=>ae(o.url)===n)||null}function yt(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:s=()=>!1,nowIso:l}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},i=new Set(e.map(a=>ae(a.url)));for(let a of t){let c=a?.url;if(!c){u.skippedNoUrl++;continue}let d=ae(c);if(i.has(d)){u.skippedDup++;continue}if(s(c)){u.skippedEngaged++;continue}let f=typeof a.note=="string"?a.note.trim():"";f.length>ke&&u.notesTooLong++;let p=f.length>0&&f.length<=ke;e.push(gt({url:c,tag:a.tag||o,priority:a.priority||r,withNote:p,note:p?f:null,status:"queued",addedAt:l||null})),i.add(d),u.added++}return u}function Zt(e){return[...e].sort((t,n)=>{let o=(zt[t.priority]??1)-(zt[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function ve(e,t){return e.filter(n=>n.status===t)}await Ue();await Qe();var wo={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};function en(e){if(!e)return null;for(let[t,n]of Object.entries(wo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}import"dotenv/config";import*as b from"fs";import*as Ct from"os";import*as D from"path";import{fileURLToPath as Vo}from"url";var St={};fe(St,{NAME:()=>So,VERSION:()=>bo,up:()=>$o});import*as z from"fs";import*as nt from"path";var bo=1,So="normalize-jobs-and-questions",ko=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],vo=50;function wt(e){return z.existsSync(e)?JSON.parse(z.readFileSync(e,"utf-8")):null}function bt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{z.writeFileSync(o,n)}catch(r){try{z.unlinkSync(o)}catch{}throw r}try{z.renameSync(o,e)}catch(r){try{z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function $o(e,t){let n=nt.join(e,"jobs.json"),o=nt.join(t,"scouted-jobs.json"),r=nt.join(e,"application-questions.json"),s=wt(n)||{},l=wt(o)||{},u=0,i=[];for(let c of Object.keys(s)){if(!l[c])continue;let d=l[c],f=s[c];for(let p of ko)d[p]!=null&&f[p]==null&&(f[p]=d[p]);i.push(c),u++}u>0?(bt(n,s),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=wt(r);if(a&&Array.isArray(a.applications)){let c={},d=0;for(let f of a.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let h=(f.questions||[]).map(m=>{let S={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=vo?S.options=m.options:(S.optionsOmitted=!0,d++)),m.page&&(S.page=m.page),m.wasPreFilled&&(S.wasPreFilled=!0),m.wasRetry&&(S.wasRetry=!0),S});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}bt(r,c),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} 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(i.length>0){for(let c of i)delete l[c];bt(o,l),console.log(` Phase 3: Removed ${i.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 kt={};fe(kt,{NAME:()=>xo,VERSION:()=>Co,up:()=>_o});import*as X from"fs";import*as tn from"path";var Co=2,xo="reset-unread-flags";function Ao(e){return X.existsSync(e)?JSON.parse(X.readFileSync(e,"utf-8")):null}function Eo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{X.writeFileSync(o,n)}catch(r){try{X.unlinkSync(o)}catch{}throw r}try{X.renameSync(o,e)}catch(r){try{X.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function _o(e){let t=tn.join(e,"conversations.json"),n=Ao(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Eo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var vt={};fe(vt,{NAME:()=>Do,VERSION:()=>Io,up:()=>Oo});import*as Z from"fs";import*as nn from"path";var Io=3,Do="recompute-last-message-by",To=new Set(["draft","confirmed","rejected","needs_review"]);function Ro(e){return Z.existsSync(e)?JSON.parse(Z.readFileSync(e,"utf-8")):null}function No(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Z.writeFileSync(o,n)}catch(r){try{Z.unlinkSync(o)}catch{}throw r}try{Z.renameSync(o,e)}catch(r){try{Z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function jo(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!To.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,l)=>l.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let l=s.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Oo(e){let t=nn.join(e,"conversations.json"),n=Ro(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,l=0;for(let u of Object.keys(n)){let i=n[u];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,s++);let a=Array.isArray(i.messages)?i.messages:[],c=jo(a,o),d=c==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==c&&l++,i.lastMessageBy=c,i.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}No(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}await Ue();import"dotenv/config";import*as Q from"path";import{fileURLToPath as Mo}from"url";var Fo=Mo(import.meta.url),Lo=Q.dirname(Q.dirname(Fo)),Je=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(Lo,"market-research"),ki=Q.join(Je,"scouted-jobs.json"),vi=Q.join(Je,"discovered-people.json"),$i=Q.join(Je,"visit-log.json"),Ci=Q.join(Je,"companies.json"),xi=Q.join(Je,"job-decisions.json");function on(){Po=null,qo=null,Uo=null,Bo=null,Jo=null}var Po=null;var qo=null;var Uo=null;var Bo=null;var Jo=null;var Ho=Vo(import.meta.url),Wo=D.dirname(Ho),Go=D.dirname(D.dirname(Wo));function Yo(e){return e&&(e==="~"?Ct.homedir():e.startsWith("~/")||e.startsWith("~\\")?D.join(Ct.homedir(),e.slice(2)):e)}var oe=process.env.DATA_DIR?D.resolve(Yo(process.env.DATA_DIR)):Go,Ce=D.join(oe,"collected-profiles"),xe=D.join(oe,"market-research"),G=D.join(oe,".schema-version"),rn=[D.join(Ce,".schema-version"),D.join(xe,".schema-version")],ye=3,le=[{version:1,module:St},{version:2,module:kt},{version:3,module:vt}];(function(){le.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of le){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=le.length?le[le.length-1].version:0;if(n!==ye)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${ye}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<le.length;o++){let r=o+1;if(le[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${le[o].version}`)}})();function cn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
254
254
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
255
255
|
`),process.exit(1));try{b.mkdirSync(oe,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
256
256
|
[FATAL] Cannot create DATA_DIR (${oe}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -260,64 +260,64 @@ ${o.join(`
|
|
|
260
260
|
[FATAL] DATA_DIR (${oe}) 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.
|
|
261
261
|
`),process.exit(1));for(let t of[Ce,xe]){let n;try{n=b.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
262
262
|
[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.
|
|
263
|
-
`),process.exit(1))}}var $e=
|
|
263
|
+
`),process.exit(1))}}var $e=D.join(oe,".migration-lock");function Ko(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return b.writeFileSync($e,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(b.readFileSync($e,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(l){l.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,s=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(s=Date.now()-l)}o&&s<r&&(console.error(`
|
|
264
264
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${$e}
|
|
265
265
|
`),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.
|
|
266
|
-
`),process.exit(1)),o&&
|
|
267
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let
|
|
266
|
+
`),process.exit(1)),o&&s>=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 n=$e+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,$e),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function xt(){try{if(JSON.parse(b.readFileSync($e,"utf-8")).pid!==process.pid)return;b.unlinkSync($e)}catch{}}var sn=!1;function Qo(){if(sn)return;sn=!0;let e=()=>{try{xt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function zo(){if(b.existsSync(G))return;let e=[],t=[];for(let s of rn)if(b.existsSync(s))try{e.push({file:s,schema:ot(s)})}catch(l){t.push({file:s,err:l.message})}if(t.length>0){console.error(`
|
|
267
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
|
|
268
268
|
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.
|
|
269
|
-
`),process.exit(1)}if(e.length===0)return;let n=e.map(
|
|
270
|
-
[FATAL] Legacy .schema-version files disagree:`);for(let
|
|
271
|
-
`),process.exit(1)}let o=e[0].schema,r=
|
|
272
|
-
[FATAL] ${
|
|
273
|
-
`),process.exit(1)}let t=
|
|
274
|
-
[FATAL] ${
|
|
275
|
-
`),process.exit(1)),t}function
|
|
276
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
277
|
-
`),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${
|
|
269
|
+
`),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
|
|
270
|
+
[FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.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.
|
|
271
|
+
`),process.exit(1)}let o=e[0].schema,r=G+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,G)}catch(s){try{b.unlinkSync(r)}catch{}throw s}for(let s of rn)if(b.existsSync(s))try{b.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${G}`)}function Xo(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 ot(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function an(){if(zo(),!b.existsSync(G))return{version:0,migrations:[]};let e;try{e=ot(G)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
272
|
+
[FATAL] ${G} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
273
|
+
`),process.exit(1)}let t=Xo(e);return t===null&&(console.error(`
|
|
274
|
+
[FATAL] ${G} 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.
|
|
275
|
+
`),process.exit(1)),t}function un(e){try{b.chmodSync(e,384)}catch{}}function Zo(e){if(cn(),b.existsSync(G))try{if(b.lstatSync(G).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${G}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=G+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),un(t),b.renameSync(t,G)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function ln(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(u=>{let i=u.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return b.statSync(D.join(e,u)).isFile()}catch{return!1}}),r=0,s=0,l=[];for(let u of o){let i=D.join(e,u),a=D.join(e,u+n);if(b.existsSync(a)){s++;continue}try{fn(i,a),r++}catch(c){l.push({file:u,err:c.message})}}if(l.length>0){let u=new Error(`Failed to back up ${l.length} file(s) in ${D.basename(e)}/: `+l.map(i=>`${i.file} (${i.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||s>0){let u=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${D.basename(e)}/ (${n})${u}`)}}var $t=!1;async function dn(){if($t)return;cn(),rr();let t=an().version;if(t===ye){$t=!0;return}Qo(),Ko(),process.on("exit",xt),t>ye&&(console.error(`
|
|
276
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${ye}.`),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.
|
|
277
|
+
`),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${ye}.
|
|
278
278
|
`),process.exit(1)),console.log(`
|
|
279
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
279
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${ye}`);let n=ir();if(!n.ok){console.error(`
|
|
280
280
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
281
281
|
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'.
|
|
282
|
-
`),process.exit(1)}let o=
|
|
283
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let
|
|
284
|
-
[FATAL] Pre-migration backup failed for ${
|
|
285
|
-
`),process.exit(1)}let u=r.module;try{await u.up(Ce,xe)}catch(
|
|
286
|
-
[FATAL] Migration ${
|
|
287
|
-
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${
|
|
288
|
-
`))}catch(
|
|
289
|
-
`)}process.exit(1)}try{let
|
|
290
|
-
[FATAL] Migration ${
|
|
291
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${
|
|
292
|
-
\u2713 Schema is now at v${
|
|
293
|
-
`)}var
|
|
294
|
-
`);let
|
|
295
|
-
Added ${u.added} to queue (tag=${n}, priority=${r}).`),u.skippedDup&&console.log(` ${u.skippedDup} already in queue \u2014 skipped.`),u.skippedEngaged&&console.log(` ${u.skippedEngaged} already connected/pending \u2014 skipped.`),u.skippedNoUrl&&console.log(` ${u.skippedNoUrl} had no url \u2014 skipped.`),u.notesTooLong&&console.log(` ${u.notesTooLong} had notes over ${ke} chars \u2014 added WITHOUT a note (LinkedIn's limit); set a shorter one with \`connect note\`.`);let s
|
|
296
|
-
Queue now: ${ve(
|
|
297
|
-
(shortcut: --valuable = ${
|
|
298
|
-
Filled ${
|
|
299
|
-
Queue now: ${ve(
|
|
282
|
+
`),process.exit(1)}let o=le.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
283
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${s}.backup`;try{ln(Ce,r.version),ln(xe,r.version)}catch(i){console.error(`
|
|
284
|
+
[FATAL] Pre-migration backup failed for ${s}: ${i.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
285
|
+
`),process.exit(1)}let u=r.module;try{await u.up(Ce,xe)}catch(i){console.error(`
|
|
286
|
+
[FATAL] Migration ${s} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let a=sr(l);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
287
|
+
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
288
|
+
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
289
|
+
`)}process.exit(1)}try{let i=new Date().toISOString(),a={version:r.version,name:u.NAME||s,appliedAt:i},c=an();c.version=r.version,c.migratedAt=i,c.migrations=c.migrations||[],c.migrations.push(a),Zo(c)}catch(i){console.error(`
|
|
290
|
+
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${i.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 ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
291
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Vt()}catch{}try{on()}catch{}$t=!0,xt(),console.log(`
|
|
292
|
+
\u2713 Schema is now at v${ye}
|
|
293
|
+
`)}var er=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function tr(e){let t=e.toLowerCase();return er.some(n=>n.test(t))}var nr=6e4;function or(){let e=Date.now(),t=[];for(let n of[oe,Ce,xe]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!tr(r))continue;let s=D.join(n,r);try{let l=b.statSync(s);if(!l.isFile()||e-l.mtimeMs<nr)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function rr({verbose:e=!1}={}){let t=or();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{b.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${D.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function ir(){let e=[];for(let t of[Ce,xe]){if(!b.existsSync(t))continue;let n=b.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=D.join(t,o);try{ot(r)}catch(s){e.push({dir:D.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function sr(e){let t=[],n=[];for(let s of[Ce,xe]){if(!b.existsSync(s))continue;let l=b.readdirSync(s).filter(u=>u.endsWith(e));for(let u of l){let i=D.join(s,u),a=u.slice(0,-e.length),c=D.join(s,a);try{a.toLowerCase().endsWith(".json")?ot(i):b.accessSync(i,b.constants.R_OK),t.push({backupPath:i,originalPath:c,fileName:u,dir:s})}catch(d){n.push(`${D.basename(s)}/${u}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:l,fileName:u,dir:i}of t)try{fn(s,l),o++}catch(a){r.push(`${D.basename(i)}/${u}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function fn(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),un(n)}catch(o){try{b.unlinkSync(n)}catch{}throw o}try{b.renameSync(n,t)}catch(o){try{b.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}var On=new Set(["connected"]),Mn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),Nn=new Set(["pending","connected","excluded_location","email_required","premium_required"]),Br=3,at=process.env.DATA_DIR?Te.resolve(process.env.DATA_DIR,"collected-profiles","connect-diagnostics"):Te.resolve("collected-profiles","connect-diagnostics");async function Jr(e,t,n){try{let o=e.url(),r=await e.evaluate(()=>({modal:(a=>Array.from(document.querySelectorAll(a)).map(c=>(c.innerText||"").trim()).filter(Boolean).join(" | "))('[role="alertdialog"], [role="dialog"], .artdeco-modal, .artdeco-toast-item, .ip-fuse-limit-alert, .artdeco-inline-feedback').slice(0,1e3),body:(document.body.innerText||"").slice(0,1500)}));ct.mkdirSync(at,{recursive:!0});let s={at:new Date().toISOString(),target:t.url,reason:n||null,pageUrl:o,modalText:r.modal,bodySnippet:r.body};ct.appendFileSync(Te.join(at,"connect-failures.jsonl"),JSON.stringify(s)+`
|
|
294
|
+
`);let l=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:Te.join(at,`fail-${l}.png`)})}catch{}return r.modal||""}catch{return""}}var Re=process.argv.slice(2),Fn=Re[0],Ne=Re.filter(e=>!e.startsWith("--")),De=e=>Re.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),ce=e=>{let t=Re.find(o=>o===`--${e}`||o.startsWith(`--${e}=`));if(t===void 0)return;let n=t.indexOf("=");return n===-1&&F(`--${e} needs a value \u2014 write --${e}=value (no space).`),t.slice(n+1)},Rt=()=>new Date().toISOString();function ut(){let e=Y(),t=new Map;for(let[n,o]of Object.entries(e)){let r=K(o.profileUrl||n);r&&t.set(r,o)}return t}function Ln(e,t){let n=e.get(K(t));return n?On.has(n.connectionStatus)||Mn.has(n.connectionStatus):!1}async function Vr(){let e=Ne[1];if(!e)return F("Usage: connect add <file.json> [--tag=X] [--priority=high]");let t;try{t=JSON.parse((await import("fs")).readFileSync(e,"utf-8"))}catch(a){return F(`Could not read/parse ${e}: ${a.message}`)}if(!Array.isArray(t))return F("File must be a JSON array of { url, note?, name? }.");let n=ce("tag")||"untagged",o=ce("priority");if(o&&!he.includes(o))return F(`--priority must be one of: ${he.join(", ")}`);let r=o||"normal",s=ne(),l=ut(),u=yt(s,t,{tag:n,priority:r,nowIso:Rt(),alreadyEngaged:a=>Ln(l,a)});ge(s),console.log(`
|
|
295
|
+
Added ${u.added} to queue (tag=${n}, priority=${r}).`),u.skippedDup&&console.log(` ${u.skippedDup} already in queue \u2014 skipped.`),u.skippedEngaged&&console.log(` ${u.skippedEngaged} already connected/pending \u2014 skipped.`),u.skippedNoUrl&&console.log(` ${u.skippedNoUrl} had no url \u2014 skipped.`),u.notesTooLong&&console.log(` ${u.notesTooLong} had notes over ${ke} chars \u2014 added WITHOUT a note (LinkedIn's limit); set a shorter one with \`connect note\`.`);let i=s.filter(a=>a.status==="queued"&&a.withNote).length;console.log(`
|
|
296
|
+
Queue now: ${ve(s,"queued").length} queued, ${ve(s,"approved").length} approved.`),i&&console.log(` ${i} queued entries have a note saved \u2014 sent only with \`connect run --with-notes\`.`),console.log(`Next: review with \`connect list\`, approve with \`connect approve --tag=${n}\`, send with \`connect run\`.`)}var jn=["founder","investor","hiring_manager","peer"];function Hr(){let e=ce("category");if(e===void 0&&De("valuable")&&(e=jn.join(",")),!e)return F(`Usage: connect fill --category=founder,investor,hiring_manager[,peer,recruiter] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
297
|
+
(shortcut: --valuable = ${jn.join(",")})`);let t=e.split(",").map($=>$.trim()).filter(Boolean),n=$=>{let g=ce($);if(g===void 0)return;let E=parseInt(g,10);return!Number.isInteger(E)||E<0?F(`--${$} must be a non-negative integer.`):E},o=n("min-posts")??0,r=n("max"),s=ce("priority");if(s&&!he.includes(s))return F(`--priority must be one of: ${he.join(", ")}`);let l=ce("tag"),u=!De("no-validate"),i=new Set(["recruiter","hiring_manager","founder","investor","coach","sales"]),a=(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map($=>$.trim().toLowerCase()).filter(Boolean),c=$=>{if(!$)return!1;let g=String($).toLowerCase();return a.some(E=>g.includes(E))},d=Y(),f=[],p=0,h=0,m=0;for(let[$,g]of Object.entries(d))if(t.includes(g.category)&&!(On.has(g.connectionStatus)||Mn.has(g.connectionStatus))&&g.connectionDegree!=="1st"&&!((g.jobIds?.length||0)<o)){if(c(g.location)){p++;continue}if(u&&i.has(g.category)){let E=(typeof g.title=="string"?g.title:"").trim();if(!E){h++;continue}if(en(E)!==g.category){m++;continue}}f.push({url:g.profileUrl||$,p:g})}let S={high:0,medium:1,low:2};f.sort(($,g)=>(S[$.p.personPriority]??1)-(S[g.p.personPriority]??1)||(g.p.mutualConnections||0)-($.p.mutualConnections||0)||(g.p.jobIds?.length||0)-($.p.jobIds?.length||0)),r!==void 0&&(f=f.slice(0,r));let y=f.map($=>({url:$.url,tag:l||$.p.category,priority:s||($.p.personPriority==="high"?"high":"normal")})),k=ne(),v=ut(),C=yt(k,y,{alreadyEngaged:$=>Ln(v,$),nowIso:Rt()});ge(k),console.log(`
|
|
298
|
+
Filled ${C.added} from [${t.join(", ")}]${o?` (\u2265${o} job-posts)`:""}${u?"":" (--no-validate)"}.`),C.skippedDup&&console.log(` ${C.skippedDup} already in queue \u2014 skipped.`),C.skippedEngaged&&console.log(` ${C.skippedEngaged} already connected/pending \u2014 skipped.`),p&&console.log(` ${p} in excluded locations \u2014 skipped.`),m&&console.log(` ${m} filtered \u2014 title doesn't confirm the category (likely mis-tagged by enrichment).`),h&&console.log(` ${h} skipped \u2014 no title stored to validate (held; not visited, to avoid ban risk).`),console.log(`
|
|
299
|
+
Queue now: ${ve(k,"queued").length} queued, ${ve(k,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function Wr(){let e=ne();if(!e.length)return console.log("\nQueue is empty. Add people with `connect add <file.json>`.");let t=ce("status"),n=ut(),o=Se();console.log(`
|
|
300
300
|
=== Connect Queue === (quota left: ${o.daily.remaining}/${o.daily.max} today, ${o.weekly.remaining}/${o.weekly.max} week)
|
|
301
|
-
`);let r={};for(let
|
|
302
|
-
`),t&&!
|
|
303
|
-
`);let
|
|
304
|
-
${
|
|
305
|
-
${o}: ${
|
|
306
|
-
Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function
|
|
307
|
-
Note reminder cleared.`)}function
|
|
308
|
-
Priority set to ${t}.`)}async function
|
|
309
|
-
Nothing approved to send.`),
|
|
310
|
-
Connection quota is used up (${
|
|
311
|
-
Nothing to send (--max=${r===1/0?"\u221E":r}).`);return}let c=
|
|
312
|
-
=== Connect run ===`),console.log(` Approved: ${
|
|
301
|
+
`);let r={};for(let a of e)r[a.status]=(r[a.status]||0)+1;console.log("Status: "+Object.entries(r).map(([a,c])=>`${a}=${c}`).join(" ")+`
|
|
302
|
+
`),t&&!tt.includes(t)&&console.log(`(unknown status "${t}" \u2014 valid: ${tt.join(", ")})
|
|
303
|
+
`);let s=t?e.filter(a=>a.status===t):e,l={approved:0,queued:1,failed:2,skipped:3,sent:4},u=[...s].sort((a,c)=>(l[a.status]??9)-(l[c.status]??9));for(let a of u){let c=n.get(K(a.url)),d=c&&c.name||"",f=c&&c.title?` \xB7 ${c.title.slice(0,40)}`:"",p=c&&c.mutualConnections?` \xB7 ${c.mutualConnections} mutual`:"",h=a.withNote?"\u{1F4DD}":" ",m=a.priority==="high"?"\u2B06high ":a.priority==="low"?"\u2B07low ":"normal";console.log(` [${a.status.padEnd(8)}] ${m} ${h} ${d}${f}${p}`),console.log(` ${a.url} (tag=${a.tag})`)}let i=e.filter(a=>(a.status==="queued"||a.status==="approved")&&a.withNote).length;i&&console.log(`
|
|
304
|
+
${i} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function lt(e,t,n,o){let r=ne(),s=0;for(let l of r)e(l)&&t.includes(l.status)&&(l.status=n,s++);return ge(r),console.log(`
|
|
305
|
+
${o}: ${s} entr${s===1?"y":"ies"} \u2192 ${n}.`),s}function Gr(){let e=["queued","failed"];if(De("all"))return lt(()=>!0,e,"approved","Approved");let t=ce("tag");if(t)return lt(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=Ne[1];if(!n)return F("Usage: connect approve <url> | --all | --tag=X");let o=ae(n);return lt(r=>ae(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function Yr(){let e=Ne[1];if(!e)return F("Usage: connect skip <url>");let t=ae(e);return lt(n=>ae(n.url)===t,["queued","approved"],"skipped","Skipped")}function Kr(){let e=Re[1],t=Re[2];if(!e||t===void 0)return F('Usage: connect note <url> "custom note text"');let n=t.trim();if(!n)return F("Note is empty \u2014 use `connect no-note <url>` to remove a note.");if(n.length>ke)return F(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${ke}. Shorten it.`);let o=ne(),r=Be(o,e);if(!r)return F("Not in queue.");r.note=n,r.withNote=!0,ge(o),console.log(`
|
|
306
|
+
Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function Qr(){let e=Ne[1];if(!e)return F("Usage: connect no-note <url>");let t=ne(),n=Be(t,e);if(!n)return F("Not in queue.");n.note=null,n.withNote=!1,ge(t),console.log(`
|
|
307
|
+
Note reminder cleared.`)}function zr(){let e=Ne[1],t=Ne[2];if(!e||!he.includes(t))return F(`Usage: connect priority <url> <${he.join("|")}>`);let n=ne(),o=Be(n,e);if(!o)return F("Not in queue.");o.priority=t,ge(n),console.log(`
|
|
308
|
+
Priority set to ${t}.`)}async function Xr(){let e=De("dry-run"),t=De("yes"),n=De("with-notes"),o=ce("max"),r=1/0;if(o!==void 0){let g=parseInt(o,10);if(!Number.isInteger(g)||g<0)return F("--max must be a non-negative integer.");r=g}let s=Se(),l=Math.min(s.daily.remaining,s.weekly.remaining),u=ne(),i=Zt(ve(u,"approved"));if(!i.length){let g=ve(u,"queued").length;console.log(`
|
|
309
|
+
Nothing approved to send.`),g&&console.log(` ${g} queued \u2014 approve them first: \`connect approve --all\` (or --tag=X).`);return}if(l<=0){console.log(`
|
|
310
|
+
Connection quota is used up (${s.daily.remaining}/${s.daily.max} today, ${s.weekly.remaining}/${s.weekly.max} week). Try again later.`);return}let a=i.slice(0,Math.min(r,l));if(!a.length){console.log(`
|
|
311
|
+
Nothing to send (--max=${r===1/0?"\u221E":r}).`);return}let c=a.filter(g=>g.withNote).length;console.log(`
|
|
312
|
+
=== Connect run ===`),console.log(` Approved: ${i.length} \xB7 quota left: ${l} \xB7 sending: ${a.length}${n?` (${c} WITH a note)`:" (without notes)"}`),!n&&c&&console.log(` ${c} have a saved note \u2014 add --with-notes to send it (spends your scarce monthly notes).`);let d=ut();if(a.forEach((g,E)=>{let L=d.get(K(g.url));console.log(` ${E+1}. ${g.withNote?"\u{1F4DD}":" "} ${L?.name||g.url} (${g.priority}, tag=${g.tag})`)}),e){console.log(`
|
|
313
313
|
[dry-run] Nothing sent. Drop --dry-run to send.`);return}t||(console.log(`
|
|
314
|
-
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(
|
|
315
|
-
[!] ${
|
|
316
|
-
`);try{
|
|
317
|
-
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}if(
|
|
318
|
-
\u26A0 ${
|
|
319
|
-
=== Done: ${
|
|
320
|
-
[!] Run aborted: ${
|
|
314
|
+
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(g=>process.stdin.once("data",()=>g())));let f=(await import("puppeteer")).default,{loadCookies:p}=await Promise.resolve().then(()=>(hn(),mn)),{sendConnectionRequest:h}=await vn().then(()=>kn),{delayed:m}=await Promise.resolve().then(()=>(it(),gn)),{startRun:S,endRun:y}=await Promise.resolve().then(()=>(Rn(),Tn)),k=S("connect","run"),v,C;try{v=await f.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),C=await v.newPage(),await C.setCookie(...p())}catch(g){console.error(`
|
|
315
|
+
[!] ${g.message}
|
|
316
|
+
`);try{v&&await v.close()}catch{}try{y(k,"error",null,g.message)}catch{}process.exit(1)}let $=0;try{let g=Y(),E=new Map;for(let[O,W]of Object.entries(g)){let N=K(W.profileUrl||O);N&&E.set(N,O)}let L=0,x=0,j=0,J=0;for(let O of a){if(!qe().allowed){console.log(" Quota reached mid-run \u2014 stopping.");break}let W=n&&O.withNote,N=await h(C,O.url,{message:W?O.note:null,useCustomMessage:W,source:O.tag,skipQuotaGate:!0}),V;if(N.connectionSent?(V="sent",L++):Nn.has(N.reason)?(V="skipped",x++):(V="failed",j++),V==="failed"){J++;let H=await Jr(C,O,N.reason);console.log(` \u2717 ${O.url.slice(-32)} \u2014 ${N.reason||"failed"}${H?` \xB7 LinkedIn: "${H.slice(0,120)}"`:""}`)}else J=0;if(N.connectionSent||Nn.has(N.reason)){let H=E.get(K(O.url))||O.url;try{Ze(H,N.reason,{method:N.method,messageSent:N.messageSent,profileInfo:N.profileInfo})}catch{}}try{let H=ne(),ue=Be(H,O.url);ue&&(ue.status=V,V==="sent"&&(ue.sentAt=Rt()),ue.result=N.reason||N.error||V,ge(H))}catch(H){console.error(` \u26A0 Could not persist queue update for ${O.url}: ${H.message}`)}if(N.fatal){console.log(`
|
|
317
|
+
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}if(J>=Br){console.log(`
|
|
318
|
+
\u26A0 ${J} sends failed in a row \u2014 stopping to protect your account (this is often LinkedIn's invite limit).`),console.log(` What LinkedIn showed on each failure is saved to: ${at}`),console.log(" Try again later; if it persists you've likely hit LinkedIn's weekly invite limit.");break}await m(3e3+Math.random()*2e3)}let R=Se();console.log(`
|
|
319
|
+
=== Done: ${L} sent, ${x} skipped, ${j} failed ===`),console.log(`Connection quota left: ${R.daily.remaining}/${R.daily.max} today, ${R.weekly.remaining}/${R.weekly.max} week.`);try{y(k,"success",{sent:L,skipped:x,failed:j})}catch{}}catch(g){console.error(`
|
|
320
|
+
[!] Run aborted: ${g.message}`);try{y(k,"error",null,g.message)}catch{}$=1}finally{try{await v.close()}catch{}}process.exit($)}function F(e){console.error(e),process.exit(1)}function Zr(){console.log(`connect \u2014 connect queue
|
|
321
321
|
|
|
322
322
|
connect add <file.json> [--tag=X] [--priority=high|normal|low]
|
|
323
323
|
connect fill --category=founder,investor,... [--valuable] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
@@ -325,4 +325,4 @@ Press Enter to send, or Ctrl+C to cancel...`),await new Promise(C=>process.stdin
|
|
|
325
325
|
connect approve <url> | --all | --tag=X
|
|
326
326
|
connect note <url> "custom note" connect no-note <url>
|
|
327
327
|
connect skip <url> connect priority <url> <high|normal|low>
|
|
328
|
-
connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var
|
|
328
|
+
connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var ei={add:Vr,fill:Hr,list:Wr,approve:Gr,skip:Yr,note:Kr,"no-note":Qr,priority:zr,run:Xr},Pn=ei[Fn];Pn||(Zr(),process.exit(Fn?1:0));await dn();await Pn();
|
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.14.
|
|
1
|
+
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.14.2";try{let n=new URL("./ilml-plugin.json",import.meta.url);return JSON.parse(e(r(n),"utf-8")).version}catch{return"unknown"}}console.log(`ilml-plugin-linkedin ${i()}`);
|
package/ilml-plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "linkedin",
|
|
3
|
-
"version": "1.14.
|
|
3
|
+
"version": "1.14.2",
|
|
4
4
|
"description": "Reference ilml plugin: keep a local mirror of your LinkedIn data with AI-assisted workflows",
|
|
5
5
|
"commands": {
|
|
6
6
|
"help": { "run": "node dist/help.mjs", "description": "List all commands with descriptions; or `help <cmd>` for detailed info on one command (usage, flags, ban-risk, when-to-use). Reads ilml-plugin.json directly.", "usage": "ilml linkedin help [<cmd>]", "useWhen": "You forgot what a command does, or you're an AI agent picking the right tool." },
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"usage": "ilml linkedin connect <add|fill|list|approve|note|no-note|skip|priority|run> [...]",
|
|
54
54
|
"flags": {
|
|
55
55
|
"add <file.json>": "Add profiles from a JSON array [{url, note?, name?}] to the queue. Dedupes against the queue and skips people already connected/pending. Combine with --tag=X and --priority=high|normal|low.",
|
|
56
|
-
"fill --category=...": "Fill the queue from people already categorised in your contacts DB (not yet connected). e.g. --category=founder,investor,hiring_manager (or --valuable for the standard high-value set). Each entry is tagged with its category so `quota` shows acceptance per category. --min-posts=N keeps only people who appeared in at least N of your job posts (the repeat-recruiter signal, useful with --category=recruiter). --max=N keeps the best N (ranked by priority, mutual connections, repeat count). Respects your excluded-locations setting. No browser.",
|
|
56
|
+
"fill --category=...": "Fill the queue from people already categorised in your contacts DB (not yet connected). e.g. --category=founder,investor,hiring_manager (or --valuable for the standard high-value set). Each entry is tagged with its category so `quota` shows acceptance per category. By default it VALIDATES that each person's stored title actually confirms the category (drops people whose title contradicts the tag — the category field is sometimes mis-set by enrichment; people with no stored title are held rather than visited, to avoid ban risk). --no-validate keeps the old trust-the-tag behaviour. --min-posts=N keeps only people who appeared in at least N of your job posts (the repeat-recruiter signal, useful with --category=recruiter). --max=N keeps the best N (ranked by priority, mutual connections, repeat count). Respects your excluded-locations setting. No browser.",
|
|
57
57
|
"list": "Show the queue (status, priority, note flag, name/title joined from your contacts). No browser. Optional --status=queued|approved|sent|skipped|failed.",
|
|
58
58
|
"approve <url>": "Move an entry from queued to approved. Or approve a whole batch with --all or --tag=X. Only approved entries are sent.",
|
|
59
59
|
"note <url> \"text\"": "Save a personal note on an entry (max 300 chars). It is sent ONLY when you run `connect run --with-notes` — by default connect sends plain requests, because LinkedIn caps custom notes to a handful per month. Shown with 📝 in `connect list`.",
|
package/package.json
CHANGED