ilml-plugin-linkedin 1.20.12 → 1.20.13
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 +10 -0
- package/dist/applyQueue.mjs +26 -26
- package/dist/connect.mjs +49 -49
- package/dist/daily.mjs +33 -33
- package/dist/enrichProfile.mjs +11 -11
- package/dist/enrichProfiles.mjs +38 -38
- package/dist/funnelRunner.mjs +39 -39
- package/dist/messageBot.mjs +40 -40
- package/dist/migrationCli.mjs +43 -43
- package/dist/profileHistory.mjs +8 -8
- package/dist/quota.mjs +32 -32
- package/dist/run.mjs +64 -61
- package/dist/scout.mjs +40 -39
- package/dist/src/saveLoginState.mjs +4 -4
- package/dist/syncAll.mjs +73 -73
- package/dist/syncConnections.mjs +30 -30
- package/dist/verifyAbout.mjs +14 -14
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +43 -43
- package/dist/visit.mjs +35 -35
- package/dist/warmScan.mjs +3 -3
- package/ilml-plugin.json +11 -2
- package/package.json +2 -2
package/dist/connect.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var Tr=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{for(var n in t)Tr(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Nr}from"@ilivemylife/graph-sdk";var jr,Se,fe,Ht,Wt,St=W(async()=>{jr=await Nr();for(let[e,t]of Object.entries(jr))process.env[e]===void 0&&(process.env[e]=t);Se=process.env.LINKEDIN_NAME,fe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Ht=Object.freeze(new Set([fe.DRAFT,fe.CONFIRMED,fe.NEEDS_REVIEW])),Wt=Object.freeze(new Set([fe.DRAFT,fe.CONFIRMED,fe.REJECTED,fe.NEEDS_REVIEW]))});import"dotenv/config";import*as q from"fs";import*as B from"path";import{fileURLToPath as Or}from"url";function Kn(){qe=null,Mr=null,pe=null,Pr=null,qr=null,Ur=null}function vt(){q.existsSync(me)||q.mkdirSync(me,{recursive:!0})}function et(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";q.writeFileSync(o,n);for(let r=0;r<3;r++)try{q.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function tt(e,t){if(!q.existsSync(e))return null;try{let n=JSON.parse(q.readFileSync(e,"utf-8"));try{q.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(q.existsSync(o))try{let r=JSON.parse(q.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{q.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{q.copyFileSync(e,e+".corrupted")}catch{}return null}}function nt(){return new Date().toISOString().split("T")[0]}function U(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Vn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Ue(e,t,n=null){if(!t||e[t])return t;let o=U(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(U(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Vn(n),i=Vn(e[r].name);if(s&&i&&s===i)return r}return t}function Vr(){q.existsSync(Yt)||q.mkdirSync(Yt,{recursive:!0})}function zn(e){let t=U(e);return t?B.join(Yt,`${t}.json`):null}function Hr(e){let t=zn(e);return t?tt(t,`profile-history/${U(e)}.json`)||[]:[]}function Wr(e,t){let n=zn(e);if(!n)return;Vr();let o=Hr(e);o.unshift(t);try{et(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${U(e)}: ${r.message}`)}}function Hn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Wn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Gr(e,t){if(!e)return[];let n=[];for(let o of Jr){let r=e[o],s=t[o];Hn(r)||Hn(s)||Wn(r)!==Wn(s)&&n.push(o)}return n}function Yr(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 H(){return qe||(vt(),qe=tt(Gt,"people.json")||{},qe)}function $t(e){vt(),qe=e;try{et(Gt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(Gt)}`)}}function kt(e,t={}){if(!e)return null;let n=H(),o=nt(),r=new Date().toISOString(),s=Ue(n,e,t.name),i=n[s];if(i){let c=Gr(i,t);c.length>0&&(Wr(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:Yr(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 a of Br)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(i[a])&&i[a].length>0)continue;i[a]=t[a]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return $t(n),n[s]}function Qn(e,t){if(!e||!t)return;let n=H(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let s={date:nt(),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(c=>c.date===s.date&&c.source===s.source&&c.action===s.action&&(c.jobId||"")===(s.jobId||""))&&(o.encounters.push(s),o.lastUpdated=new Date().toISOString(),$t(n))}function Xn(e){return e&&H()[e]?.connectionStatus||null}function Ct(e,t,n={}){if(!e)return;if(n.profileInfo)kt(e,n.profileInfo);else{let c=H(),a=Ue(c,e,n.profileInfo?.name);c[a]||kt(e,{})}let o=H(),r=Ue(o,e,n.profileInfo?.name),s=o[r];if(!s)return;let i=nt();s.connectionStatus=t,t==="connected"?s.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(s.requestedConnectionAt||(s.requestedConnectionAt=i)),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),$t(o)}function xt(e,t,n={}){if(n.dryRun||!e||!t)return;let o=U(t);if(!o)return;let r=H(),s=Ue(r,e),i=r[s];if(!i)return;let c=U(i.profileUrl||s);o!==c&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),$t(r)))}function Zn(){return pe||(vt(),pe=tt(Gn,"quota.json"),(!pe||!pe.connections)&&(pe={connections:[]}),pe)}function Kr(e){vt(),pe=e;try{et(Gn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function eo(e,t="unknown"){let n=Zn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Kr(n)}function to(){let e=Zn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function ot(){let e=to(),t=nt(),n=e.filter(a=>a.date===t).length,o=e.length,r=n>=Xe,s=o>=Ze,i=!r&&!s,c={allowed:i,daily:{sent:n,max:Xe},weekly:{sent:o,max:Ze}};return i||(c.reason=r?`Daily limit reached (${n}/${Xe})`:`Weekly limit reached (${o}/${Ze})`),c}function De(){let e=to(),t=nt(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Xe,remaining:Xe-n},weekly:{sent:o,max:Ze,remaining:Ze-o}}}var Fr,Lr,me,Gt,Na,Gn,ja,Oa,Fa,Yt,Yn,Xe,Ze,qe,Mr,pe,Pr,qr,Ur,Br,Jr,Re=W(async()=>{await St();Fr=Or(import.meta.url),Lr=B.dirname(B.dirname(Fr)),me=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Lr,"collected-profiles"),Gt=B.join(me,"people.json"),Na=B.join(me,"jobs.json"),Gn=B.join(me,"quota.json"),ja=B.join(me,"conversations.json"),Oa=B.join(me,"sync-state.json"),Fa=B.join(me,"application-questions.json"),Yt=B.join(me,"profile-history"),Yn=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Xe=Yn(process.env.CONNECT_MAX_DAILY,20),Ze=Yn(process.env.CONNECT_MAX_WEEKLY,100),qe=null,Mr=null,pe=null,Pr=null,qr=null,Ur=null;Br=["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"],Jr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var go={};z(go,{computeEngagement:()=>Xt,detectCategory:()=>ao,detectCategoryFromTitle:()=>Je,determineAction:()=>mo,determineLastMessageBy:()=>co,determineSituation:()=>lo,enrichConversation:()=>ti,enrichPerson:()=>ai,enrichPersonContext:()=>ho,extractAutoTags:()=>fo,generateSummary:()=>uo,normPreview:()=>Qt});function ti(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(a=>!Wt.has(a.status)),s=oi(t,e.profileUrl,n),i=co(r,t);if(e.lastMessageBy=i,e.conversationStatus=i==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let a=ao(r,t,s);a&&(e.category=a,e.categorySource=e.categorySource||"message_content")}if(e.situation=lo(r,i,t),r.length>0){let a=r[r.length-1];e.lastMessageTime=a.time}if(r.length>0&&!e.initiatedBy){let a=r[0];a.sender===Se?e.initiatedBy="us":a.sender!=="Unknown"&&a.sender!==""&&(e.initiatedBy="them")}e.engagement=Xt(r,t),e.personContext=ho(s),e.summary=uo(e,t,s),e.autoTags=fo(e,t,s);let c=mo(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=ni(e),e}function ao(e,t,n){if(!e||e.length===0)return n?.title?Je(n.title):null;let o=e.filter(r=>r.sender!==Se&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,s]of Object.entries(so))if(s.theirMessages){for(let i of s.theirMessages)if(i.test(o))return r}if(n?.title){let r=Je(n.title);if(r)return r}return null}function Je(e){if(!e)return null;for(let[t,n]of Object.entries(so))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function lo(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return io.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let r=[...e].reverse().find(s=>s.sender!==Se&&s.sender!=="Unknown");return io.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function co(e,t){if(!e||e.length===0)return"them";let n=[...e].map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,s)=>s.t-r.t).map(r=>r.m),o=n.length>0?n:[...e].reverse();for(let r of o){let s=r.sender;if(s===Se)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}function uo(e,t,n){let o=e.messages||[];if(o.length===0)return null;let r=[],s=e.category,i=n?.title,c=n?.company,a=n?.location;s==="recruiter"&&c?r.push(`Recruiter from ${c}`):s==="hiring_manager"&&c?r.push(`Hiring manager at ${c}`):s==="founder"&&c?r.push(`Founder of ${c}`):s&&i?r.push(`${Zt(s)}: ${Be(i,40)}`):i?r.push(Be(i,50)):r.push(t.split(" ")[0]);let l=o.filter(m=>m.sender!==Se&&m.sender!=="Unknown").map(m=>m.text).join(" "),u=ri(l),f=ii(l),d=si(l),p=[];return u&&p.push(u),d&&d!==a&&p.push(d),f&&p.push(f),p.length>0&&r.push(p.join(", ")),e.situation==="they_want_to_schedule_call"?r.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?r.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?r.push("needs reply"):e.conversationStatus==="awaiting_reply"&&r.push("waiting on them"),r.join(". ").replace(/\.\./g,".")}function fo(e,t,n){let o=[],r=(e.messages||[]).filter(l=>!Wt.has(l.status)),s=r.map(l=>l.text).join(" "),i=r.filter(l=>l.sender!==Se&&l.sender!=="Unknown").map(l=>l.text).join(" "),c=po(i,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(s)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(s)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(s)&&o.push("remote"),/\b(hybrid)\b/i.test(s)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(s)&&o.push("onsite"),/\b(java)\b/i.test(s)&&!/javascript/i.test(s)&&o.push("java"),/\b(python)\b/i.test(s)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(s)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(s)&&o.push("backend"),/\b(full.?stack)\b/i.test(s)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(s)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(s)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(s)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(s)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(s)&&o.push("has-salary");let a=e.engagement||Xt(r,t);return a.messageCount>=6&&o.push("active-thread"),a.theirCount===0&&a.ourCount>0&&o.push("no-response"),a.ourCount===0&&a.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(l=>Ht.has(l.status))&&o.push("has-draft"),[...new Set(o)]}function po(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],r=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],s=(e+" "+(t||"")).toLowerCase();for(let i of o)s.includes(i)&&n.push(i.replace(/\s+/g,"-"));for(let[i,c]of r)s.includes(i)&&n.push(c);return n}function mo(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Qt(e.lastMessagePreview)===Qt(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(s=>Ht.has(s.status));return r?r.status===fe.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Zt(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Xt(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,r=0,s=!1,i=!1,c=e.map(a=>a.text).join(" ");for(let a of e)a.sender===Se?n++:a.sender==="Unknown"||a.sender===""?r++:o++;return s=/\b(job|role|position|opening)\b/i.test(c),i=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:r,hasJob:s,hasSalary:i}}function ho(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function ni(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function oi(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let r=Ue(n,t,e);if(n[r])return n[r]}if(!e)return null;let o=Object.values(n).filter(r=>r.name===e);return o.length===1?o[0]:null}function Qt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Zt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Be(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function ri(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function ii(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function si(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function ai(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Je(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}li(e),e.personSummary=ci(e),e.personAutoTags=ui(e);let n=di(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=fi(e)),e}function li(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function ci(e){let t=[],n=e.category,o=e.title,r=e.company,s=e.location;if(n==="recruiter"&&r?t.push(`Recruiter at ${r}`):n==="hiring_manager"&&r?t.push(`Hiring manager at ${r}`):n==="founder"&&r?t.push(`Founder of ${r}`):o&&r?t.push(`${Be(o,40)} at ${Be(r,30)}`):o?t.push(Be(o,50)):e.name&&t.push(e.name.split(" ")[0]),s&&t.push(s),e.connectionDate){let i=new Date(e.connectionDate);if(!isNaN(i)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[i.getMonth()]} ${i.getDate()}`)}}if(e.jobCount>0){let i=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(i+=` (last: ${Be(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(i+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}i+=")"}t.push(i)}return t.join(". ").replace(/\.\./g,".")||null}function ui(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=po("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function di(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Zt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function fi(e){let t=e.category;if(!t)return null;let n=pi(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function pi(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var so,io,en=W(async()=>{await St();await Re();so={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]}};io=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var $o={};z($o,{BLOCK_MARKERS:()=>So,dedupeAndCap:()=>vo,extractSidePanelProfiles:()=>Li,normalizeFundUrl:()=>It,normalizeProfileUrl:()=>Ve,scanRelatedBlocks:()=>ko});function Ve(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function It(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function ko(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=l=>(l||"").replace(/\s+/g," ").trim(),r=l=>{let u=String(l||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},s=l=>o(l).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),i=l=>{let u=l,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let p=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(p))return u}return f||l.parentElement},c=[],a=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let l of a){let u=o(l.textContent).toLowerCase();if(!u)continue;let f=e.find(([h])=>u.includes(h));if(!f)continue;let d=f[1],p=i(l);if(!p)continue;let m=0,g=new Set;for(let h of Array.from(p.querySelectorAll('a[href*="/in/"]'))){let y=h.href||h.getAttribute("href")||"",k=r(y);if(!k)continue;let A=h.querySelector('span[aria-hidden="true"]'),w=o(A?A.textContent:h.getAttribute("aria-label")||h.textContent),S=s(w);if(!S||g.has(k))continue;g.add(k);let x="",b=w.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(b&&(x=o(b[1])),!x){let D=h.closest("li")||h.parentElement;D&&(x=Array.from(D.querySelectorAll("p, span")).map(R=>o(R.textContent)).filter(R=>R&&R!==S&&!/^view\b/i.test(R)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(R)&&/[a-z]/i.test(R)&&R.length>2)[0]||"")}c.push({href:y,name:S,headline:x,block:d,rank:m++})}}return c}function vo(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=Ve(t.seedUrl||""),r=new Map,s={};for(let i of e||[]){let c=Ve(i.href);c&&(o&&c===o||(s[i.block]=s[i.block]||0,!(s[i.block]>=n)&&(r.has(c)||(s[i.block]++,r.set(c,{url:c,name:i.name,headline:i.headline||null,block:i.block,rank:i.rank})))))}return Array.from(r.values())}async function Li(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(ko,So)}catch{return[]}return vo(n,t)}var So,ln=W(()=>{So=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var Io={};z(Io,{getJobDecision:()=>Ji,getLastVisit:()=>Qi,getScoutStats:()=>Xi,loadCompanies:()=>mn,loadDiscoveredPeople:()=>Oe,loadJobDecisions:()=>pn,loadScoutedJobs:()=>fn,loadVisitLog:()=>Tt,recordCompany:()=>Yi,recordDiscoveredEdge:()=>Wi,recordDiscoveredEdges:()=>Gi,recordVisit:()=>zi,resetCaches:()=>dn,saveCompany:()=>Ki,saveDiscoveredPerson:()=>Vi,saveScoutedJob:()=>Ui,setJobDecision:()=>Bi});import"dotenv/config";import*as se from"fs";import*as te from"path";import{fileURLToPath as Mi}from"url";function ve(){se.existsSync(je)||se.mkdirSync(je,{recursive:!0})}function $e(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";se.writeFileSync(o,n);for(let r=0;r<3;r++)try{se.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function ut(e){try{if(se.existsSync(e))return JSON.parse(se.readFileSync(e,"utf-8"))}catch{}return null}function dn(){st=null,at=null,lt=null,ct=null,Ne=null}function fn(){return st||(st=ut(Co)||{},st)}function Ui(e,t){if(!e)return;ve();let n=fn(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[r,s]of Object.entries(t))s!=null&&(n[e][r]=s);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{$e(Co,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function pn(){return at||(at=ut(Ao)||{},at)}function Bi(e,t,n={}){if(!e||!t)return;ve();let o=pn(),r=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=r,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:r,updatedAt:r,reason:n.reason||null,score:n.score??null,source:n.source||null};try{$e(Ao,o)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function Ji(e){return pn()[e]||null}function Oe(){return lt||(lt=ut(Rt)||{},lt)}function He(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Eo(e,t){let n=Ve(t)||t;if(e[n])return n;let o=He(t);if(!o)return n;let r=null;for(let[s,i]of Object.entries(e)){if(He(i&&(i.canonicalUrl||i.profileUrl)||s)===o)return s;!r&&i&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}return r||n}function Vi(e,t){if(!e)return;ve();let n=Oe(),o=new Date().toISOString().slice(0,10),r=Eo(n,e),s=He(e);if(n[r]){let i=n[r];t.name&&(i.name=t.name),t.title&&(i.title=t.title),t.company&&(i.company=t.company),t.location&&(i.location=t.location),t.role&&(i.role=t.role),t.isConnected!=null&&(i.isConnected=t.isConnected),t.jobId&&(i.jobIds||(i.jobIds=[]),i.jobIds.includes(t.jobId)||i.jobIds.push(t.jobId)),s&&He(i.canonicalUrl||i.profileUrl||r)!==s&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(s)||i.aliases.push(s)),i.lastSeen=o,i.seenCount=(i.seenCount||1)+1}else n[r]={canonicalUrl:r,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{$e(Rt,n)}catch(i){console.error(`[!] Failed to save discovered-people.json: ${i.message}`)}}function Hi(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function _o(e,t,n={},o){if(!t)return;let r=He(t);t=Eo(e,t);let s=n.seedUrl?{...n,seedUrl:Ve(n.seedUrl)||n.seedUrl}:n,i=o.slice(0,10),{edge:c,match:a}=Hi(s,o),l=e[t];l||(l=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:i,firstSeen:i,lastSeen:i}),n.name&&(l.name=n.name),n.headline&&(!l.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(l.headline))&&(l.headline=n.headline),n.location&&(l.location=l.location||n.location),n.company&&(l.company=n.company),n.companyUrl&&(l.companyUrl=l.companyUrl||n.companyUrl),n.isConnected!=null&&(l.isConnected=n.isConnected),n.connectionsCount!=null&&(l.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(l.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(l.connectGate=n.connectGate),n.note&&!l.note&&(l.note=n.note),n.whyUseful&&!l.whyUseful&&(l.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(l.extra={...l.extra||{},...n.extra}),Array.isArray(l.sources)||(l.sources=[]);let u=l.sources.find(a);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):l.sources.push(c),Array.isArray(l.categories)||(l.categories=[]),Array.isArray(l.sectors)||(l.sectors=[]),Array.isArray(l.aliases)||(l.aliases=[]),Array.isArray(l.graphRefs)||(l.graphRefs=[]),cn(l.categories,n.category),Dt(l.categories,n.categories),Dt(l.sectors,n.sectors),Dt(l.aliases,n.aliases),r&&He(l.canonicalUrl||t)!==r&&cn(l.aliases,r),Dt(l.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(l.affiliations)||(l.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||l.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||l.affiliations.push(f)}l.lastSeen=i,l.seenCount=(l.seenCount||0)+1}function Wi(e,t={}){if(!e)return;ve();let n=Oe();_o(n,e,t,new Date().toISOString());try{$e(Rt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Gi(e){if(!Array.isArray(e)||e.length===0)return;ve();let t=Oe(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(_o(t,r.url,r,n),o++);if(o)try{$e(Rt,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function Yi(e={}){if(!e||!e.name)return;ve();let t=e.key||It(e.website)||It(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=mn(),o=new Date().toISOString().slice(0,10),r=(a,l)=>{l&&Array.isArray(a)&&!a.includes(l)&&a.push(l)},s=(a,l)=>{if(Array.isArray(l))for(let u of l)r(a,u)},i=n[t];i||(i=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(i.name=e.name),e.website&&(i.website=i.website||e.website),e.linkedinUrl&&(i.linkedinUrl=i.linkedinUrl||e.linkedinUrl);for(let a of["size","check","stage","location","industries","about"])e[a]&&!i[a]&&(i[a]=e[a]);e.note&&!i.note&&(i.note=e.note),e.whyUseful&&!i.whyUseful&&(i.whyUseful=e.whyUseful),e.fitScore!=null&&(i.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(i.extra={...i.extra||{},...e.extra});for(let a of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(i[a])||(i[a]=[]),s(i[a],e[a]);Array.isArray(i.people)||(i.people=[]);let c=a=>{if(!a||!a.url)return;let l=i.people.find(u=>u.url===a.url&&(u.role||null)===(a.role||null));l?a.current!=null&&(l.current=a.current):i.people.push({url:a.url,name:a.name||null,role:a.role||null,current:a.current??null,from:a.from??null,to:a.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(a=>c({url:a.url,name:a.name,role:"Partner",current:!0})),Array.isArray(i.portfolio)||(i.portfolio=[]);for(let a of e.portfolio||[]){let l=a&&(a.key||a.name);l&&!i.portfolio.some(u=>(u.key||u.name)===l)&&i.portfolio.push(a)}i.lastSeen=o,i.seenCount=(i.seenCount||0)+1;try{$e(un,n)}catch(a){console.error(`[!] Failed to save companies.json: ${a.message}`)}return t}function mn(){return ct||(ct=ut(un)||{},ct)}function Ki(e,t){if(!e)return;ve();let n=mn(),o=new Date().toISOString().slice(0,10);if(n[e]){let r=n[e];t.name&&(r.name=t.name),t.about&&(r.about=t.about),t.size&&(r.size=t.size),t.industries&&(r.industries=t.industries),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),t.recruiterUrl&&(r.recruiterUrls||(r.recruiterUrls=[]),r.recruiterUrls.includes(t.recruiterUrl)||r.recruiterUrls.push(t.recruiterUrl)),r.lastSeen=o,r.jobCount=r.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{$e(un,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function Tt(){return Ne||(Ne=ut(xo)||{visits:[]},Array.isArray(Ne.visits)||(Ne.visits=[]),Ne)}function zi(e,t={}){if(!e)return;ve();let n=Tt();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{$e(xo,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function Qi(e){let t=Tt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function Xi(){let e=fn(),t=Oe(),n=Object.values(e),o=Object.values(t),r={};for(let d of n)d.company&&(r[d.company]=(r[d.company]||0)+1);let s=Object.entries(r).sort((d,p)=>p[1]-d[1]).slice(0,5).map(([d,p])=>`${d} (${p})`),i={};for(let d of n)for(let p of d.techStack||[])i[p]=(i[p]||0)+1;let c=Object.entries(i).sort((d,p)=>p[1]-d[1]).slice(0,8).map(([d,p])=>`${d} (${p})`),a=Tt(),l=new Date().toISOString().slice(0,10),u=a.visits.filter(d=>d.date.startsWith(l)).length,f=new Set(a.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:s,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,p)=>(p.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var Pi,qi,je,Co,Rt,xo,un,Ao,st,at,lt,cn,Dt,ct,Ne,Nt=W(()=>{ln();Pi=Mi(import.meta.url),qi=te.dirname(te.dirname(Pi)),je=process.env.DATA_DIR?te.resolve(process.env.DATA_DIR,"market-research"):te.join(qi,"market-research"),Co=te.join(je,"scouted-jobs.json"),Rt=te.join(je,"discovered-people.json"),xo=te.join(je,"visit-log.json"),un=te.join(je,"companies.json"),Ao=te.join(je,"job-decisions.json");st=null;at=null;lt=null;cn=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Dt=(e,t)=>{if(Array.isArray(t))for(let n of t)cn(e,n)};ct=null;Ne=null});var Mo={};z(Mo,{DEFAULT_PROFILE_INTERESTS:()=>Ot,computeFit:()=>wn,detectSectors:()=>ys});function ys(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(gs))r.some(s=>s.test(t))&&n.push(o);return n}function wn(e,t=Ot){if(!Array.isArray(e)||e.length===0)return 0;let n=s=>typeof s=="number"&&Number.isFinite(s)?s:0,o=Math.max(1,...Object.values(t||{}).map(n)),r=0;for(let s of e){let i=n(t&&t[s]);i>r&&(r=i)}return Math.min(1,r/o)}var gs,Ot,bn=W(()=>{gs={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};Ot={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import Z from"fs";import we from"path";function Sn(){let e=process.env.ILML_SCOPE_DIR;return e?we.join(e,"plugins-state","linkedin","cookies.json"):xs}function As(){let e=Sn(),t=we.dirname(e);return t&&t!=="."&&!Z.existsSync(t)&&Z.mkdirSync(t,{recursive:!0}),e}function Uo(e){let t=As();return Z.writeFileSync(t,JSON.stringify(e)),t}function Bo(){let e=Sn();if(!Z.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Z.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 Jo(){return Z.existsSync(Sn())}function Es(){let e=process.env.ILML_SCOPE_DIR;return e?we.join(e,"plugins-state","linkedin"):"."}function Vo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function _s(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Vo(t[1]):"default"}function Ho(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Z.existsSync(t)||Z.mkdirSync(t,{recursive:!0}),we.resolve(t);let n=Vo(e||_s()),o=we.join(Es(),"chrome-profile",n);return Z.existsSync(o)||Z.mkdirSync(o,{recursive:!0}),we.resolve(o)}function Go(e){return!Z.existsSync(we.join(e,Wo))}function kn(e){try{Z.writeFileSync(we.join(e,Wo),new Date().toISOString())}catch{}}function Yo(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Z.rmSync(we.join(e,n),{force:!0}),t++}catch{}return t}var xs,Wo,vn=W(()=>{xs="cookies.json";Wo=".ilml-seeded"});var er={};z(er,{_pidAlive:()=>$n,launchWithProfile:()=>js,markProfileEstablished:()=>Fs,registerBrowserForCleanup:()=>Zo,resolveProfileHolder:()=>Cn,seedCookiesIfNeeded:()=>Os});import xn from"fs";import Is from"path";async function Ft(){let e=[...ft].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ft.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Rs(){if(Ko)return;Ko=!0;let e=t=>async()=>{await Ft(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Ft(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Ft(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Ft(),process.exit(0))}),process.on("exit",()=>{for(let t of ft)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function An(e){return Is.join(e,".ilml-browser-session.json")}function Qo(e,t={}){try{xn.writeFileSync(An(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Ts(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Qo(e,n?{wsEndpoint:n}:{})}catch{}}function Ns(e){let t=Xo(e);t&&t.ownerPid===process.pid&&dt(e)}function dt(e){try{xn.rmSync(An(e),{force:!0})}catch{}}function Xo(e){try{return JSON.parse(xn.readFileSync(An(e),"utf-8"))}catch{return null}}function $n(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function zo(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Cn(e,t,{probeTimeoutMs:n=4e3}={}){let o=Xo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&$n(o.ownerPid)?"live":(dt(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await zo(s,n,r);if(i===r)return s.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!i)return dt(t),"free";if($n(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await zo(i.close().then(()=>!0).catch(()=>!1),n,!1))return dt(t),"free";try{i.disconnect()}catch{}return"live"}function Zo(e,t){e&&(Rs(),ft.add(e),e.on("disconnected",()=>{ft.delete(e),t&&dt(t)}))}async function js(e,t={}){let n=Ho(),o={...Ds,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Cn(e,n)==="live")throw new Error(r);Qo(n);let s;try{s=await e.launch(o)}catch{if(await Cn(e,n)==="live")throw new Error(r);Yo(n);try{s=await e.launch(o)}catch(c){throw Ns(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return Zo(s,n),Ts(n,s),{browser:s,profileDir:n,needsSeed:Go(n)}}async function Os(e,t){if(!t||!t.needsSeed)return!1;if(!Jo())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Bo()),kn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}function Fs(e){kn(e)}var Ds,ft,Ko,tr=W(()=>{vn();Ds={headless:!1,defaultViewport:null,protocolTimeout:3e5},ft=new Set,Ko=!1});var or={};z(or,{AUTHWALL_RE:()=>In,cleanSearchName:()=>Bs,delayed:()=>C,dismissPremiumOverlay:()=>xe,ensureInboxPage:()=>qs,gotoWithReauth:()=>Pe,isAuthwallUrl:()=>mt,parseLinkedInTime:()=>Ps,recoverFromAuthwall:()=>Lt,safeParseInt:()=>Us,stripDesignations:()=>Js,utilityFunction:()=>Ls,waitForPageReady:()=>nr,waitPastReauth:()=>_n});function Ls(){console.log("Utility function called...")}function pt(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 Ps(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 c=pt(n),a=new Date(t);return c?a.setHours(c.hours,c.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let c=Ms[o[1].toLowerCase()],a=pt(o[2]||""),l=new Date(t),f=l.getDay()-c;return f<=0&&(f+=7),l.setDate(l.getDate()-f),a?l.setHours(a.hours,a.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 c=En[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(r[2],10),l=parseInt(r[3],10),u=pt(r[4]||"");return new Date(l,c,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(s){let c=En[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(s[2],10),l=pt(s[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let c=En[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(i[2],10),l=pt(i[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function C(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function nr(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-s;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}function mt(e){return In.test(e||"")}async function Lt(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let a="wait";try{a=await e.evaluate(l=>!new RegExp(l).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",In.source)}catch{}if(a==="in"){try{let l=await e.cookies();if(Array.isArray(l)&&l.some(f=>f.name==="li_at")){let f=Uo(l);console.log(` \u2713 Session recovered \u2014 re-saved ${l.length} cookies (${f}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(l){console.log(` \u2713 Session recovered (cookie re-save skipped: ${l.message}).`)}return!0}if(a==="creds"){if(!o){let l=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}i||(i=!0,console.log(`
|
|
1
|
+
var Lr=Object.defineProperty;var V=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{for(var n in t)Lr(e,n,{get:t[n],enumerable:!0})};function Pr(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function Vn(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&n.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&n.set("distance",String(s)),Hn(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),Hn(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let i=Pr(e.JOB_SEARCH_COMPANY_IDS);i.length&&n.set("f_C",i.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&n.set("f_TPR",Fr[c]||c),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let a="https://www.linkedin.com/jobs/search/?"+n.toString(),l=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return l&&(a+="&"+l),a}var Fr,Hn,Wn=V(()=>{Fr={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},Hn=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as Mr}from"@ilivemylife/graph-sdk";var qr,Gn,Se,fe,Vt,Wt,St=V(async()=>{Wn();qr=await Mr();for(let[e,t]of Object.entries(qr))process.env[e]===void 0&&(process.env[e]=t);Gn=Vn(process.env);Gn&&(process.env.LINKEDIN_SEARCH_URL=Gn);Se=process.env.LINKEDIN_NAME,fe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Vt=Object.freeze(new Set([fe.DRAFT,fe.CONFIRMED,fe.NEEDS_REVIEW])),Wt=Object.freeze(new Set([fe.DRAFT,fe.CONFIRMED,fe.REJECTED,fe.NEEDS_REVIEW]))});import"dotenv/config";import*as q from"fs";import*as B from"path";import{fileURLToPath as Ur}from"url";function Zn(){qe=null,Hr=null,pe=null,Vr=null,Wr=null,Gr=null}function vt(){q.existsSync(me)||q.mkdirSync(me,{recursive:!0})}function et(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";q.writeFileSync(o,n);for(let r=0;r<3;r++)try{q.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function tt(e,t){if(!q.existsSync(e))return null;try{let n=JSON.parse(q.readFileSync(e,"utf-8"));try{q.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(q.existsSync(o))try{let r=JSON.parse(q.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{q.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{q.copyFileSync(e,e+".corrupted")}catch{}return null}}function nt(){return new Date().toISOString().split("T")[0]}function U(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Yn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Ue(e,t,n=null){if(!t||e[t])return t;let o=U(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(U(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Yn(n),i=Yn(e[r].name);if(s&&i&&s===i)return r}return t}function zr(){q.existsSync(Yt)||q.mkdirSync(Yt,{recursive:!0})}function eo(e){let t=U(e);return t?B.join(Yt,`${t}.json`):null}function Qr(e){let t=eo(e);return t?tt(t,`profile-history/${U(e)}.json`)||[]:[]}function Xr(e,t){let n=eo(e);if(!n)return;zr();let o=Qr(e);o.unshift(t);try{et(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${U(e)}: ${r.message}`)}}function Kn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function zn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Zr(e,t){if(!e)return[];let n=[];for(let o of Kr){let r=e[o],s=t[o];Kn(r)||Kn(s)||zn(r)!==zn(s)&&n.push(o)}return n}function ei(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 W(){return qe||(vt(),qe=tt(Gt,"people.json")||{},qe)}function $t(e){vt(),qe=e;try{et(Gt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(Gt)}`)}}function kt(e,t={}){if(!e)return null;let n=W(),o=nt(),r=new Date().toISOString(),s=Ue(n,e,t.name),i=n[s];if(i){let c=Zr(i,t);c.length>0&&(Xr(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:ei(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 a of Yr)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(i[a])&&i[a].length>0)continue;i[a]=t[a]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return $t(n),n[s]}function to(e,t){if(!e||!t)return;let n=W(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let s={date:nt(),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(c=>c.date===s.date&&c.source===s.source&&c.action===s.action&&(c.jobId||"")===(s.jobId||""))&&(o.encounters.push(s),o.lastUpdated=new Date().toISOString(),$t(n))}function no(e){return e&&W()[e]?.connectionStatus||null}function Ct(e,t,n={}){if(!e)return;if(n.profileInfo)kt(e,n.profileInfo);else{let c=W(),a=Ue(c,e,n.profileInfo?.name);c[a]||kt(e,{})}let o=W(),r=Ue(o,e,n.profileInfo?.name),s=o[r];if(!s)return;let i=nt();s.connectionStatus=t,t==="connected"?s.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(s.requestedConnectionAt||(s.requestedConnectionAt=i)),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),$t(o)}function At(e,t,n={}){if(n.dryRun||!e||!t)return;let o=U(t);if(!o)return;let r=W(),s=Ue(r,e),i=r[s];if(!i)return;let c=U(i.profileUrl||s);o!==c&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),$t(r)))}function oo(){return pe||(vt(),pe=tt(Qn,"quota.json"),(!pe||!pe.connections)&&(pe={connections:[]}),pe)}function ti(e){vt(),pe=e;try{et(Qn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function ro(e,t="unknown"){let n=oo(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),ti(n)}function io(){let e=oo(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function ot(){let e=io(),t=nt(),n=e.filter(a=>a.date===t).length,o=e.length,r=n>=Xe,s=o>=Ze,i=!r&&!s,c={allowed:i,daily:{sent:n,max:Xe},weekly:{sent:o,max:Ze}};return i||(c.reason=r?`Daily limit reached (${n}/${Xe})`:`Weekly limit reached (${o}/${Ze})`),c}function Re(){let e=io(),t=nt(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Xe,remaining:Xe-n},weekly:{sent:o,max:Ze,remaining:Ze-o}}}var Br,Jr,me,Gt,Ua,Qn,Ba,Ja,Ha,Yt,Xn,Xe,Ze,qe,Hr,pe,Vr,Wr,Gr,Yr,Kr,De=V(async()=>{await St();Br=Ur(import.meta.url),Jr=B.dirname(B.dirname(Br)),me=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Jr,"collected-profiles"),Gt=B.join(me,"people.json"),Ua=B.join(me,"jobs.json"),Qn=B.join(me,"quota.json"),Ba=B.join(me,"conversations.json"),Ja=B.join(me,"sync-state.json"),Ha=B.join(me,"application-questions.json"),Yt=B.join(me,"profile-history"),Xn=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Xe=Xn(process.env.CONNECT_MAX_DAILY,20),Ze=Xn(process.env.CONNECT_MAX_WEEKLY,100),qe=null,Hr=null,pe=null,Vr=null,Wr=null,Gr=null;Yr=["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"],Kr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var So={};z(So,{computeEngagement:()=>Xt,detectCategory:()=>fo,detectCategoryFromTitle:()=>Je,determineAction:()=>wo,determineLastMessageBy:()=>mo,determineSituation:()=>po,enrichConversation:()=>ai,enrichPerson:()=>pi,enrichPersonContext:()=>bo,extractAutoTags:()=>go,generateSummary:()=>ho,normPreview:()=>Qt});function ai(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(a=>!Wt.has(a.status)),s=ci(t,e.profileUrl,n),i=mo(r,t);if(e.lastMessageBy=i,e.conversationStatus=i==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let a=fo(r,t,s);a&&(e.category=a,e.categorySource=e.categorySource||"message_content")}if(e.situation=po(r,i,t),r.length>0){let a=r[r.length-1];e.lastMessageTime=a.time}if(r.length>0&&!e.initiatedBy){let a=r[0];a.sender===Se?e.initiatedBy="us":a.sender!=="Unknown"&&a.sender!==""&&(e.initiatedBy="them")}e.engagement=Xt(r,t),e.personContext=bo(s),e.summary=ho(e,t,s),e.autoTags=go(e,t,s);let c=wo(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=li(e),e}function fo(e,t,n){if(!e||e.length===0)return n?.title?Je(n.title):null;let o=e.filter(r=>r.sender!==Se&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,s]of Object.entries(uo))if(s.theirMessages){for(let i of s.theirMessages)if(i.test(o))return r}if(n?.title){let r=Je(n.title);if(r)return r}return null}function Je(e){if(!e)return null;for(let[t,n]of Object.entries(uo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function po(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return co.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let r=[...e].reverse().find(s=>s.sender!==Se&&s.sender!=="Unknown");return co.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function mo(e,t){if(!e||e.length===0)return"them";let n=[...e].map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,s)=>s.t-r.t).map(r=>r.m),o=n.length>0?n:[...e].reverse();for(let r of o){let s=r.sender;if(s===Se)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}function ho(e,t,n){let o=e.messages||[];if(o.length===0)return null;let r=[],s=e.category,i=n?.title,c=n?.company,a=n?.location;s==="recruiter"&&c?r.push(`Recruiter from ${c}`):s==="hiring_manager"&&c?r.push(`Hiring manager at ${c}`):s==="founder"&&c?r.push(`Founder of ${c}`):s&&i?r.push(`${Zt(s)}: ${Be(i,40)}`):i?r.push(Be(i,50)):r.push(t.split(" ")[0]);let l=o.filter(m=>m.sender!==Se&&m.sender!=="Unknown").map(m=>m.text).join(" "),u=ui(l),f=di(l),d=fi(l),p=[];return u&&p.push(u),d&&d!==a&&p.push(d),f&&p.push(f),p.length>0&&r.push(p.join(", ")),e.situation==="they_want_to_schedule_call"?r.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?r.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?r.push("needs reply"):e.conversationStatus==="awaiting_reply"&&r.push("waiting on them"),r.join(". ").replace(/\.\./g,".")}function go(e,t,n){let o=[],r=(e.messages||[]).filter(l=>!Wt.has(l.status)),s=r.map(l=>l.text).join(" "),i=r.filter(l=>l.sender!==Se&&l.sender!=="Unknown").map(l=>l.text).join(" "),c=yo(i,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(s)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(s)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(s)&&o.push("remote"),/\b(hybrid)\b/i.test(s)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(s)&&o.push("onsite"),/\b(java)\b/i.test(s)&&!/javascript/i.test(s)&&o.push("java"),/\b(python)\b/i.test(s)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(s)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(s)&&o.push("backend"),/\b(full.?stack)\b/i.test(s)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(s)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(s)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(s)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(s)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(s)&&o.push("has-salary");let a=e.engagement||Xt(r,t);return a.messageCount>=6&&o.push("active-thread"),a.theirCount===0&&a.ourCount>0&&o.push("no-response"),a.ourCount===0&&a.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(l=>Vt.has(l.status))&&o.push("has-draft"),[...new Set(o)]}function yo(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],r=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],s=(e+" "+(t||"")).toLowerCase();for(let i of o)s.includes(i)&&n.push(i.replace(/\s+/g,"-"));for(let[i,c]of r)s.includes(i)&&n.push(c);return n}function wo(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Qt(e.lastMessagePreview)===Qt(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(s=>Vt.has(s.status));return r?r.status===fe.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Zt(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Xt(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,r=0,s=!1,i=!1,c=e.map(a=>a.text).join(" ");for(let a of e)a.sender===Se?n++:a.sender==="Unknown"||a.sender===""?r++:o++;return s=/\b(job|role|position|opening)\b/i.test(c),i=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:r,hasJob:s,hasSalary:i}}function bo(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function li(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function ci(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let r=Ue(n,t,e);if(n[r])return n[r]}if(!e)return null;let o=Object.values(n).filter(r=>r.name===e);return o.length===1?o[0]:null}function Qt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Zt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Be(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function ui(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function di(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function fi(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function pi(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Je(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}mi(e),e.personSummary=hi(e),e.personAutoTags=gi(e);let n=yi(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=wi(e)),e}function mi(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function hi(e){let t=[],n=e.category,o=e.title,r=e.company,s=e.location;if(n==="recruiter"&&r?t.push(`Recruiter at ${r}`):n==="hiring_manager"&&r?t.push(`Hiring manager at ${r}`):n==="founder"&&r?t.push(`Founder of ${r}`):o&&r?t.push(`${Be(o,40)} at ${Be(r,30)}`):o?t.push(Be(o,50)):e.name&&t.push(e.name.split(" ")[0]),s&&t.push(s),e.connectionDate){let i=new Date(e.connectionDate);if(!isNaN(i)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[i.getMonth()]} ${i.getDate()}`)}}if(e.jobCount>0){let i=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(i+=` (last: ${Be(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(i+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}i+=")"}t.push(i)}return t.join(". ").replace(/\.\./g,".")||null}function gi(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=yo("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function yi(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Zt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function wi(e){let t=e.category;if(!t)return null;let n=bi(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function bi(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var uo,co,en=V(async()=>{await St();await De();uo={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]}};co=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Eo={};z(Eo,{BLOCK_MARKERS:()=>Co,dedupeAndCap:()=>xo,extractSidePanelProfiles:()=>Ji,normalizeFundUrl:()=>It,normalizeProfileUrl:()=>He,scanRelatedBlocks:()=>Ao});function He(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function It(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Ao(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=l=>(l||"").replace(/\s+/g," ").trim(),r=l=>{let u=String(l||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},s=l=>o(l).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),i=l=>{let u=l,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let p=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(p))return u}return f||l.parentElement},c=[],a=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let l of a){let u=o(l.textContent).toLowerCase();if(!u)continue;let f=e.find(([h])=>u.includes(h));if(!f)continue;let d=f[1],p=i(l);if(!p)continue;let m=0,g=new Set;for(let h of Array.from(p.querySelectorAll('a[href*="/in/"]'))){let y=h.href||h.getAttribute("href")||"",k=r(y);if(!k)continue;let x=h.querySelector('span[aria-hidden="true"]'),w=o(x?x.textContent:h.getAttribute("aria-label")||h.textContent),S=s(w);if(!S||g.has(k))continue;g.add(k);let A="",b=w.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(b&&(A=o(b[1])),!A){let R=h.closest("li")||h.parentElement;R&&(A=Array.from(R.querySelectorAll("p, span")).map(D=>o(D.textContent)).filter(D=>D&&D!==S&&!/^view\b/i.test(D)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(D)&&/[a-z]/i.test(D)&&D.length>2)[0]||"")}c.push({href:y,name:S,headline:A,block:d,rank:m++})}}return c}function xo(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=He(t.seedUrl||""),r=new Map,s={};for(let i of e||[]){let c=He(i.href);c&&(o&&c===o||(s[i.block]=s[i.block]||0,!(s[i.block]>=n)&&(r.has(c)||(s[i.block]++,r.set(c,{url:c,name:i.name,headline:i.headline||null,block:i.block,rank:i.rank})))))}return Array.from(r.values())}async function Ji(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(Ao,Co)}catch{return[]}return xo(n,t)}var Co,ln=V(()=>{Co=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var No={};z(No,{getJobDecision:()=>Ki,getLastVisit:()=>os,getScoutStats:()=>rs,loadCompanies:()=>mn,loadDiscoveredPeople:()=>je,loadJobDecisions:()=>pn,loadScoutedJobs:()=>fn,loadVisitLog:()=>Tt,recordCompany:()=>es,recordDiscoveredEdge:()=>Xi,recordDiscoveredEdges:()=>Zi,recordVisit:()=>ns,resetCaches:()=>dn,saveCompany:()=>ts,saveDiscoveredPerson:()=>zi,saveScoutedJob:()=>Gi,setJobDecision:()=>Yi});import"dotenv/config";import*as se from"fs";import*as te from"path";import{fileURLToPath as Hi}from"url";function ve(){se.existsSync(Oe)||se.mkdirSync(Oe,{recursive:!0})}function $e(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";se.writeFileSync(o,n);for(let r=0;r<3;r++)try{se.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function ut(e){try{if(se.existsSync(e))return JSON.parse(se.readFileSync(e,"utf-8"))}catch{}return null}function dn(){st=null,at=null,lt=null,ct=null,Ne=null}function fn(){return st||(st=ut(_o)||{},st)}function Gi(e,t){if(!e)return;ve();let n=fn(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[r,s]of Object.entries(t))s!=null&&(n[e][r]=s);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{$e(_o,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function pn(){return at||(at=ut(Ro)||{},at)}function Yi(e,t,n={}){if(!e||!t)return;ve();let o=pn(),r=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=r,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:r,updatedAt:r,reason:n.reason||null,score:n.score??null,source:n.source||null};try{$e(Ro,o)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function Ki(e){return pn()[e]||null}function je(){return lt||(lt=ut(Dt)||{},lt)}function Ve(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Do(e,t){let n=He(t)||t;if(e[n])return n;let o=Ve(t);if(!o)return n;let r=null;for(let[s,i]of Object.entries(e)){if(Ve(i&&(i.canonicalUrl||i.profileUrl)||s)===o)return s;!r&&i&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}return r||n}function zi(e,t){if(!e)return;ve();let n=je(),o=new Date().toISOString().slice(0,10),r=Do(n,e),s=Ve(e);if(n[r]){let i=n[r];t.name&&(i.name=t.name),t.title&&(i.title=t.title),t.company&&(i.company=t.company),t.location&&(i.location=t.location),t.role&&(i.role=t.role),t.isConnected!=null&&(i.isConnected=t.isConnected),t.jobId&&(i.jobIds||(i.jobIds=[]),i.jobIds.includes(t.jobId)||i.jobIds.push(t.jobId)),s&&Ve(i.canonicalUrl||i.profileUrl||r)!==s&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(s)||i.aliases.push(s)),i.lastSeen=o,i.seenCount=(i.seenCount||1)+1}else n[r]={canonicalUrl:r,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{$e(Dt,n)}catch(i){console.error(`[!] Failed to save discovered-people.json: ${i.message}`)}}function Qi(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function To(e,t,n={},o){if(!t)return;let r=Ve(t);t=Do(e,t);let s=n.seedUrl?{...n,seedUrl:He(n.seedUrl)||n.seedUrl}:n,i=o.slice(0,10),{edge:c,match:a}=Qi(s,o),l=e[t];l||(l=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:i,firstSeen:i,lastSeen:i}),n.name&&(l.name=n.name),n.headline&&(!l.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(l.headline))&&(l.headline=n.headline),n.location&&(l.location=l.location||n.location),n.company&&(l.company=n.company),n.companyUrl&&(l.companyUrl=l.companyUrl||n.companyUrl),n.isConnected!=null&&(l.isConnected=n.isConnected),n.connectionsCount!=null&&(l.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(l.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(l.connectGate=n.connectGate),n.note&&!l.note&&(l.note=n.note),n.whyUseful&&!l.whyUseful&&(l.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(l.extra={...l.extra||{},...n.extra}),Array.isArray(l.sources)||(l.sources=[]);let u=l.sources.find(a);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):l.sources.push(c),Array.isArray(l.categories)||(l.categories=[]),Array.isArray(l.sectors)||(l.sectors=[]),Array.isArray(l.aliases)||(l.aliases=[]),Array.isArray(l.graphRefs)||(l.graphRefs=[]),cn(l.categories,n.category),Rt(l.categories,n.categories),Rt(l.sectors,n.sectors),Rt(l.aliases,n.aliases),r&&Ve(l.canonicalUrl||t)!==r&&cn(l.aliases,r),Rt(l.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(l.affiliations)||(l.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||l.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||l.affiliations.push(f)}l.lastSeen=i,l.seenCount=(l.seenCount||0)+1}function Xi(e,t={}){if(!e)return;ve();let n=je();To(n,e,t,new Date().toISOString());try{$e(Dt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Zi(e){if(!Array.isArray(e)||e.length===0)return;ve();let t=je(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(To(t,r.url,r,n),o++);if(o)try{$e(Dt,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function es(e={}){if(!e||!e.name)return;ve();let t=e.key||It(e.website)||It(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=mn(),o=new Date().toISOString().slice(0,10),r=(a,l)=>{l&&Array.isArray(a)&&!a.includes(l)&&a.push(l)},s=(a,l)=>{if(Array.isArray(l))for(let u of l)r(a,u)},i=n[t];i||(i=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(i.name=e.name),e.website&&(i.website=i.website||e.website),e.linkedinUrl&&(i.linkedinUrl=i.linkedinUrl||e.linkedinUrl);for(let a of["size","check","stage","location","industries","about"])e[a]&&!i[a]&&(i[a]=e[a]);e.note&&!i.note&&(i.note=e.note),e.whyUseful&&!i.whyUseful&&(i.whyUseful=e.whyUseful),e.fitScore!=null&&(i.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(i.extra={...i.extra||{},...e.extra});for(let a of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(i[a])||(i[a]=[]),s(i[a],e[a]);Array.isArray(i.people)||(i.people=[]);let c=a=>{if(!a||!a.url)return;let l=i.people.find(u=>u.url===a.url&&(u.role||null)===(a.role||null));l?a.current!=null&&(l.current=a.current):i.people.push({url:a.url,name:a.name||null,role:a.role||null,current:a.current??null,from:a.from??null,to:a.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(a=>c({url:a.url,name:a.name,role:"Partner",current:!0})),Array.isArray(i.portfolio)||(i.portfolio=[]);for(let a of e.portfolio||[]){let l=a&&(a.key||a.name);l&&!i.portfolio.some(u=>(u.key||u.name)===l)&&i.portfolio.push(a)}i.lastSeen=o,i.seenCount=(i.seenCount||0)+1;try{$e(un,n)}catch(a){console.error(`[!] Failed to save companies.json: ${a.message}`)}return t}function mn(){return ct||(ct=ut(un)||{},ct)}function ts(e,t){if(!e)return;ve();let n=mn(),o=new Date().toISOString().slice(0,10);if(n[e]){let r=n[e];t.name&&(r.name=t.name),t.about&&(r.about=t.about),t.size&&(r.size=t.size),t.industries&&(r.industries=t.industries),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),t.recruiterUrl&&(r.recruiterUrls||(r.recruiterUrls=[]),r.recruiterUrls.includes(t.recruiterUrl)||r.recruiterUrls.push(t.recruiterUrl)),r.lastSeen=o,r.jobCount=r.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{$e(un,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function Tt(){return Ne||(Ne=ut(Io)||{visits:[]},Array.isArray(Ne.visits)||(Ne.visits=[]),Ne)}function ns(e,t={}){if(!e)return;ve();let n=Tt();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{$e(Io,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function os(e){let t=Tt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function rs(){let e=fn(),t=je(),n=Object.values(e),o=Object.values(t),r={};for(let d of n)d.company&&(r[d.company]=(r[d.company]||0)+1);let s=Object.entries(r).sort((d,p)=>p[1]-d[1]).slice(0,5).map(([d,p])=>`${d} (${p})`),i={};for(let d of n)for(let p of d.techStack||[])i[p]=(i[p]||0)+1;let c=Object.entries(i).sort((d,p)=>p[1]-d[1]).slice(0,8).map(([d,p])=>`${d} (${p})`),a=Tt(),l=new Date().toISOString().slice(0,10),u=a.visits.filter(d=>d.date.startsWith(l)).length,f=new Set(a.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:s,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,p)=>(p.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var Vi,Wi,Oe,_o,Dt,Io,un,Ro,st,at,lt,cn,Rt,ct,Ne,Nt=V(()=>{ln();Vi=Hi(import.meta.url),Wi=te.dirname(te.dirname(Vi)),Oe=process.env.DATA_DIR?te.resolve(process.env.DATA_DIR,"market-research"):te.join(Wi,"market-research"),_o=te.join(Oe,"scouted-jobs.json"),Dt=te.join(Oe,"discovered-people.json"),Io=te.join(Oe,"visit-log.json"),un=te.join(Oe,"companies.json"),Ro=te.join(Oe,"job-decisions.json");st=null;at=null;lt=null;cn=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Rt=(e,t)=>{if(Array.isArray(t))for(let n of t)cn(e,n)};ct=null;Ne=null});var Bo={};z(Bo,{DEFAULT_PROFILE_INTERESTS:()=>jt,computeFit:()=>wn,detectSectors:()=>$s});function $s(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(vs))r.some(s=>s.test(t))&&n.push(o);return n}function wn(e,t=jt){if(!Array.isArray(e)||e.length===0)return 0;let n=s=>typeof s=="number"&&Number.isFinite(s)?s:0,o=Math.max(1,...Object.values(t||{}).map(n)),r=0;for(let s of e){let i=n(t&&t[s]);i>r&&(r=i)}return Math.min(1,r/o)}var vs,jt,bn=V(()=>{vs={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};jt={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import Z from"fs";import we from"path";function Sn(){let e=process.env.ILML_SCOPE_DIR;return e?we.join(e,"plugins-state","linkedin","cookies.json"):Ds}function Ts(){let e=Sn(),t=we.dirname(e);return t&&t!=="."&&!Z.existsSync(t)&&Z.mkdirSync(t,{recursive:!0}),e}function Vo(e){let t=Ts();return Z.writeFileSync(t,JSON.stringify(e)),t}function Wo(){let e=Sn();if(!Z.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Z.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 Go(){return Z.existsSync(Sn())}function Ns(){let e=process.env.ILML_SCOPE_DIR;return e?we.join(e,"plugins-state","linkedin"):"."}function Yo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Os(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Yo(t[1]):"default"}function Ko(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Z.existsSync(t)||Z.mkdirSync(t,{recursive:!0}),we.resolve(t);let n=Yo(e||Os()),o=we.join(Ns(),"chrome-profile",n);return Z.existsSync(o)||Z.mkdirSync(o,{recursive:!0}),we.resolve(o)}function Qo(e){return!Z.existsSync(we.join(e,zo))}function kn(e){try{Z.writeFileSync(we.join(e,zo),new Date().toISOString())}catch{}}function Xo(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Z.rmSync(we.join(e,n),{force:!0}),t++}catch{}return t}var Ds,zo,vn=V(()=>{Ds="cookies.json";zo=".ilml-seeded"});var rr={};z(rr,{_pidAlive:()=>$n,launchWithProfile:()=>qs,markProfileEstablished:()=>Bs,registerBrowserForCleanup:()=>or,resolveProfileHolder:()=>Cn,seedCookiesIfNeeded:()=>Us});import An from"fs";import js from"path";async function Lt(){let e=[...ft].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ft.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Fs(){if(Zo)return;Zo=!0;let e=t=>async()=>{await Lt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Lt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Lt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Lt(),process.exit(0))}),process.on("exit",()=>{for(let t of ft)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function xn(e){return js.join(e,".ilml-browser-session.json")}function tr(e,t={}){try{An.writeFileSync(xn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Ps(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();tr(e,n?{wsEndpoint:n}:{})}catch{}}function Ms(e){let t=nr(e);t&&t.ownerPid===process.pid&&dt(e)}function dt(e){try{An.rmSync(xn(e),{force:!0})}catch{}}function nr(e){try{return JSON.parse(An.readFileSync(xn(e),"utf-8"))}catch{return null}}function $n(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function er(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Cn(e,t,{probeTimeoutMs:n=4e3}={}){let o=nr(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&$n(o.ownerPid)?"live":(dt(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await er(s,n,r);if(i===r)return s.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!i)return dt(t),"free";if($n(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await er(i.close().then(()=>!0).catch(()=>!1),n,!1))return dt(t),"free";try{i.disconnect()}catch{}return"live"}function or(e,t){e&&(Fs(),ft.add(e),e.on("disconnected",()=>{ft.delete(e),t&&dt(t)}))}async function qs(e,t={}){let n=Ko(),o={...Ls,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Cn(e,n)==="live")throw new Error(r);tr(n);let s;try{s=await e.launch(o)}catch{if(await Cn(e,n)==="live")throw new Error(r);Xo(n);try{s=await e.launch(o)}catch(c){throw Ms(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return or(s,n),Ps(n,s),{browser:s,profileDir:n,needsSeed:Qo(n)}}async function Us(e,t){if(!t||!t.needsSeed)return!1;if(!Go())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Wo()),kn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}function Bs(e){kn(e)}var Ls,ft,Zo,ir=V(()=>{vn();Ls={headless:!1,defaultViewport:null,protocolTimeout:3e5},ft=new Set,Zo=!1});var ar={};z(ar,{AUTHWALL_RE:()=>In,cleanSearchName:()=>Ys,delayed:()=>C,dismissPremiumOverlay:()=>Ae,ensureInboxPage:()=>Ws,gotoWithReauth:()=>Me,isAuthwallUrl:()=>mt,parseLinkedInTime:()=>Vs,recoverFromAuthwall:()=>Ft,safeParseInt:()=>Gs,stripDesignations:()=>Ks,utilityFunction:()=>Js,waitForPageReady:()=>sr,waitPastReauth:()=>_n});function Js(){console.log("Utility function called...")}function pt(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 Vs(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 c=pt(n),a=new Date(t);return c?a.setHours(c.hours,c.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let c=Hs[o[1].toLowerCase()],a=pt(o[2]||""),l=new Date(t),f=l.getDay()-c;return f<=0&&(f+=7),l.setDate(l.getDate()-f),a?l.setHours(a.hours,a.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 c=En[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(r[2],10),l=parseInt(r[3],10),u=pt(r[4]||"");return new Date(l,c,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(s){let c=En[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(s[2],10),l=pt(s[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let c=En[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(i[2],10),l=pt(i[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function C(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function sr(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-s;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}function mt(e){return In.test(e||"")}async function Ft(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let a="wait";try{a=await e.evaluate(l=>!new RegExp(l).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",In.source)}catch{}if(a==="in"){try{let l=await e.cookies();if(Array.isArray(l)&&l.some(f=>f.name==="li_at")){let f=Vo(l);console.log(` \u2713 Session recovered \u2014 re-saved ${l.length} cookies (${f}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(l){console.log(` \u2713 Session recovered (cookie re-save skipped: ${l.message}).`)}return!0}if(a==="creds"){if(!o){let l=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}i||(i=!0,console.log(`
|
|
2
2
|
\u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
|
|
3
|
-
`))}await new Promise(l=>setTimeout(l,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function _n(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await
|
|
3
|
+
`))}await new Promise(l=>setTimeout(l,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function _n(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await sr(e,t,{timeout:o,label:n});if(!r&&mt(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function Me(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:s=6e4,autoRecover:i=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await _n(e,{readySelector:n,label:o,timeout:r})}catch(c){if(i&&c.code==="SESSION_EXPIRED"){await Ft(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await _n(e,{readySelector:n,label:o,timeout:r})}throw c}}async function Ws(e){let t=e.url();if(t.includes("/messaging"))return!1;if(mt(t)?await Ft(e,{label:"inbox"}):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 C(4e3),mt(e.url())&&(await Ft(e,{label:"inbox"}),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await C(3e3),mt(e.url())))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function Gs(e){return parseInt(e,10)||0}async function Ae(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"),i=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||i||c){let a=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:r.substring(0,80)};let l=o.querySelectorAll("button");for(let u of l){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.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 Ys(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 Ks(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 En,Hs,In,Pt=V(()=>{vn();En={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Hs={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};In=/\/authwall|\/login|\/checkpoint|\/uas\/login/});var lr={};z(lr,{extractCertificationsFromDetails:()=>ea,extractEducationFromDetails:()=>Xs,extractExperienceFromDetails:()=>zs,extractFeaturedFromDetails:()=>Qs,extractRecommendationsFromDetails:()=>ta,extractSkillsFromDetails:()=>Zs});async function zs(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await Me(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await C(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(900);await C(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.click(),!0;return!1});)r++,await C(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function i(u){let f=[];for(let d of u.querySelectorAll("div")){let p=Array.from(d.children).filter(g=>g.tagName==="DIV");if(p.length<3)continue;let m=p.filter(g=>(g.textContent||"").trim().length>50);m.length<3||(d.textContent||"").length<500||f.push({el:d,count:m.length,totalText:(d.textContent||"").length})}return f.sort((d,p)=>p.count-d.count||d.totalText-p.totalText),f[0]?.el}let c=i(s);if(!c)return[];let a=Array.from(c.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function l(u){let f=u[0]||null,d=null,p=null;if(u[1]){let $=u[1].split("\xB7").map(D=>D.trim());d=$[0]||null,$[1]&&(p=$[1])}let m=u.findIndex($=>/(\d{4}|present)/i.test($)&&/(-|–|—)/i.test($)&&$.length<80),g=null,h=null;if(m>=0){let $=u[m].split("\xB7").map(D=>D.trim());g=$[0]||null,$[1]&&(h=$[1])}let y=null,k=-1;if(m>=0&&u[m+1]){let $=u[m+1],D=/^[>*\-•]|^>/.test($),Y=/https?:\/\//.test($),J=/\d{4}/.test($),P=/,/.test($)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test($);!D&&!Y&&!J&&$.length<100&&P&&(y=$,k=m+1)}let x=null,w=-1,S=u[u.length-1];if(S&&/and\s+\+\d+\s+skills?$/i.test(S)){w=u.length-1;let $=S.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);$&&(x={listed:$[1].split(",").map(D=>D.trim()),additional:parseInt($[2],10)})}let A=new Set([0,1,m,k,w].filter($=>$>=0)),b=u.filter(($,D)=>!A.has(D)),R=b.length>0?b.join(`
|
|
4
4
|
|
|
5
|
-
`):null;return{title:f,company:d,employmentType:p,dates:g,duration:h,location:y,description:
|
|
6
|
-
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return l(d)}).filter(u=>u.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function ht(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await
|
|
5
|
+
`):null;return{title:f,company:d,employmentType:p,dates:g,duration:h,location:y,description:R,skills:x,_raw:u}}return a.map(u=>{let d=(u.innerText||"").trim().split(`
|
|
6
|
+
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return l(d)}).filter(u=>u.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function ht(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await Me(e,o,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:`details/${n}`}),await C(1e3);let r=e.url();if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let i=0;i<4;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(700);await C(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)s++,await C(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(600)}async function yt(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(r.code==="SESSION_EXPIRED"||/^session expired/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 Qs(e,t){return yt(t,"featured","extractFeaturedFromDetails",async()=>(await ht(e,t,"featured"),await e.evaluate(`(() => {
|
|
7
7
|
${gt}
|
|
8
8
|
|
|
9
9
|
const main = document.querySelector('main');
|
|
@@ -44,7 +44,7 @@ var Tr=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
44
44
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
45
45
|
return true;
|
|
46
46
|
});
|
|
47
|
-
})()`)))}async function
|
|
47
|
+
})()`)))}async function Xs(e,t){return yt(t,"education","extractEducationFromDetails",async()=>(await ht(e,t,"education"),await e.evaluate(`(() => {
|
|
48
48
|
${gt}
|
|
49
49
|
|
|
50
50
|
const main = document.querySelector('main');
|
|
@@ -81,7 +81,7 @@ var Tr=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
81
81
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
82
82
|
return true;
|
|
83
83
|
});
|
|
84
|
-
})()`)))}async function
|
|
84
|
+
})()`)))}async function Zs(e,t){return yt(t,"skills","extractSkillsFromDetails",async()=>(await ht(e,t,"skills"),await e.evaluate(`(() => {
|
|
85
85
|
${gt}
|
|
86
86
|
|
|
87
87
|
const main = document.querySelector('main');
|
|
@@ -113,7 +113,7 @@ var Tr=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
113
113
|
skills.push({ name, endorsements, _raw: lines });
|
|
114
114
|
}
|
|
115
115
|
return skills;
|
|
116
|
-
})()`)))}async function
|
|
116
|
+
})()`)))}async function ea(e,t){return yt(t,"certifications","extractCertificationsFromDetails",async()=>(await ht(e,t,"certifications"),await e.evaluate(`(() => {
|
|
117
117
|
${gt}
|
|
118
118
|
|
|
119
119
|
const main = document.querySelector('main');
|
|
@@ -138,7 +138,7 @@ var Tr=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
138
138
|
|
|
139
139
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
140
140
|
}).filter(e => e.name);
|
|
141
|
-
})()`)))}async function
|
|
141
|
+
})()`)))}async function ta(e,t){return yt(t,"recommendations","extractRecommendationsFromDetails",async()=>(await ht(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
142
142
|
${gt}
|
|
143
143
|
|
|
144
144
|
const main = document.querySelector('main');
|
|
@@ -174,7 +174,7 @@ var Tr=Object.defineProperty;var W=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{fo
|
|
|
174
174
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
175
175
|
return true;
|
|
176
176
|
});
|
|
177
|
-
})()`)))}var gt,
|
|
177
|
+
})()`)))}var gt,cr=V(()=>{Pt();gt=`
|
|
178
178
|
function findEntryContainer(root) {
|
|
179
179
|
const candidates = [];
|
|
180
180
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -237,22 +237,22 @@ function findEntryContainer(root) {
|
|
|
237
237
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
238
238
|
return candidates[0]?.el;
|
|
239
239
|
}
|
|
240
|
-
`});var lr={};z(lr,{clickConnectButton:()=>Rn,default:()=>Xs,detectConnectionStatus:()=>Ae,findConnectButton:()=>wt,runFunnel:()=>ar,sendConnectionRequest:()=>Tn,shouldExcludeLocation:()=>Pt,viewProfile:()=>Dn});async function sr(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: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Pt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Dn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:c=!1,extractCertifications:a=!1}=n;try{await Pe(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await C(1500),await xe(e)&&(console.log(" Dismissed Premium overlay"),await C(1500),await sr(e,t));let u=0;for(let w=0;w<2;w++){let S=await e.evaluate(()=>document.body.scrollHeight);for(let b=1;b<=6;b++)await e.evaluate(D=>window.scrollTo(0,D),S*b/6),await C(900);let x=await e.evaluate(()=>document.body.scrollHeight);if(x===u)break;u=x}await C(800);let f=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(f=w.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),S=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"]),x=E=>{let I=(E||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},b={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},D=document.querySelector("main");if(!D)return b;let $=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],R=Array.from(D.querySelectorAll("h2")),Y=$.find(E=>{let I=E.textContent&&E.textContent.trim(),N=(I||"").replace(/\s*\(\d+\)$/,"").trim();return I&&I.length>1&&I.length<100&&!w.has(N)&&!S.has(N)}),J=Y?Y.textContent.trim():null,M=Y?Y.parentElement:null;for(;M&&M!==D&&!Array.from(M.children).filter(I=>I.tagName==="P").some(I=>{let N=I.textContent&&I.textContent.trim();return N&&N.length>5&&!x(N)});)M=M.parentElement;let O=null,ee=null,T=null,K=null;if(M&&M!==D){let E=Array.from(M.children).filter(N=>N.tagName==="P").filter(N=>{let be=N.textContent&&N.textContent.trim();return be&&be.length>5&&!x(be)});if(E[0]&&(O=E[0].textContent.trim()),E[1]){let N=E[1].textContent.trim().split(/\s*[·•]\s*/);ee=N[0]||null,N.length>1&&(T=N.slice(1).join(" \xB7 "))}let I=Array.from(M.children).filter(N=>N.tagName==="DIV");for(let N=I.length-1;N>=0;N--){let be=I[N].textContent&&I[N].textContent.trim();if(be&&!(J&&be.startsWith(J))&&(K=be.split(/[·•]/)[0].trim(),K))break}}let Ie=null;if(M){let E=M.querySelectorAll("p, span, div");for(let I of E){let N=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){Ie=N;break}}}let _=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),F=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),V=F&&F.src||null,P=D.textContent||"",le=null,Fn=P.match(/(\d+\+?)\s+connections\b/i);Fn&&(le=Fn[1]+" connections");let bt=null,Ln=P.match(/(\d+)\s+mutual connection/i),Mn=P.match(/and\s+(\d+)\s+other mutual/i),Er=P.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Ln?bt=parseInt(Ln[1],10):Mn?bt=2+parseInt(Mn[1],10):Er&&(bt=2);let Pn=null,qn=null,Un=R.find(E=>E.textContent&&E.textContent.trim()==="About");if(Un){let E=Un.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let I=(E.textContent||"").trim();I=I.replace(/^About\s*/,"").trim();let N=I.match(/Top skills\s*(.+?)$/i);if(N){let Vt=N[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Rr=>Rr.trim()).filter(Boolean);Vt.length>0&&Vt.length<10&&(qn=Vt)}I=I.split(/\n?…\s*more/i)[0].trim(),I=I.split(/\n?\.\.\.\s*more/i)[0].trim(),I=I.split(/\bTop skills\b/i)[0].trim(),I=I.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Pn=I||null}}let Bn=null,Jn=R.find(E=>E.textContent&&E.textContent.trim()==="Activity");if(Jn){let E=Jn.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let I=(E.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);I&&(Bn=parseInt(I[1].replace(/,/g,""),10))}}let _r=[...new Set(R.map(E=>(E.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(E=>E&&E.length>1&&E.length<60&&E!==J).filter(E=>w.has(E)))],Qe=document.body.textContent||"",Ir=/#OpenToWork\b/i.test(Qe)||/\bOpen to work\b/.test(Qe),Dr=/#Hiring\b/i.test(Qe)||/\bI'?m hiring\b/i.test(Qe)||/\bWe are hiring\b/i.test(Qe);return{name:J,title:O,location:K,currentCompany:ee,currentSchool:T,connectionDegree:Ie,hasVerifiedBadge:_,photoUrl:V,connectionsLevel:le,mutualConnectionsCount:bt,followers:Bn,openToWork:Ir,hiring:Dr,about:Pn,topSkills:qn,availableSections:_r}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,m=null,g=null,h=null,y=null,k=null;if(o||r||s||i||c||a){let w=await Promise.resolve().then(()=>(ir(),rr));o&&(p=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(m=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),s&&(g=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),i&&(h=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),c&&(y=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),a&&(k=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${k.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...m!==null&&{featured:m},...g!==null&&{education:g},...h!==null&&{skillsFull:h},...y!==null&&{recommendations:y},...k!==null&&{certifications:k}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await C(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function Ae(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',s=f=>f&&!f.closest(r),i=f=>Array.from(document.querySelectorAll(f)).filter(s),c=i('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=i('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=i('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return c.length>0?{status:"pending",debug:u}:a&&!l?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await C(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function wt(e){let t=null,n=await e.evaluate(()=>{let l=document.querySelector("h1")?.textContent?.trim();if(l&&!l.includes("notification"))return l;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(l=u.textContent?.trim(),l&&!l.includes("notification")))return l;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let l=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});l.count>0&&console.log(` S0: ${l.count} custom-invite links: ${JSON.stringify(l.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=f.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let g of d){let h=g.getBoundingClientRect();if(h.width===0||h.height===0||g.closest(m))continue;if((g.getAttribute("aria-label")||"").toLowerCase().includes(p))return g}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let l=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${l}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(h=>{let y=h.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(h=>h.getAttribute("aria-label")?.slice(0,50))},l);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',g=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of p){if(h.closest(m))continue;let y=h.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&g.test(y))return h}return null},l);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,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 l=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();l.includes("invite")&&!l.includes(u)&&(console.log(` Skipping primary button: wrong person (${l})`),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 l of o){let u=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),m=f.className.includes("sticky-header")||f.className.includes("sticky"),g=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(f.getAttribute("aria-label")||"").toLowerCase(),y=h.includes("invite"),k=d?h.includes(d):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:g,hasInvite:y,matchesName:k,ariaLabel:h}},l,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}s=l;break}}for(let l of o)l!==s&&await l.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 i=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let l of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),p=d.width>0&&d.height>0,m=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:d.top}},l);if(u.isVisible&&!u.isInStickyHeader){i=l,console.log(" Found More button by ID pattern (main)");break}}for(let l of c)l!==i&&await l.dispose().catch(()=>{});if(!i&&c.length>0&&(i=c[c.length-1],console.log(" Found More button by ID pattern (last)")),i||(i=await e.$('button[aria-label="More actions"]'),i&&console.log(" Found More button by aria-label")),!i){let l=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),g=p.getAttribute("aria-label")||"",h=p.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let p=0;p<8&&d;p++){for(let m of d.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==f)return m;d=d.parentElement}return null});i=l?.asElement?.()||null,i||await l?.dispose?.().catch(()=>{}),i&&console.log(" Found More button by text (near profile actions)")}if(i)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),i),await C(500),await e.evaluate(d=>d.click(),i),await C(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let g=m.querySelector('a[href*="custom-invite"]');if(g)return g;for(let h of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of d)for(let g of m.querySelectorAll('[role="menuitem"], a, div')){let h=g.innerText?.trim();h&&h.length<40&&p.push(h)}return[...new Set(p)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(l){console.log(" More dropdown click failed:",l.message),await e.keyboard.press("Escape")}let a=await e.evaluateHandle(l=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(l||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let p=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(p))continue;let m=d.getBoundingClientRect();if(!(m.width===0||m.height===0)){if(p.includes("invite")){if(f&&p.includes(f))return d;continue}if(p==="connect")return d}}return null},n||"");return t=a?.asElement?.()||null,t||await a?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Rn(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await C(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),s=n.tag==="DIV",i=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(i))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(i.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!i.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await C(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await C(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await C(3e3)):(await e.evaluate(u=>u.click(),t),await C(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),l=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${l}`:` \u26A0 No modal after connect click \u2014 ${l}`),"success"}async function zs(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 C(1500);let n=await wt(e);if(n){await e.evaluate(r=>r.click(),n),await C(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await We(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function We(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(i=>{let c=a=>!!(a&&a.querySelector(i));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let i of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(i.innerText||""))return!0;return!1}),s=async()=>{let i=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(i)return i;let c=await e.evaluateHandle(a=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(a)||null,n);return i=c?.asElement?.()||null,i||await c?.dispose?.().catch(()=>{}),i};for(let i=0;i<2;i++){try{await t.evaluate(c=>c.click())}catch{}if(await C(3e3),await r())return!1;if(await o())return!0;if(i===0){let c=await s();if(!c)return await o();t=c,await C(600)}}return await o()}async function Tn(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:s=!1}=n;if(!r){let c=ot();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let i=await Qs(e,t,n);return i.connectionSent&&!s&&eo(t,o),i}async function Qs(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:s=!0,skipIfConnected:i=!0,excludeLocations:c=[]}=n,a={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
241
|
-
--- Connecting: ${l} ---`),c.length>0){let y=H()[t]?.location;if(Pt(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),a.reason="excluded_location",a.profileInfo={location:y},a}try{await Pe(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(y){if(y.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),a.reason="session_expired",a.fatal=!0,a;throw y}if(await C(2e3),await xe(e)&&(console.log(" Dismissed Premium overlay"),await C(2e3),await sr(e,t),await C(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:k}=await Promise.resolve().then(()=>(ln(),$o)),{recordDiscoveredEdges:A}=await Promise.resolve().then(()=>(Nt(),Io)),{detectCategoryFromTitle:w}=await en().then(()=>go),{detectSectors:S}=await Promise.resolve().then(()=>(bn(),Mo)),x=k(t)||t,b=await y(e,{seedUrl:x}),D=b.map($=>{let R=$.headline?w($.headline):null;return{url:$.url,seedUrl:x,block:$.block,rank:$.rank,name:$.name,headline:$.headline,categories:R?[R]:[],sectors:S($.headline||"")}});A(D),b.length&&console.log(` \xB7 discovery: harvested ${b.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}a.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=_=>{let F=(_||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(F)},A={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return A;let S=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],x=Array.from(w.querySelectorAll("h2")),b=S.find(_=>{let F=_.textContent&&_.textContent.trim();return F&&F.length>1&&F.length<100&&!y.has(F)&&F!=="0 notifications"}),D=b?b.textContent.trim():null,$=b?b.parentElement:null;for(;$&&$!==w&&!Array.from($.children).filter(V=>V.tagName==="P").some(V=>{let P=V.textContent&&V.textContent.trim();return P&&P.length>5&&!k(P)});)$=$.parentElement;let R=null,Y=null,J=null;if($&&$!==w){let _=Array.from($.children),F=_.filter(P=>P.tagName==="P").filter(P=>{let le=P.textContent&&P.textContent.trim();return le&&le.length>5&&!k(le)});F[0]&&(R=F[0].textContent.trim()),F[1]&&(Y=F[1].textContent.trim());let V=_.filter(P=>P.tagName==="DIV");for(let P=V.length-1;P>=0;P--){let le=V[P].textContent&&V[P].textContent.trim();if(le&&!(D&&le.startsWith(D))&&(J=le.split(/[·•]/)[0].trim(),J))break}}let M=null;if($){let _=$.querySelectorAll("p, span, div");for(let F of _){let V=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(V==="1st"||V==="2nd"||V==="3rd"){M=V;break}}}let O=null,ee=x.find(_=>_.textContent&&_.textContent.trim()==="About");if(ee){let _=ee.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;_&&(O=(_.textContent||"").trim().replace(/^About\s*/,"").trim()||null,O&&(O=O.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),K=T&&T.src||null,Ie=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:D,title:R,location:J,about:O,company:Y,connectionDegree:M,connectionsCount:null,mutualConnections:null,photoUrl:K,hasVerifiedBadge:Ie}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(a.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let y=a.profileInfo?.location,k=H()[t]?.location,A=y||k;if(Pt(A,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${A}`),a.reason="excluded_location",a;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Ae(e,{detail:!0})).status==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),a.reason="pending",a;await xe(e);let d=await wt(e);if(d||await xe(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await C(2e3),d=await wt(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),a.reason="connected",a;if(!d){let y=await Ae(e,{detail:!0});return i&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),a.reason="connected",a):(console.log(" \u2717 Connect not found"),a.reason="button_not_found",a)}a.method=d.method;let p=await Rn(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),a.reason="wrong_target",a;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(4e3);let y=await Ae(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await xe(e),await C(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),k),await C(500),await k.click().catch(()=>e.evaluate(w=>w.click(),k)),await C(2e3);let A=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(A){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(x=>x.click(),A),await C(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(3e3),a.reason="premium_required",a;if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.method="more_dropdown",a.withCustomMessage=!1,a;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await C(500),a.reason="premium_required",a}catch(A){return console.log(" More dropdown failed:",A.message),await e.keyboard.press("Escape").catch(()=>{}),a.reason="premium_required",a}else return console.log(" \u2717 No More button found \u2014 Premium required"),a.reason="premium_required",a}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let k of y){let A=k.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!A)continue;let w=(A.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(w)||A.querySelector('input[type="email"], input[name="email"]'))return!0;let S=A.querySelector('button[aria-label="Send without a note"]');if(S&&(S.disabled||S.getAttribute("aria-disabled")==="true"||(S.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await C(500),a.reason="email_required",a}let g=await e.$('button[aria-label="Add a note"]'),h=await e.$('button[aria-label="Send without a note"]');if(!g&&!h){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let A=k.querySelector('button[aria-label="Add a note"]'),w=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!A,sendWithout:!!w}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));g=k?.asElement?.()||null,g||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"]'));h=k?.asElement?.()||null,h||await k.dispose().catch(()=>{})}}if(r)if(g&&o){if(console.log(" Adding personalized note..."),await g.click(),await C(1500),await e.$("div.modal-upsell")){let A=await zs(e);return a.success=A,a.connectionSent=A,a.reason=A?"sent_without_note_upsell":"upsell_failed",a.withCustomMessage=!1,a}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let A=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=o.replace("{name}",A);await k.type(w,{delay:20}),await C(500);let S=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(S)return await We(e,S)?(console.log(" \u2713 Connection sent (with note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_with_note",a.withCustomMessage=!0,a.messageSent=w,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{if(h)return console.log(" Sending without note..."),await We(e,h)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a);if(g&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await We(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{console.log(" Sending without note (custom messages disabled)...");let y=h;if(y)return await We(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(4e3)),await xe(e),await C(500);let k=await e.$$('button[id*="profile-overflow-action"]'),A=null;for(let w of k){let S=await e.evaluate(x=>{let b=x.getBoundingClientRect();return{visible:b.width>0&&b.height>0,inSticky:!!x.closest('.sticky-header, [class*="sticky"]')}},w);if(S.visible&&!S.inSticky){A=w;break}}!A&&k.length>0&&(A=k[k.length-1]);for(let w of k)w!==A&&await w.dispose().catch(()=>{});if(A)try{await e.evaluate(S=>S.scrollIntoView({behavior:"smooth",block:"center"}),A),await C(500),await A.click().catch(()=>e.evaluate(S=>S.click(),A)),await C(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(w){console.log(" Found Connect in More dropdown, clicking..."),a.method="more_dropdown",await e.evaluate(D=>D.click(),w),await C(3e3);let S=e.url();if(S.includes("/premium/")||S.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(3e3),await Ae(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(a.reason="premium_required",a);if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;let b=await e.$('button[aria-label="Send without a note"]');if(b)return console.log(" Modal appeared via More dropdown, sending without note..."),await We(e,b)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),a.reason="modal_failed",a);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),a.reason="modal_failed",a}catch(l){console.error(` \u2717 Error: ${l.message}`),a.reason="error",a.error=l.message;let u=l.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return a.fatal=!0,a;try{await e.goto("about:blank",{timeout:1e4}),await C(1e3)}catch{a.fatal=!0}return a}}async function ar(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:s=20,viewOnly:i=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:a=null,excludeLocations:l=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
242
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${i?"View Only":`Connect (max ${s})`}`),i||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!i){let p=
|
|
240
|
+
`});var fr={};z(fr,{clickConnectButton:()=>Dn,default:()=>ra,detectConnectionStatus:()=>xe,findConnectButton:()=>wt,runFunnel:()=>dr,sendConnectionRequest:()=>Tn,shouldExcludeLocation:()=>Mt,viewProfile:()=>Rn});async function ur(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: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Mt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Rn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:c=!1,extractCertifications:a=!1}=n;try{await Me(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await C(1500),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await C(1500),await ur(e,t));let u=0;for(let w=0;w<2;w++){let S=await e.evaluate(()=>document.body.scrollHeight);for(let b=1;b<=6;b++)await e.evaluate(R=>window.scrollTo(0,R),S*b/6),await C(900);let A=await e.evaluate(()=>document.body.scrollHeight);if(A===u)break;u=A}await C(800);let f=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(f=w.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),S=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=E=>{let I=(E||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},b={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},R=document.querySelector("main");if(!R)return b;let $=[...Array.from(R.querySelectorAll("h1")),...Array.from(R.querySelectorAll("h2"))],D=Array.from(R.querySelectorAll("h2")),Y=$.find(E=>{let I=E.textContent&&E.textContent.trim(),N=(I||"").replace(/\s*\(\d+\)$/,"").trim();return I&&I.length>1&&I.length<100&&!w.has(N)&&!S.has(N)}),J=Y?Y.textContent.trim():null,P=Y?Y.parentElement:null;for(;P&&P!==R&&!Array.from(P.children).filter(I=>I.tagName==="P").some(I=>{let N=I.textContent&&I.textContent.trim();return N&&N.length>5&&!A(N)});)P=P.parentElement;let j=null,ee=null,T=null,K=null;if(P&&P!==R){let E=Array.from(P.children).filter(N=>N.tagName==="P").filter(N=>{let be=N.textContent&&N.textContent.trim();return be&&be.length>5&&!A(be)});if(E[0]&&(j=E[0].textContent.trim()),E[1]){let N=E[1].textContent.trim().split(/\s*[·•]\s*/);ee=N[0]||null,N.length>1&&(T=N.slice(1).join(" \xB7 "))}let I=Array.from(P.children).filter(N=>N.tagName==="DIV");for(let N=I.length-1;N>=0;N--){let be=I[N].textContent&&I[N].textContent.trim();if(be&&!(J&&be.startsWith(J))&&(K=be.split(/[·•]/)[0].trim(),K))break}}let Ie=null;if(P){let E=P.querySelectorAll("p, span, div");for(let I of E){let N=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){Ie=N;break}}}let _=!!R.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),H=L&&L.src||null,M=R.textContent||"",le=null,Ln=M.match(/(\d+\+?)\s+connections\b/i);Ln&&(le=Ln[1]+" connections");let bt=null,Fn=M.match(/(\d+)\s+mutual connection/i),Pn=M.match(/and\s+(\d+)\s+other mutual/i),Dr=M.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Fn?bt=parseInt(Fn[1],10):Pn?bt=2+parseInt(Pn[1],10):Dr&&(bt=2);let Mn=null,qn=null,Un=D.find(E=>E.textContent&&E.textContent.trim()==="About");if(Un){let E=Un.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let I=(E.textContent||"").trim();I=I.replace(/^About\s*/,"").trim();let N=I.match(/Top skills\s*(.+?)$/i);if(N){let Ht=N[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(jr=>jr.trim()).filter(Boolean);Ht.length>0&&Ht.length<10&&(qn=Ht)}I=I.split(/\n?…\s*more/i)[0].trim(),I=I.split(/\n?\.\.\.\s*more/i)[0].trim(),I=I.split(/\bTop skills\b/i)[0].trim(),I=I.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Mn=I||null}}let Bn=null,Jn=D.find(E=>E.textContent&&E.textContent.trim()==="Activity");if(Jn){let E=Jn.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let I=(E.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);I&&(Bn=parseInt(I[1].replace(/,/g,""),10))}}let Tr=[...new Set(D.map(E=>(E.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(E=>E&&E.length>1&&E.length<60&&E!==J).filter(E=>w.has(E)))],Qe=document.body.textContent||"",Nr=/#OpenToWork\b/i.test(Qe)||/\bOpen to work\b/.test(Qe),Or=/#Hiring\b/i.test(Qe)||/\bI'?m hiring\b/i.test(Qe)||/\bWe are hiring\b/i.test(Qe);return{name:J,title:j,location:K,currentCompany:ee,currentSchool:T,connectionDegree:Ie,hasVerifiedBadge:_,photoUrl:H,connectionsLevel:le,mutualConnectionsCount:bt,followers:Bn,openToWork:Nr,hiring:Or,about:Mn,topSkills:qn,availableSections:Tr}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,m=null,g=null,h=null,y=null,k=null;if(o||r||s||i||c||a){let w=await Promise.resolve().then(()=>(cr(),lr));o&&(p=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(m=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),s&&(g=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),i&&(h=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),c&&(y=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),a&&(k=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${k.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...m!==null&&{featured:m},...g!==null&&{education:g},...h!==null&&{skillsFull:h},...y!==null&&{recommendations:y},...k!==null&&{certifications:k}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await C(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function xe(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',s=f=>f&&!f.closest(r),i=f=>Array.from(document.querySelectorAll(f)).filter(s),c=i('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=i('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=i('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return c.length>0?{status:"pending",debug:u}:a&&!l?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await C(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function wt(e){let t=null,n=await e.evaluate(()=>{let l=document.querySelector("h1")?.textContent?.trim();if(l&&!l.includes("notification"))return l;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(l=u.textContent?.trim(),l&&!l.includes("notification")))return l;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let l=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});l.count>0&&console.log(` S0: ${l.count} custom-invite links: ${JSON.stringify(l.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=f.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let g of d){let h=g.getBoundingClientRect();if(h.width===0||h.height===0||g.closest(m))continue;if((g.getAttribute("aria-label")||"").toLowerCase().includes(p))return g}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let l=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${l}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(h=>{let y=h.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(h=>h.getAttribute("aria-label")?.slice(0,50))},l);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',g=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of p){if(h.closest(m))continue;let y=h.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&g.test(y))return h}return null},l);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,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 l=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();l.includes("invite")&&!l.includes(u)&&(console.log(` Skipping primary button: wrong person (${l})`),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 l of o){let u=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),m=f.className.includes("sticky-header")||f.className.includes("sticky"),g=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(f.getAttribute("aria-label")||"").toLowerCase(),y=h.includes("invite"),k=d?h.includes(d):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:g,hasInvite:y,matchesName:k,ariaLabel:h}},l,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}s=l;break}}for(let l of o)l!==s&&await l.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 i=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let l of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),p=d.width>0&&d.height>0,m=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:d.top}},l);if(u.isVisible&&!u.isInStickyHeader){i=l,console.log(" Found More button by ID pattern (main)");break}}for(let l of c)l!==i&&await l.dispose().catch(()=>{});if(!i&&c.length>0&&(i=c[c.length-1],console.log(" Found More button by ID pattern (last)")),i||(i=await e.$('button[aria-label="More actions"]'),i&&console.log(" Found More button by aria-label")),!i){let l=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),g=p.getAttribute("aria-label")||"",h=p.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let p=0;p<8&&d;p++){for(let m of d.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==f)return m;d=d.parentElement}return null});i=l?.asElement?.()||null,i||await l?.dispose?.().catch(()=>{}),i&&console.log(" Found More button by text (near profile actions)")}if(i)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),i),await C(500),await e.evaluate(d=>d.click(),i),await C(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let g=m.querySelector('a[href*="custom-invite"]');if(g)return g;for(let h of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of d)for(let g of m.querySelectorAll('[role="menuitem"], a, div')){let h=g.innerText?.trim();h&&h.length<40&&p.push(h)}return[...new Set(p)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(l){console.log(" More dropdown click failed:",l.message),await e.keyboard.press("Escape")}let a=await e.evaluateHandle(l=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(l||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let p=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(p))continue;let m=d.getBoundingClientRect();if(!(m.width===0||m.height===0)){if(p.includes("invite")){if(f&&p.includes(f))return d;continue}if(p==="connect")return d}}return null},n||"");return t=a?.asElement?.()||null,t||await a?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Dn(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await C(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),s=n.tag==="DIV",i=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(i))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(i.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!i.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await C(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await C(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await C(3e3)):(await e.evaluate(u=>u.click(),t),await C(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),l=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${l}`:` \u26A0 No modal after connect click \u2014 ${l}`),"success"}async function na(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 C(1500);let n=await wt(e);if(n){await e.evaluate(r=>r.click(),n),await C(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await We(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function We(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(i=>{let c=a=>!!(a&&a.querySelector(i));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let i of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(i.innerText||""))return!0;return!1}),s=async()=>{let i=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(i)return i;let c=await e.evaluateHandle(a=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(a)||null,n);return i=c?.asElement?.()||null,i||await c?.dispose?.().catch(()=>{}),i};for(let i=0;i<2;i++){try{await t.evaluate(c=>c.click())}catch{}if(await C(3e3),await r())return!1;if(await o())return!0;if(i===0){let c=await s();if(!c)return await o();t=c,await C(600)}}return await o()}async function Tn(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:s=!1}=n;if(!r){let c=ot();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let i=await oa(e,t,n);return i.connectionSent&&!s&&ro(t,o),i}async function oa(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:s=!0,skipIfConnected:i=!0,excludeLocations:c=[]}=n,a={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
241
|
+
--- Connecting: ${l} ---`),c.length>0){let y=W()[t]?.location;if(Mt(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),a.reason="excluded_location",a.profileInfo={location:y},a}try{await Me(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(y){if(y.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),a.reason="session_expired",a.fatal=!0,a;throw y}if(await C(2e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await C(2e3),await ur(e,t),await C(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:k}=await Promise.resolve().then(()=>(ln(),Eo)),{recordDiscoveredEdges:x}=await Promise.resolve().then(()=>(Nt(),No)),{detectCategoryFromTitle:w}=await en().then(()=>So),{detectSectors:S}=await Promise.resolve().then(()=>(bn(),Bo)),A=k(t)||t,b=await y(e,{seedUrl:A}),R=b.map($=>{let D=$.headline?w($.headline):null;return{url:$.url,seedUrl:A,block:$.block,rank:$.rank,name:$.name,headline:$.headline,categories:D?[D]:[],sectors:S($.headline||"")}});x(R),b.length&&console.log(` \xB7 discovery: harvested ${b.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}a.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=_=>{let L=(_||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},x={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return x;let S=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],A=Array.from(w.querySelectorAll("h2")),b=S.find(_=>{let L=_.textContent&&_.textContent.trim();return L&&L.length>1&&L.length<100&&!y.has(L)&&L!=="0 notifications"}),R=b?b.textContent.trim():null,$=b?b.parentElement:null;for(;$&&$!==w&&!Array.from($.children).filter(H=>H.tagName==="P").some(H=>{let M=H.textContent&&H.textContent.trim();return M&&M.length>5&&!k(M)});)$=$.parentElement;let D=null,Y=null,J=null;if($&&$!==w){let _=Array.from($.children),L=_.filter(M=>M.tagName==="P").filter(M=>{let le=M.textContent&&M.textContent.trim();return le&&le.length>5&&!k(le)});L[0]&&(D=L[0].textContent.trim()),L[1]&&(Y=L[1].textContent.trim());let H=_.filter(M=>M.tagName==="DIV");for(let M=H.length-1;M>=0;M--){let le=H[M].textContent&&H[M].textContent.trim();if(le&&!(R&&le.startsWith(R))&&(J=le.split(/[·•]/)[0].trim(),J))break}}let P=null;if($){let _=$.querySelectorAll("p, span, div");for(let L of _){let H=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(H==="1st"||H==="2nd"||H==="3rd"){P=H;break}}}let j=null,ee=A.find(_=>_.textContent&&_.textContent.trim()==="About");if(ee){let _=ee.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;_&&(j=(_.textContent||"").trim().replace(/^About\s*/,"").trim()||null,j&&(j=j.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),K=T&&T.src||null,Ie=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:D,location:J,about:j,company:Y,connectionDegree:P,connectionsCount:null,mutualConnections:null,photoUrl:K,hasVerifiedBadge:Ie}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(a.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let y=a.profileInfo?.location,k=W()[t]?.location,x=y||k;if(Mt(x,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${x}`),a.reason="excluded_location",a;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await xe(e,{detail:!0})).status==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),a.reason="pending",a;await Ae(e);let d=await wt(e);if(d||await Ae(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await C(2e3),d=await wt(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),a.reason="connected",a;if(!d){let y=await xe(e,{detail:!0});return i&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),a.reason="connected",a):(console.log(" \u2717 Connect not found"),a.reason="button_not_found",a)}a.method=d.method;let p=await Dn(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),a.reason="wrong_target",a;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(4e3);let y=await xe(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await Ae(e),await C(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),k),await C(500),await k.click().catch(()=>e.evaluate(w=>w.click(),k)),await C(2e3);let x=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(x){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(A=>A.click(),x),await C(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(3e3),a.reason="premium_required",a;if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.method="more_dropdown",a.withCustomMessage=!1,a;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await C(500),a.reason="premium_required",a}catch(x){return console.log(" More dropdown failed:",x.message),await e.keyboard.press("Escape").catch(()=>{}),a.reason="premium_required",a}else return console.log(" \u2717 No More button found \u2014 Premium required"),a.reason="premium_required",a}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let k of y){let x=k.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!x)continue;let w=(x.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(w)||x.querySelector('input[type="email"], input[name="email"]'))return!0;let S=x.querySelector('button[aria-label="Send without a note"]');if(S&&(S.disabled||S.getAttribute("aria-disabled")==="true"||(S.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await C(500),a.reason="email_required",a}let g=await e.$('button[aria-label="Add a note"]'),h=await e.$('button[aria-label="Send without a note"]');if(!g&&!h){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let x=k.querySelector('button[aria-label="Add a note"]'),w=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!w}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));g=k?.asElement?.()||null,g||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"]'));h=k?.asElement?.()||null,h||await k.dispose().catch(()=>{})}}if(r)if(g&&o){if(console.log(" Adding personalized note..."),await g.click(),await C(1500),await e.$("div.modal-upsell")){let x=await na(e);return a.success=x,a.connectionSent=x,a.reason=x?"sent_without_note_upsell":"upsell_failed",a.withCustomMessage=!1,a}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=o.replace("{name}",x);await k.type(w,{delay:20}),await C(500);let S=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(S)return await We(e,S)?(console.log(" \u2713 Connection sent (with note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_with_note",a.withCustomMessage=!0,a.messageSent=w,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{if(h)return console.log(" Sending without note..."),await We(e,h)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a);if(g&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await We(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{console.log(" Sending without note (custom messages disabled)...");let y=h;if(y)return await We(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(4e3)),await Ae(e),await C(500);let k=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let w of k){let S=await e.evaluate(A=>{let b=A.getBoundingClientRect();return{visible:b.width>0&&b.height>0,inSticky:!!A.closest('.sticky-header, [class*="sticky"]')}},w);if(S.visible&&!S.inSticky){x=w;break}}!x&&k.length>0&&(x=k[k.length-1]);for(let w of k)w!==x&&await w.dispose().catch(()=>{});if(x)try{await e.evaluate(S=>S.scrollIntoView({behavior:"smooth",block:"center"}),x),await C(500),await x.click().catch(()=>e.evaluate(S=>S.click(),x)),await C(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(w){console.log(" Found Connect in More dropdown, clicking..."),a.method="more_dropdown",await e.evaluate(R=>R.click(),w),await C(3e3);let S=e.url();if(S.includes("/premium/")||S.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await C(3e3),await xe(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(a.reason="premium_required",a);if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;let b=await e.$('button[aria-label="Send without a note"]');if(b)return console.log(" Modal appeared via More dropdown, sending without note..."),await We(e,b)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),a.reason="modal_failed",a);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),a.reason="modal_failed",a}catch(l){console.error(` \u2717 Error: ${l.message}`),a.reason="error",a.error=l.message;let u=l.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return a.fatal=!0,a;try{await e.goto("about:blank",{timeout:1e4}),await C(1e3)}catch{a.fatal=!0}return a}}async function dr(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:s=20,viewOnly:i=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:a=null,excludeLocations:l=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
242
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${i?"View Only":`Connect (max ${s})`}`),i||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!i){let p=Re();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let d=0;for(let p=0;p<t.length;p++){let m=t[p];try{if(e.isClosed()){console.log(`
|
|
243
243
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
244
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let g=
|
|
244
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let g=no(m.profileUrl);if(g==="pending"||g==="connected"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${g})`),g==="pending"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,a&&await a(m,f,{success:!1,reason:g,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl}`);let h=null;if(i){let y=await Rn(e,m.profileUrl);y?(kt(m.profileUrl,{...y,source:u}),f.viewed++,h={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,h={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let y=ot();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(h=await Tn(e,m.profileUrl,{message:o,useCustomMessage:r,excludeLocations:l,source:u,skipQuotaGate:!0}),h.success)f.connectionsSent++;else switch(h.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(h?.fatal){console.log(`
|
|
245
245
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(h?.reason==="error"){if(d++,d>=3){console.log(`
|
|
246
|
-
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(h&&h.reason&&(Ct(m.profileUrl,h.reason,{method:h.method,messageSent:h.messageSent,profileInfo:h.profileInfo}),h.resolvedUrl&&
|
|
247
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!i){let p=
|
|
246
|
+
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(h&&h.reason&&(Ct(m.profileUrl,h.reason,{method:h.method,messageSent:h.messageSent,profileInfo:h.profileInfo}),h.resolvedUrl&&At(m.profileUrl,h.resolvedUrl),to(m.profileUrl,{source:u||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:h.reason})),a&&await a(m,f,h),p<t.length-1){let y=c+Math.random()*2e3;await C(y)}}if(console.log(`
|
|
247
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!i){let p=Re();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return f}var ra,pr=V(async()=>{Pt();await De();ra={viewProfile:Rn,detectConnectionStatus:xe,findConnectButton:wt,clickConnectButton:Dn,sendConnectionRequest:Tn,runFunnel:dr,shouldExcludeLocation:Mt}});import{createGraphClient as ia,resolveToken as sa}from"@ilivemylife/graph-sdk";import{config as aa}from"dotenv";var mr,hr,gr=V(()=>{aa();mr=sa()||process.env.TOKEN;mr||(console.error(`
|
|
248
248
|
[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.
|
|
249
249
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
250
250
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
251
|
-
`),process.exit(1));
|
|
251
|
+
`),process.exit(1));hr=ia({token:mr})});import"dotenv/config";function la(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 ca({scriptName:e,mode:t,status:n,error:o,duration:r}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${la(r)}`:"",a=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",l=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${l} \u2014 ${a} \u2014 ${i}${c}`}async function yr({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let a=`**${ca({scriptName:e,mode:t,status:n,error:r,duration:s})}**
|
|
252
252
|
|
|
253
253
|
${o.join(`
|
|
254
|
-
`)}`;try{await
|
|
255
|
-
`)}var ia,sa,Nn,jn,br=W(()=>{mr();ia=ra(import.meta.url),sa=Ee.dirname(Ee.dirname(ia)),Nn=process.env.DATA_DIR?Ee.resolve(process.env.DATA_DIR,"collected-profiles"):Ee.join(sa,"collected-profiles"),jn=Ee.join(Nn,"run-log.json")});import*as Bt from"fs";import*as Ye from"path";await St();await Re();import"dotenv/config";import*as At from"fs";import*as ke from"path";import{fileURLToPath as zr}from"url";var Qr=zr(import.meta.url),Xr=ke.dirname(ke.dirname(Qr)),Kt=process.env.DATA_DIR?ke.resolve(process.env.DATA_DIR,"collected-profiles"):ke.join(Xr,"collected-profiles"),oo=ke.join(Kt,"connect-queue.json"),Zr=1,Te=300,Et=["queued","approved","sent","skipped","failed"],ce=["high","normal","low"],no={high:0,normal:1,low:2};function ei(){At.existsSync(Kt)||At.mkdirSync(Kt,{recursive:!0})}function zt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=Te?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:ce.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 Q(){let e=tt(oo,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(zt).filter(n=>n.url):[]}function ue(e){ei(),et(oo,{version:Zr,entries:e.map(zt)})}function he(e){return U(e)||(e||"").trim().toLowerCase()}function rt(e,t){let n=he(t);return e.find(o=>he(o.url)===n)||null}function it(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:s=()=>!1,nowIso:i}=n,c={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},a=new Set(e.map(l=>he(l.url)));for(let l of t){let u=l?.url;if(!u){c.skippedNoUrl++;continue}let f=he(u);if(a.has(f)){c.skippedDup++;continue}if(s(u)){c.skippedEngaged++;continue}let d=typeof l.note=="string"?l.note.trim():"";d.length>Te&&c.notesTooLong++;let p=d.length>0&&d.length<=Te;e.push(zt({url:u,tag:l.tag||o,priority:l.priority||r,withNote:p,note:p?d:null,status:"queued",addedAt:i||null})),a.add(f),c.added++}return c}function ro(e){return[...e].sort((t,n)=>{let o=(no[t.priority]??1)-(no[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function ge(e,t){return e.filter(n=>n.status===t)}await Re();await en();import"dotenv/config";import*as v from"fs";import*as gn from"os";import*as j from"path";import{fileURLToPath as Zi}from"url";var on={};z(on,{NAME:()=>hi,VERSION:()=>mi,up:()=>wi});import*as ne from"fs";import*as _t from"path";var mi=1,hi="normalize-jobs-and-questions",gi=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],yi=50;function tn(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function nn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(r){try{ne.unlinkSync(o)}catch{}throw r}try{ne.renameSync(o,e)}catch(r){try{ne.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 wi(e,t){let n=_t.join(e,"jobs.json"),o=_t.join(t,"scouted-jobs.json"),r=_t.join(e,"application-questions.json"),s=tn(n)||{},i=tn(o)||{},c=0,a=[];for(let u of Object.keys(s)){if(!i[u])continue;let f=i[u],d=s[u];for(let p of gi)f[p]!=null&&d[p]==null&&(d[p]=f[p]);a.push(u),c++}c>0?(nn(n,s),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=tn(r);if(l&&Array.isArray(l.applications)){let u={},f=0;for(let d of l.applications){let p=d.jobId||"unknown";u[p]||(u[p]={applications:[]});let m=(d.questions||[]).map(g=>{let h={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=yi?h.options=g.options:(h.optionsOmitted=!0,f++)),g.page&&(h.page=g.page),g.wasPreFilled&&(h.wasPreFilled=!0),g.wasRetry&&(h.wasRetry=!0),h});u[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||m.length,questions:m})}nn(r,u),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} 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(a.length>0){for(let u of a)delete i[u];nn(o,i),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var rn={};z(rn,{NAME:()=>Si,VERSION:()=>bi,up:()=>$i});import*as oe from"fs";import*as yo from"path";var bi=2,Si="reset-unread-flags";function ki(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function vi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(r){try{oe.unlinkSync(o)}catch{}throw r}try{oe.renameSync(o,e)}catch(r){try{oe.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 $i(e){let t=yo.join(e,"conversations.json"),n=ki(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}vi(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var sn={};z(sn,{NAME:()=>xi,VERSION:()=>Ci,up:()=>Di});import*as re from"fs";import*as wo from"path";var Ci=3,xi="recompute-last-message-by",Ai=new Set(["draft","confirmed","rejected","needs_review"]);function Ei(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function _i(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{re.writeFileSync(o,n)}catch(r){try{re.unlinkSync(o)}catch{}throw r}try{re.renameSync(o,e)}catch(r){try{re.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 Ii(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!Ai.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,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Di(e){let t=wo.join(e,"conversations.json"),n=Ei(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,i=0;for(let c of Object.keys(n)){let a=n[c];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,s++);let l=Array.isArray(a.messages)?a.messages:[],u=Ii(l,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&i++,a.lastMessageBy=u,a.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}_i(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} 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.")}var an={};z(an,{NAME:()=>Ti,VERSION:()=>Ri,up:()=>Fi});import*as ie from"fs";import*as bo from"path";var Ri=4,Ti="split-connection-timestamps",Ni=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ji(e){if(!ie.existsSync(e))return null;let t=ie.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Oi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ie.writeFileSync(o,n)}catch(r){try{ie.unlinkSync(o)}catch{}throw r}try{ie.renameSync(o,e)}catch(r){try{ie.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 Fi(e){let t=bo.join(e,"people.json"),n=ji(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,Ni.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Oi(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Re();Nt();var es=Zi(import.meta.url),ts=j.dirname(es),ns=j.dirname(j.dirname(ts));function os(e){return e&&(e==="~"?gn.homedir():e.startsWith("~/")||e.startsWith("~\\")?j.join(gn.homedir(),e.slice(2)):e)}var de=process.env.DATA_DIR?j.resolve(os(process.env.DATA_DIR)):ns,Le=j.join(de,"collected-profiles"),Me=j.join(de,"market-research"),X=j.join(de,".schema-version"),Do=[j.join(Le,".schema-version"),j.join(Me,".schema-version")],Ce=4,ye=[{version:1,module:on},{version:2,module:rn},{version:3,module:sn},{version:4,module:an}];(function(){ye.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ye){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=ye.length?ye[ye.length-1].version:0;if(n!==Ce)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${Ce}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ye.length;o++){let r=o+1;if(ye[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ye[o].version}`)}})();function jo(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
254
|
+
`)}`;try{await hr.addMessage(i,a)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var wr=V(()=>{gr()});var vr={};z(vr,{endRun:()=>ha,formatScriptStatus:()=>wa,getLastRun:()=>ya,getRunHistory:()=>ga,getTodayRunSummary:()=>Sr,startRun:()=>ma,timeAgo:()=>kr});import"dotenv/config";import*as ae from"fs";import*as Ee from"path";import{fileURLToPath as ua}from"url";function pa(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ae.writeFileSync(o,n);for(let r=0;r<3;r++)try{ae.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ge(){try{if(!ae.existsSync(On))return{runs:[]};let e=JSON.parse(ae.readFileSync(On,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function br(e){ae.existsSync(Nn)||ae.mkdirSync(Nn,{recursive:!0});try{pa(On,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ma(e,t="default"){let n=Ge();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.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(i=>new Date(i.timestamp).getTime()>s),br(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function ha(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=Ge(),c=i.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let a=i.runs.find(l=>l.script===e.script&&l.status==="running"&&l.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,r=a.duration)}br(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";yr({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}function ga(e=7){let t=Ge(),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 ya(e=null){let t=Ge(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function Sr(){let e=new Date().toISOString().slice(0,10),t=Ge(),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 kr(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 wa(){let e=["sync-all","messages","funnel","sync","apply"],t=Ge(),n=Sr(),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 i=t.runs.filter(g=>g.script===s),c=[...i].reverse().find(g=>g.status==="success"),a=i[i.length-1],l=c||a,u=l?kr(l.timestamp):"never",d=(l?Math.floor((Date.now()-new Date(l.timestamp).getTime())/864e5):1/0)>1?" \u26A0":l?.status==="error"?" \u2717":" \u2713",p="";if(l?.stats){let g=l.stats,h=Object.entries(g).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,k])=>`${k} ${y}`);h.length&&(p=` (${h.join(", ")})`)}let m=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${s.padEnd(14)} ${u.padEnd(16)}${m}${p}${d}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[s,i]of r){let c=[];i.success&&c.push(`${i.success} success`),i.error&&c.push(`${i.error} error`),i.interrupted&&c.push(`${i.interrupted} interrupted`),i.running&&c.push(`${i.running} running`),o.push(` Today: ${s} \xD7${i.total} (${c.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(`
|
|
255
|
+
`)}var da,fa,Nn,On,$r=V(()=>{wr();da=ua(import.meta.url),fa=Ee.dirname(Ee.dirname(da)),Nn=process.env.DATA_DIR?Ee.resolve(process.env.DATA_DIR,"collected-profiles"):Ee.join(fa,"collected-profiles"),On=Ee.join(Nn,"run-log.json")});import*as Bt from"fs";import*as Ye from"path";await St();await De();import"dotenv/config";import*as xt from"fs";import*as ke from"path";import{fileURLToPath as ni}from"url";var oi=ni(import.meta.url),ri=ke.dirname(ke.dirname(oi)),Kt=process.env.DATA_DIR?ke.resolve(process.env.DATA_DIR,"collected-profiles"):ke.join(ri,"collected-profiles"),ao=ke.join(Kt,"connect-queue.json"),ii=1,Te=300,Et=["queued","approved","sent","skipped","failed"],ce=["high","normal","low"],so={high:0,normal:1,low:2};function si(){xt.existsSync(Kt)||xt.mkdirSync(Kt,{recursive:!0})}function zt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=Te?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:ce.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 Q(){let e=tt(ao,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(zt).filter(n=>n.url):[]}function ue(e){si(),et(ao,{version:ii,entries:e.map(zt)})}function he(e){return U(e)||(e||"").trim().toLowerCase()}function rt(e,t){let n=he(t);return e.find(o=>he(o.url)===n)||null}function it(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:s=()=>!1,nowIso:i}=n,c={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},a=new Set(e.map(l=>he(l.url)));for(let l of t){let u=l?.url;if(!u){c.skippedNoUrl++;continue}let f=he(u);if(a.has(f)){c.skippedDup++;continue}if(s(u)){c.skippedEngaged++;continue}let d=typeof l.note=="string"?l.note.trim():"";d.length>Te&&c.notesTooLong++;let p=d.length>0&&d.length<=Te;e.push(zt({url:u,tag:l.tag||o,priority:l.priority||r,withNote:p,note:p?d:null,status:"queued",addedAt:i||null})),a.add(f),c.added++}return c}function lo(e){return[...e].sort((t,n)=>{let o=(so[t.priority]??1)-(so[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function ge(e,t){return e.filter(n=>n.status===t)}await De();await en();import"dotenv/config";import*as v from"fs";import*as gn from"os";import*as O from"path";import{fileURLToPath as is}from"url";var on={};z(on,{NAME:()=>ki,VERSION:()=>Si,up:()=>Ci});import*as ne from"fs";import*as _t from"path";var Si=1,ki="normalize-jobs-and-questions",vi=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],$i=50;function tn(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function nn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(r){try{ne.unlinkSync(o)}catch{}throw r}try{ne.renameSync(o,e)}catch(r){try{ne.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 Ci(e,t){let n=_t.join(e,"jobs.json"),o=_t.join(t,"scouted-jobs.json"),r=_t.join(e,"application-questions.json"),s=tn(n)||{},i=tn(o)||{},c=0,a=[];for(let u of Object.keys(s)){if(!i[u])continue;let f=i[u],d=s[u];for(let p of vi)f[p]!=null&&d[p]==null&&(d[p]=f[p]);a.push(u),c++}c>0?(nn(n,s),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=tn(r);if(l&&Array.isArray(l.applications)){let u={},f=0;for(let d of l.applications){let p=d.jobId||"unknown";u[p]||(u[p]={applications:[]});let m=(d.questions||[]).map(g=>{let h={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=$i?h.options=g.options:(h.optionsOmitted=!0,f++)),g.page&&(h.page=g.page),g.wasPreFilled&&(h.wasPreFilled=!0),g.wasRetry&&(h.wasRetry=!0),h});u[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||m.length,questions:m})}nn(r,u),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} 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(a.length>0){for(let u of a)delete i[u];nn(o,i),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var rn={};z(rn,{NAME:()=>xi,VERSION:()=>Ai,up:()=>Ii});import*as oe from"fs";import*as ko from"path";var Ai=2,xi="reset-unread-flags";function Ei(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function _i(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(r){try{oe.unlinkSync(o)}catch{}throw r}try{oe.renameSync(o,e)}catch(r){try{oe.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 Ii(e){let t=ko.join(e,"conversations.json"),n=Ei(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}_i(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var sn={};z(sn,{NAME:()=>Di,VERSION:()=>Ri,up:()=>Li});import*as re from"fs";import*as vo from"path";var Ri=3,Di="recompute-last-message-by",Ti=new Set(["draft","confirmed","rejected","needs_review"]);function Ni(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function Oi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{re.writeFileSync(o,n)}catch(r){try{re.unlinkSync(o)}catch{}throw r}try{re.renameSync(o,e)}catch(r){try{re.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 ji(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!Ti.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,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Li(e){let t=vo.join(e,"conversations.json"),n=Ni(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,i=0;for(let c of Object.keys(n)){let a=n[c];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,s++);let l=Array.isArray(a.messages)?a.messages:[],u=ji(l,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&i++,a.lastMessageBy=u,a.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}Oi(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} 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.")}var an={};z(an,{NAME:()=>Pi,VERSION:()=>Fi,up:()=>Bi});import*as ie from"fs";import*as $o from"path";var Fi=4,Pi="split-connection-timestamps",Mi=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function qi(e){if(!ie.existsSync(e))return null;let t=ie.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ui(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ie.writeFileSync(o,n)}catch(r){try{ie.unlinkSync(o)}catch{}throw r}try{ie.renameSync(o,e)}catch(r){try{ie.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 Bi(e){let t=$o.join(e,"people.json"),n=qi(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,Mi.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ui(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await De();Nt();var ss=is(import.meta.url),as=O.dirname(ss),ls=O.dirname(O.dirname(as));function cs(e){return e&&(e==="~"?gn.homedir():e.startsWith("~/")||e.startsWith("~\\")?O.join(gn.homedir(),e.slice(2)):e)}var de=process.env.DATA_DIR?O.resolve(cs(process.env.DATA_DIR)):ls,Fe=O.join(de,"collected-profiles"),Pe=O.join(de,"market-research"),X=O.join(de,".schema-version"),Oo=[O.join(Fe,".schema-version"),O.join(Pe,".schema-version")],Ce=4,ye=[{version:1,module:on},{version:2,module:rn},{version:3,module:sn},{version:4,module:an}];(function(){ye.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ye){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=ye.length?ye[ye.length-1].version:0;if(n!==Ce)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${Ce}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ye.length;o++){let r=o+1;if(ye[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ye[o].version}`)}})();function Po(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
256
256
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
257
257
|
`),process.exit(1));try{v.mkdirSync(de,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
258
258
|
[FATAL] Cannot create DATA_DIR (${de}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -260,68 +260,68 @@ ${o.join(`
|
|
|
260
260
|
[FATAL] DATA_DIR (${de}) is not accessible: ${t.message}
|
|
261
261
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
262
262
|
[FATAL] DATA_DIR (${de}) 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.
|
|
263
|
-
`),process.exit(1));for(let t of[
|
|
263
|
+
`),process.exit(1));for(let t of[Fe,Pe]){let n;try{n=v.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
264
264
|
[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.
|
|
265
|
-
`),process.exit(1))}}var
|
|
266
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
265
|
+
`),process.exit(1))}}var Le=O.join(de,".migration-lock");function us(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return v.writeFileSync(Le,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(v.readFileSync(Le,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,s=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(s=Date.now()-i)}o&&s<r&&(console.error(`
|
|
266
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Le}
|
|
267
267
|
`),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.
|
|
268
|
-
`),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=
|
|
268
|
+
`),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=Le+".tmp";try{return v.writeFileSync(n,e),v.renameSync(n,Le),!0}catch(o){try{v.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function yn(){try{if(JSON.parse(v.readFileSync(Le,"utf-8")).pid!==process.pid)return;v.unlinkSync(Le)}catch{}}var jo=!1;function ds(){if(jo)return;jo=!0;let e=()=>{try{yn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function fs(){if(v.existsSync(X))return;let e=[],t=[];for(let s of Oo)if(v.existsSync(s))try{e.push({file:s,schema:Ot(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
|
|
269
269
|
[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(`
|
|
270
270
|
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.
|
|
271
271
|
`),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
|
|
272
272
|
[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.
|
|
273
|
-
`),process.exit(1)}let o=e[0].schema,r=X+".tmp";try{v.writeFileSync(r,JSON.stringify(o,null,2)),v.renameSync(r,X)}catch(s){try{v.unlinkSync(r)}catch{}throw s}for(let s of
|
|
273
|
+
`),process.exit(1)}let o=e[0].schema,r=X+".tmp";try{v.writeFileSync(r,JSON.stringify(o,null,2)),v.renameSync(r,X)}catch(s){try{v.unlinkSync(r)}catch{}throw s}for(let s of Oo)if(v.existsSync(s))try{v.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${X}`)}function ps(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=v.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Lo(){if(fs(),!v.existsSync(X))return{version:0,migrations:[]};let e;try{e=Ot(X)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
274
274
|
[FATAL] ${X} 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.
|
|
275
|
-
`),process.exit(1)}let t=
|
|
275
|
+
`),process.exit(1)}let t=ps(e);return t===null&&(console.error(`
|
|
276
276
|
[FATAL] ${X} 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.
|
|
277
|
-
`),process.exit(1)),t}function
|
|
277
|
+
`),process.exit(1)),t}function Mo(e){try{v.chmodSync(e,384)}catch{}}function ms(e){if(Po(),v.existsSync(X))try{if(v.lstatSync(X).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${X}. 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=X+".tmp";try{v.writeFileSync(t,JSON.stringify(e,null,2)),Mo(t),v.renameSync(t,X)}catch(n){try{v.unlinkSync(t)}catch{}throw n}}function Fo(e,t){if(!v.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=v.readdirSync(e).filter(c=>{let a=c.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return v.statSync(O.join(e,c)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let c of o){let a=O.join(e,c),l=O.join(e,c+n);if(v.existsSync(l)){s++;continue}try{Uo(a,l),r++}catch(u){i.push({file:c,err:u.message})}}if(i.length>0){let c=new Error(`Failed to back up ${i.length} file(s) in ${O.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||s>0){let c=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${O.basename(e)}/ (${n})${c}`)}}var hn=!1;async function qo(){if(hn)return;Po(),bs();let t=Lo().version;if(t===Ce){hn=!0;return}ds(),us(),process.on("exit",yn),t>Ce&&(console.error(`
|
|
278
278
|
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${Ce}.`),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.
|
|
279
279
|
`),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${Ce}.
|
|
280
280
|
`),process.exit(1)),console.log(`
|
|
281
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${Ce}`);let n=
|
|
281
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${Ce}`);let n=Ss();if(!n.ok){console.error(`
|
|
282
282
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
283
283
|
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'.
|
|
284
284
|
`),process.exit(1)}let o=ye.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
285
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{
|
|
285
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{Fo(Fe,r.version),Fo(Pe,r.version)}catch(a){console.error(`
|
|
286
286
|
[FATAL] Pre-migration backup failed for ${s}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
287
|
-
`),process.exit(1)}let c=r.module;try{await c.up(
|
|
288
|
-
[FATAL] Migration ${s} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let l=
|
|
287
|
+
`),process.exit(1)}let c=r.module;try{await c.up(Fe,Pe)}catch(a){console.error(`
|
|
288
|
+
[FATAL] Migration ${s} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let l=ks(i);l.ok?(console.error(` \u2713 Auto-rollback restored ${l.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
289
289
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${l.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
290
290
|
`))}catch(l){console.error(` [!] Auto-rollback CRASHED while restoring: ${l.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
291
|
-
`)}process.exit(1)}try{let a=new Date().toISOString(),l={version:r.version,name:c.NAME||s,appliedAt:a},u=
|
|
291
|
+
`)}process.exit(1)}try{let a=new Date().toISOString(),l={version:r.version,name:c.NAME||s,appliedAt:a},u=Lo();u.version=r.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(l),ms(u)}catch(a){console.error(`
|
|
292
292
|
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${a.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.
|
|
293
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{
|
|
293
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Zn()}catch{}try{dn()}catch{}hn=!0,yn(),console.log(`
|
|
294
294
|
\u2713 Schema is now at v${Ce}
|
|
295
|
-
`)}var
|
|
296
|
-
`);let i=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:Ye.join(qt,`fail-${i}.png`)})}catch{}return r.modal||""}catch{return""}}var Ke=process.argv.slice(2),
|
|
295
|
+
`)}var hs=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function gs(e){let t=e.toLowerCase();return hs.some(n=>n.test(t))}var ys=6e4;function ws(){let e=Date.now(),t=[];for(let n of[de,Fe,Pe]){if(!v.existsSync(n))continue;let o;try{o=v.readdirSync(n)}catch{continue}for(let r of o){if(!gs(r))continue;let s=O.join(n,r);try{let i=v.statSync(s);if(!i.isFile()||e-i.mtimeMs<ys)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function bs({verbose:e=!1}={}){let t=ws();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{v.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${O.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 Ss(){let e=[];for(let t of[Fe,Pe]){if(!v.existsSync(t))continue;let n=v.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=O.join(t,o);try{Ot(r)}catch(s){e.push({dir:O.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ks(e){let t=[],n=[];for(let s of[Fe,Pe]){if(!v.existsSync(s))continue;let i=v.readdirSync(s).filter(c=>c.endsWith(e));for(let c of i){let a=O.join(s,c),l=c.slice(0,-e.length),u=O.join(s,l);try{l.toLowerCase().endsWith(".json")?Ot(a):v.accessSync(a,v.constants.R_OK),t.push({backupPath:a,originalPath:u,fileName:c,dir:s})}catch(f){n.push(`${O.basename(s)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:i,fileName:c,dir:a}of t)try{Uo(s,i),o++}catch(l){r.push(`${O.basename(a)}/${c}: ${l.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Uo(e,t){let n=t+".tmp";try{v.copyFileSync(e,n),Mo(n)}catch(o){try{v.unlinkSync(n)}catch{}throw o}try{v.renameSync(n,t)}catch(o){try{v.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}}Nt();bn();var Cs={people_also_viewed:1,similar_profiles:1,more_profiles_for_you:.7,viewers_also_viewed:.6,people_you_may_know:.5,other_profiles:.4,unknown:.3};function As(e){return 1/(1+(Number.isFinite(e)?Math.max(0,e):3))}function xs(e,t={}){let n=t.seedWeights||{},o=t.blockWeights||Cs,r=Number.isInteger(t.iterations)?t.iterations:3,s=typeof t.damping=="number"?t.damping:.6,i=d=>typeof d=="number"&&Number.isFinite(d)?d:0,c=d=>Array.isArray(d&&d.sources)?d.sources.filter(p=>p&&p.seedUrl):[],a=Object.keys(e||{}),l={};for(let d of a)l[d]=i(n[d]);for(let d of a)for(let p of c(e[d]))p.seedUrl in l||(l[p.seedUrl]=i(n[p.seedUrl]));let u={...l},f=(d,p)=>d in n?i(n[d]):i(p[d]);for(let d=0;d<r;d++){let p={...l};for(let g of a){let h=0;for(let y of c(e[g])){let k=i(o[y.block]??o.unknown??.3);h+=f(y.seedUrl,u)*k*As(y.rank)}p[g]+=s*h}let m=1e-9;for(let g of Object.keys(p)){let h=i(p[g]);h>m&&(m=h)}for(let g of Object.keys(p))p[g]=i(p[g])/m;u=p}return a.map(d=>{let p=c(e[d]),m=[...new Set(p.map(g=>g.seedUrl).filter(Boolean))].sort((g,h)=>f(h,u)-f(g,u)).slice(0,3);return{url:d,score:u[d]||0,categories:e[d]?.categories||[],edges:p.length,topSeeds:m}}).sort((d,p)=>p.score-d.score)}function Jo(e,t={}){let n=t.interests||jt,o=typeof t.fitWeight=="number"?t.fitWeight:1;return xs(e,t).map(s=>{let i=e[s.url]?.sectors||[],c=wn(i,n),a=s.score*(1+o*c);return{...s,sectors:i,fit:c,rank:a}}).sort((s,i)=>i.rank-s.rank)}await De();var Es=new Set(["connected"]),_s=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Is(e=W()){let t=new Map;for(let[n,o]of Object.entries(e)){let r=U(o.profileUrl||n);r&&!t.has(r)&&t.set(r,o);for(let s of o.aliases||[])s&&!t.has(s)&&t.set(s,o)}return n=>{let o=t.get(U(n));return!!o&&(Es.has(o.connectionStatus)||_s.has(o.connectionStatus))}}function Rs(e,t={}){let n=Number.isInteger(t.max)?t.max:20,o=t.minRank??0,r=t.minFit??0,s=new Set(t.categories||[]),i=new Set(t.sectors||[]),c=typeof t.isEngaged=="function"?t.isEngaged:()=>!1,a=(t.excludeLocations||[]).map(d=>String(d).toLowerCase()).filter(Boolean),l=d=>!!d&&a.some(p=>String(d).toLowerCase().includes(p)),u=Jo(e||{},{interests:t.interests,seedWeights:t.seedWeights,fitWeight:t.fitWeight}),f=[];for(let d of u){if(f.length>=n)break;let p=e[d.url]||{};p.isConnected||c(d.url)||d.rank<o||d.fit<r||l(p.location)||s.size&&!(p.categories||[]).some(m=>s.has(m))||i.size&&!(p.sectors||[]).some(m=>i.has(m))||f.push({url:d.url,name:p.name||null,rank:d.rank,fit:d.fit,score:d.score,categories:p.categories||[],sectors:p.sectors||[]})}return{candidates:u.length,selected:f}}function Ho(e={}){let t=e.tag||"discovered",n=e.priority||"normal",o=je(),r=e.isEngaged||Is(),s=e.excludeLocations||(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map(f=>f.trim()).filter(Boolean),{candidates:i,selected:c}=Rs(o,{...e,isEngaged:r,excludeLocations:s});if(e.dryRun)return{candidates:i,selected:c,added:0,skippedDup:0,skippedEngaged:0,dryRun:!0};let a=Q(),l=c.map(f=>({url:f.url,tag:t,priority:n})),u=it(a,l,{tag:t,priority:n,nowIso:new Date().toISOString(),alreadyEngaged:r});return ue(a),{candidates:i,selected:c,...u,dryRun:!1}}var xr=new Set(["connected"]),Er=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),Cr=new Set(["pending","connected","excluded_location","email_required","premium_required","wrong_target"]),ba=3,qt=process.env.DATA_DIR?Ye.resolve(process.env.DATA_DIR,"collected-profiles","connect-diagnostics"):Ye.resolve("collected-profiles","connect-diagnostics");async function Sa(e,t,n){try{let o=e.url(),r=await e.evaluate(()=>({modal:(l=>Array.from(document.querySelectorAll(l)).map(u=>(u.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)}));Bt.mkdirSync(qt,{recursive:!0});let s={at:new Date().toISOString(),target:t.url,reason:n||null,pageUrl:o,modalText:r.modal,bodySnippet:r.body};Bt.appendFileSync(Ye.join(qt,"connect-failures.jsonl"),JSON.stringify(s)+`
|
|
296
|
+
`);let i=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:Ye.join(qt,`fail-${i}.png`)})}catch{}return r.modal||""}catch{return""}}var Ke=process.argv.slice(2),_r=Ke[0],ze=Ke.filter(e=>!e.startsWith("--")),_e=e=>Ke.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),G=e=>{let t=Ke.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)},jn=()=>new Date().toISOString();function Jt(){let e=W(),t=new Map;for(let[n,o]of Object.entries(e)){let r=U(o.profileUrl||n);r&&!t.has(r)&&t.set(r,o)}for(let n of Object.values(e))for(let o of n.aliases||[])o&&!t.has(o)&&t.set(o,n);return t}function Ir(e,t){let n=e.get(U(t));return n?xr.has(n.connectionStatus)||Er.has(n.connectionStatus):!1}async function ka(){let e=ze[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(l){return F(`Could not read/parse ${e}: ${l.message}`)}if(!Array.isArray(t))return F("File must be a JSON array of { url, note?, name? }.");let n=G("tag")||"untagged",o=G("priority");if(o&&!ce.includes(o))return F(`--priority must be one of: ${ce.join(", ")}`);let r=o||"normal",s=Q(),i=Jt(),c=it(s,t,{tag:n,priority:r,nowIso:jn(),alreadyEngaged:l=>Ir(i,l)});ue(s),console.log(`
|
|
297
297
|
Added ${c.added} to queue (tag=${n}, priority=${r}).`),c.skippedDup&&console.log(` ${c.skippedDup} already in queue \u2014 skipped.`),c.skippedEngaged&&console.log(` ${c.skippedEngaged} already connected/pending \u2014 skipped.`),c.skippedNoUrl&&console.log(` ${c.skippedNoUrl} had no url \u2014 skipped.`),c.notesTooLong&&console.log(` ${c.notesTooLong} had notes over ${Te} chars \u2014 added WITHOUT a note (LinkedIn's limit); set a shorter one with \`connect note\`.`);let a=s.filter(l=>l.status==="queued"&&l.withNote).length;console.log(`
|
|
298
|
-
Queue now: ${ge(s,"queued").length} queued, ${ge(s,"approved").length} approved.`),a&&console.log(` ${a} 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
|
|
298
|
+
Queue now: ${ge(s,"queued").length} queued, ${ge(s,"approved").length} approved.`),a&&console.log(` ${a} 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 Ar=["founder","investor","hiring_manager","peer"];function va(){let e=m=>{let g=G(m);if(g===void 0)return;let h=parseFloat(g);return Number.isFinite(h)?h:F(`--${m} must be a number.`)},t=G("max"),n=20;if(t!==void 0&&(n=parseInt(t,10),!Number.isInteger(n)||n<=0))return F("--max must be a positive integer.");let o=e("min-fit")??0,r=e("min-rank")??0,s=m=>{let g=G(m);return g?g.split(",").map(h=>h.trim()).filter(Boolean):void 0},i=s("category"),c=s("sector"),a=G("tag")||"discovered",l=G("priority");if(l&&!ce.includes(l))return F(`--priority must be one of: ${ce.join(", ")}`);let u=l||"normal",f=_e("dry-run"),d=Ho({max:n,minFit:o,minRank:r,categories:i,sectors:c,tag:a,priority:u,dryRun:f});if(console.log(`
|
|
299
299
|
${f?"[dry-run] ":""}Fill from discovered pool \u2014 ${d.candidates} ranked candidates.`),f){console.log(`Would add ${d.selected.length} (top by rank\xD7fit):`);for(let m of d.selected.slice(0,30))console.log(` rank ${m.rank.toFixed(2)} \xB7 fit ${m.fit.toFixed(2)} \xB7 ${m.name||m.url} [${(m.sectors||[]).join(",")}]`);return}console.log(`Added ${d.added} to queue (tag=${a}, priority=${u}).`),d.skippedDup&&console.log(` ${d.skippedDup} already in queue \u2014 skipped.`),d.skippedEngaged&&console.log(` ${d.skippedEngaged} already connected/pending \u2014 skipped.`);let p=Q();console.log(`
|
|
300
|
-
Queue now: ${ge(p,"queued").length} queued, ${ge(p,"approved").length} approved.`),console.log(`Next: review \`connect list\`, approve \`connect approve --tag=${a}\`, send \`connect run\`.`)}function
|
|
301
|
-
(shortcut: --valuable = ${
|
|
300
|
+
Queue now: ${ge(p,"queued").length} queued, ${ge(p,"approved").length} approved.`),console.log(`Next: review \`connect list\`, approve \`connect approve --tag=${a}\`, send \`connect run\`.`)}function $a(){if(_e("from-discovered"))return va();let e=G("category");if(e===void 0&&_e("valuable")&&(e=Ar.join(",")),!e)return F(`Usage: connect fill --category=founder,investor,hiring_manager[,peer,recruiter] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
301
|
+
(shortcut: --valuable = ${Ar.join(",")})`);let t=e.split(",").map(S=>S.trim()).filter(Boolean),n=S=>{let A=G(S);if(A===void 0)return;let b=parseInt(A,10);return!Number.isInteger(b)||b<0?F(`--${S} must be a non-negative integer.`):b},o=n("min-posts")??0,r=n("max"),s=G("priority");if(s&&!ce.includes(s))return F(`--priority must be one of: ${ce.join(", ")}`);let i=G("tag"),c=!_e("no-validate"),a=new Set(["recruiter","hiring_manager","founder","investor","coach","sales"]),l=(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map(S=>S.trim().toLowerCase()).filter(Boolean),u=S=>{if(!S)return!1;let A=String(S).toLowerCase();return l.some(b=>A.includes(b))},f=W(),d=[],p=0,m=0,g=0;for(let[S,A]of Object.entries(f))if(t.includes(A.category)&&!(xr.has(A.connectionStatus)||Er.has(A.connectionStatus))&&A.connectionDegree!=="1st"&&!((A.jobIds?.length||0)<o)){if(u(A.location)){p++;continue}if(c&&a.has(A.category)){let b=(typeof A.title=="string"?A.title:"").trim();if(!b){m++;continue}if(Je(b)!==A.category){g++;continue}}d.push({url:A.profileUrl||S,p:A})}let h={high:0,medium:1,low:2};d.sort((S,A)=>(h[S.p.personPriority]??1)-(h[A.p.personPriority]??1)||(A.p.mutualConnections||0)-(S.p.mutualConnections||0)||(A.p.jobIds?.length||0)-(S.p.jobIds?.length||0)),r!==void 0&&(d=d.slice(0,r));let y=d.map(S=>({url:S.url,tag:i||S.p.category,priority:s||(S.p.personPriority==="high"?"high":"normal")})),k=Q(),x=Jt(),w=it(k,y,{alreadyEngaged:S=>Ir(x,S),nowIso:jn()});ue(k),console.log(`
|
|
302
302
|
Filled ${w.added} from [${t.join(", ")}]${o?` (\u2265${o} job-posts)`:""}${c?"":" (--no-validate)"}.`),w.skippedDup&&console.log(` ${w.skippedDup} already in queue \u2014 skipped.`),w.skippedEngaged&&console.log(` ${w.skippedEngaged} already connected/pending \u2014 skipped.`),p&&console.log(` ${p} in excluded locations \u2014 skipped.`),g&&console.log(` ${g} filtered \u2014 title doesn't confirm the category (likely mis-tagged by enrichment).`),m&&console.log(` ${m} skipped \u2014 no title stored to validate (held; not visited, to avoid ban risk).`),console.log(`
|
|
303
|
-
Queue now: ${ge(k,"queued").length} queued, ${ge(k,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function
|
|
303
|
+
Queue now: ${ge(k,"queued").length} queued, ${ge(k,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function Ca(){let e=Q();if(!e.length)return console.log("\nQueue is empty. Add people with `connect add <file.json>`.");let t=G("status"),n=Jt(),o=Re();console.log(`
|
|
304
304
|
=== Connect Queue === (quota left: ${o.daily.remaining}/${o.daily.max} today, ${o.weekly.remaining}/${o.weekly.max} week)
|
|
305
305
|
`);let r={};for(let l of e)r[l.status]=(r[l.status]||0)+1;console.log("Status: "+Object.entries(r).map(([l,u])=>`${l}=${u}`).join(" ")+`
|
|
306
306
|
`),t&&!Et.includes(t)&&console.log(`(unknown status "${t}" \u2014 valid: ${Et.join(", ")})
|
|
307
307
|
`);let s=t?e.filter(l=>l.status===t):e,i={approved:0,queued:1,failed:2,skipped:3,sent:4},c=[...s].sort((l,u)=>(i[l.status]??9)-(i[u.status]??9));for(let l of c){let u=n.get(U(l.url)),f=u&&u.name||"",d=u&&u.title?` \xB7 ${u.title.slice(0,40)}`:"",p=u&&u.mutualConnections?` \xB7 ${u.mutualConnections} mutual`:"",m=l.withNote?"\u{1F4DD}":" ",g=l.priority==="high"?"\u2B06high ":l.priority==="low"?"\u2B07low ":"normal";console.log(` [${l.status.padEnd(8)}] ${g} ${m} ${f}${d}${p}`),console.log(` ${l.url} (tag=${l.tag})`)}let a=e.filter(l=>(l.status==="queued"||l.status==="approved")&&l.withNote).length;a&&console.log(`
|
|
308
308
|
${a} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function Ut(e,t,n,o){let r=Q(),s=0;for(let i of r)e(i)&&t.includes(i.status)&&(i.status=n,s++);return ue(r),console.log(`
|
|
309
|
-
${o}: ${s} entr${s===1?"y":"ies"} \u2192 ${n}.`),s}function
|
|
310
|
-
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
|
|
311
|
-
Note reminder cleared.`)}function
|
|
312
|
-
Priority set to ${t}.`)}async function
|
|
309
|
+
${o}: ${s} entr${s===1?"y":"ies"} \u2192 ${n}.`),s}function Aa(){let e=["queued","failed"];if(_e("all"))return Ut(()=>!0,e,"approved","Approved");let t=G("tag");if(t)return Ut(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=ze[1];if(!n)return F("Usage: connect approve <url> | --all | --tag=X");let o=he(n);return Ut(r=>he(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function xa(){let e=ze[1];if(!e)return F("Usage: connect skip <url>");let t=he(e);return Ut(n=>he(n.url)===t,["queued","approved"],"skipped","Skipped")}function Ea(){let e=Ke[1],t=Ke[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>Te)return F(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${Te}. Shorten it.`);let o=Q(),r=rt(o,e);if(!r)return F("Not in queue.");r.note=n,r.withNote=!0,ue(o),console.log(`
|
|
310
|
+
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 _a(){let e=ze[1];if(!e)return F("Usage: connect no-note <url>");let t=Q(),n=rt(t,e);if(!n)return F("Not in queue.");n.note=null,n.withNote=!1,ue(t),console.log(`
|
|
311
|
+
Note reminder cleared.`)}function Ia(){let e=ze[1],t=ze[2];if(!e||!ce.includes(t))return F(`Usage: connect priority <url> <${ce.join("|")}>`);let n=Q(),o=rt(n,e);if(!o)return F("Not in queue.");o.priority=t,ue(n),console.log(`
|
|
312
|
+
Priority set to ${t}.`)}async function Ra(){let e=_e("dry-run"),t=_e("yes"),n=_e("with-notes"),o=G("max"),r=1/0;if(o!==void 0){let b=parseInt(o,10);if(!Number.isInteger(b)||b<0)return F("--max must be a non-negative integer.");r=b}let s=Re(),i=Math.min(s.daily.remaining,s.weekly.remaining),c=Q(),a=lo(ge(c,"approved"));if(!a.length){let b=ge(c,"queued").length;console.log(`
|
|
313
313
|
Nothing approved to send.`),b&&console.log(` ${b} queued \u2014 approve them first: \`connect approve --all\` (or --tag=X).`);return}if(i<=0){console.log(`
|
|
314
314
|
Connection quota is used up (${s.daily.remaining}/${s.daily.max} today, ${s.weekly.remaining}/${s.weekly.max} week). Try again later.`);return}let l=a.slice(0,Math.min(r,i));if(!l.length){console.log(`
|
|
315
315
|
Nothing to send (--max=${r===1/0?"\u221E":r}).`);return}let u=l.filter(b=>b.withNote).length;console.log(`
|
|
316
|
-
=== Connect run ===`),console.log(` Approved: ${a.length} \xB7 quota left: ${i} \xB7 sending: ${l.length}${n?` (${u} WITH a note)`:" (without notes)"}`),!n&&u&&console.log(` ${u} have a saved note \u2014 add --with-notes to send it (spends your scarce monthly notes).`);let f=Jt();if(l.forEach((b,
|
|
316
|
+
=== Connect run ===`),console.log(` Approved: ${a.length} \xB7 quota left: ${i} \xB7 sending: ${l.length}${n?` (${u} WITH a note)`:" (without notes)"}`),!n&&u&&console.log(` ${u} have a saved note \u2014 add --with-notes to send it (spends your scarce monthly notes).`);let f=Jt();if(l.forEach((b,R)=>{let $=f.get(U(b.url));console.log(` ${R+1}. ${b.withNote?"\u{1F4DD}":" "} ${$?.name||b.url} (${b.priority}, tag=${b.tag})`)}),e){console.log(`
|
|
317
317
|
[dry-run] Nothing sent. Drop --dry-run to send.`);return}t||(console.log(`
|
|
318
|
-
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(b=>process.stdin.once("data",()=>b())));let d=(await import("puppeteer")).default,{launchWithProfile:p,seedCookiesIfNeeded:m}=await Promise.resolve().then(()=>(
|
|
318
|
+
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(b=>process.stdin.once("data",()=>b())));let d=(await import("puppeteer")).default,{launchWithProfile:p,seedCookiesIfNeeded:m}=await Promise.resolve().then(()=>(ir(),rr)),{sendConnectionRequest:g}=await pr().then(()=>fr),{delayed:h}=await Promise.resolve().then(()=>(Pt(),ar)),{startRun:y,endRun:k}=await Promise.resolve().then(()=>($r(),vr)),x=y("connect","run"),w,S;try{let b=await p(d);w=b.browser,S=await w.newPage(),await m(S,b)}catch(b){console.error(`
|
|
319
319
|
[!] ${b.message}
|
|
320
|
-
`);try{w&&await w.close()}catch{}try{k(
|
|
321
|
-
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}let K;if(T.connectionSent?(K="sent",$++):
|
|
322
|
-
\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: ${qt}`),console.log(" Try again later; if it persists you've likely hit LinkedIn's weekly invite limit.");break}await h(3e3+Math.random()*2e3)}let
|
|
323
|
-
=== Done: ${$} sent, ${
|
|
324
|
-
[!] Run aborted: ${b.message}`);try{k(
|
|
320
|
+
`);try{w&&await w.close()}catch{}try{k(x,"error",null,b.message)}catch{}process.exit(1)}let A=0;try{let b=W(),R=new Map;for(let[j,ee]of Object.entries(b)){let T=U(ee.profileUrl||j);T&&!R.has(T)&&R.set(T,j)}for(let[j,ee]of Object.entries(b))for(let T of ee.aliases||[])T&&!R.has(T)&&R.set(T,j);let $=0,D=0,Y=0,J=0;for(let j of l){if(!ot().allowed){console.log(" Quota reached mid-run \u2014 stopping.");break}let ee=n&&j.withNote,T=await g(S,j.url,{message:ee?j.note:null,useCustomMessage:ee,source:j.tag,skipQuotaGate:!0});if(T.fatal){T.reason==="session_expired"?console.log("\n\u26A0 Session expired (LinkedIn re-auth / logout) \u2014 run: `ilml linkedin login`, then retry. Remaining entries left approved."):console.log(`
|
|
321
|
+
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}let K;if(T.connectionSent?(K="sent",$++):Cr.has(T.reason)?(K="skipped",D++):(K="failed",Y++),K==="failed"){J++;let _=await Sa(S,j,T.reason);console.log(` \u2717 ${j.url.slice(-32)} \u2014 ${T.reason||"failed"}${_?` \xB7 LinkedIn: "${_.slice(0,120)}"`:""}`)}else J=0;let Ie=R.get(U(j.url));if(T.connectionSent||Cr.has(T.reason)&&Ie){let _=Ie||j.url;try{Ct(_,T.reason,{method:T.method,messageSent:T.messageSent,profileInfo:T.profileInfo})}catch{}if(T.resolvedUrl)try{At(_,T.resolvedUrl)}catch{}}try{let _=Q(),L=rt(_,j.url);L&&(L.status=K,K==="sent"&&(L.sentAt=jn()),L.result=T.reason||T.error||K,ue(_))}catch(_){console.error(` \u26A0 Could not persist queue update for ${j.url}: ${_.message}`)}if(J>=ba){console.log(`
|
|
322
|
+
\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: ${qt}`),console.log(" Try again later; if it persists you've likely hit LinkedIn's weekly invite limit.");break}await h(3e3+Math.random()*2e3)}let P=Re();console.log(`
|
|
323
|
+
=== Done: ${$} sent, ${D} skipped, ${Y} failed ===`),console.log(`Connection quota left: ${P.daily.remaining}/${P.daily.max} today, ${P.weekly.remaining}/${P.weekly.max} week.`);try{k(x,"success",{sent:$,skipped:D,failed:Y})}catch{}}catch(b){console.error(`
|
|
324
|
+
[!] Run aborted: ${b.message}`);try{k(x,"error",null,b.message)}catch{}A=1}finally{try{await w.close()}catch{}}process.exit(A)}function F(e){console.error(e),process.exit(1)}function Da(){console.log(`connect \u2014 connect queue
|
|
325
325
|
|
|
326
326
|
connect add <file.json> [--tag=X] [--priority=high|normal|low]
|
|
327
327
|
connect fill --category=founder,investor,... [--valuable] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
@@ -329,4 +329,4 @@ Press Enter to send, or Ctrl+C to cancel...`),await new Promise(b=>process.stdin
|
|
|
329
329
|
connect approve <url> | --all | --tag=X
|
|
330
330
|
connect note <url> "custom note" connect no-note <url>
|
|
331
331
|
connect skip <url> connect priority <url> <high|normal|low>
|
|
332
|
-
connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var
|
|
332
|
+
connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var Ta={add:ka,fill:$a,list:Ca,approve:Aa,skip:xa,note:Ea,"no-note":_a,priority:Ia,run:Ra},Rr=Ta[_r];Rr||(Da(),process.exit(_r?1:0));await qo();await Rr();
|