ilml-plugin-linkedin 1.19.2 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/dist/applyQueue.mjs +33 -33
- package/dist/connect.mjs +80 -78
- package/dist/daily.mjs +34 -34
- package/dist/enrichProfile.mjs +15 -15
- package/dist/enrichProfiles.mjs +40 -40
- package/dist/funnelRunner.mjs +60 -60
- package/dist/messageBot.mjs +54 -54
- package/dist/migrationCli.mjs +26 -26
- package/dist/quota.mjs +36 -36
- package/dist/run.mjs +73 -73
- package/dist/scout.mjs +30 -30
- package/dist/syncAll.mjs +112 -112
- package/dist/syncConnections.mjs +50 -50
- package/dist/verifyAbout.mjs +12 -12
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +18 -18
- package/dist/visit.mjs +39 -39
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/run.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var pr=Object.defineProperty;var ze=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ee=(e,t)=>{for(var o in t)pr(e,o,{get:t[o],enumerable:!0})};async function w(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function _o(e){return parseInt(e,10)||0}async function te(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",s=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),i=n.includes("Try for")||n.includes("free trial")||n.includes("/month")||n.includes("per month")||n.includes("Start my")||n.includes("Subscribe"),a=n.includes("Get hired faster")||n.includes("Get hired 2x");if(s||i||a){let l=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:n.substring(0,80)};let f=r.querySelectorAll("button");for(let c of f){let d=c.innerText?.trim().toLowerCase()||"",u=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||u.includes("dismiss"))return c.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var je=ze(()=>{});var Do={};Ee(Do,{default:()=>vr,getAllUnprocessedProfiles:()=>yt,getSummary:()=>qe,getUnprocessedProfiles:()=>ht,listFiles:()=>Lo,loadProfiles:()=>mt,markProfileProcessed:()=>Ro,saveProfile:()=>Ze,saveProfiles:()=>Io});import"dotenv/config";import*as J from"fs";import*as oe from"path";import{fileURLToPath as gr}from"url";function Xe(){J.existsSync(pe)||J.mkdirSync(pe,{recursive:!0})}function Sr(e,t){try{let o=`${e}-${Pt()}.json`,r=J.readdirSync(pe).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==o),n=0;for(let s of r)JSON.parse(J.readFileSync(oe.join(pe,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function Pt(){return new Date().toISOString().split("T")[0]}function Mt(e,t=null){let o=t||Pt();return oe.join(pe,`${e}-${o}.json`)}function mt(e,t=null){Xe();let o=Mt(e,t);try{if(J.existsSync(o)){let r=J.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function Ze(e,t){Xe();let o=Mt(e),r={source:e,date:Pt(),lastUpdated:new Date().toISOString(),profiles:[]};try{J.existsSync(o)&&(r=JSON.parse(J.readFileSync(o,"utf-8")))}catch(i){console.error(`Error reading ${o}:`,i.message)}if(r.profiles.some(i=>i.profileUrl===t.profileUrl))return!1;let s=Sr(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{J.writeFileSync(o,JSON.stringify(r,null,2));let i=s>0?` (seen ${s} day${s>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${i} (total: ${r.profiles.length})`),!0}catch(i){return console.error(`Error saving to ${o}:`,i.message),!1}}function Io(e,t){let o=0;for(let r of t)Ze(e,r)&&o++;return o}function ht(e,t=null){return mt(e,t).filter(r=>!r.processed)}function Ro(e,t,o,r=null){Xe();let n=Mt(e,r);try{if(!J.existsSync(n))return;let s=JSON.parse(J.readFileSync(n,"utf-8")),i=s.profiles.find(a=>a.profileUrl===t);if(i){if(i.processed=!0,i.processedAt=new Date().toISOString(),typeof o=="string")i.status=o;else if(typeof o=="object"){if(i.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(i.name=a.name),a.title&&(i.title=a.title),a.location&&(i.location=a.location),a.company&&(i.company=a.company),a.connectionDegree&&(i.connectionDegree=a.connectionDegree),a.connectionsCount&&(i.connectionsCount=a.connectionsCount),a.mutualConnections&&(i.mutualConnections=a.mutualConnections),a.photoUrl&&(i.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(i.hasVerifiedBadge=a.hasVerifiedBadge)}i.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}s.lastUpdated=new Date().toISOString(),J.writeFileSync(n,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function qe(e){let t=mt(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,s)=>(n[s.status]=(n[s.status]||0)+1,n),{})}}function Lo(){Xe();try{return J.readdirSync(pe).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(J.readFileSync(oe.join(pe,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(s=>!s.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function yt(e){Xe();let t=[];try{let n=J.readdirSync(pe).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of n)try{let i=JSON.parse(J.readFileSync(oe.join(pe,s),"utf-8"));i.profiles&&t.push({file:s,date:i.date,profiles:i.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:s}of t)for(let i of s)!i.processed&&i.profileUrl&&!o.has(i.profileUrl)&&(o.add(i.profileUrl),r.push({...i,_fromDate:n}));return r}var br,wr,pe,vr,Ut=ze(()=>{br=gr(import.meta.url),wr=oe.dirname(oe.dirname(br)),pe=process.env.DATA_DIR?oe.resolve(process.env.DATA_DIR,"collected-profiles"):oe.join(wr,"collected-profiles");vr={loadProfiles:mt,saveProfile:Ze,saveProfiles:Io,getUnprocessedProfiles:ht,getAllUnprocessedProfiles:yt,markProfileProcessed:Ro,getSummary:qe,listFiles:Lo}});import{getPluginConfig as kr}from"@ilivemylife/graph-sdk";var xr,ji,Ce,Ni,Fi,jo=ze(async()=>{xr=await kr();for(let[e,t]of Object.entries(xr))process.env[e]===void 0&&(process.env[e]=t);ji=process.env.LINKEDIN_NAME,Ce=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Ni=Object.freeze(new Set([Ce.DRAFT,Ce.CONFIRMED,Ce.NEEDS_REVIEW])),Fi=Object.freeze(new Set([Ce.DRAFT,Ce.CONFIRMED,Ce.REJECTED,Ce.NEEDS_REVIEW]))});var Zo={};Ee(Zo,{addEncounter:()=>Je,addProfileAlias:()=>Et,atomicWriteJSON:()=>he,canSendConnection:()=>ot,commitDataSnapshot:()=>Xo,default:()=>Nr,getAllApplications:()=>zo,getPersonStatus:()=>kt,getQuestionStats:()=>Qo,getQuotaStatus:()=>nt,getRecentConnections:()=>At,linkPersonToJob:()=>vt,loadApplicationQuestions:()=>Kt,loadConversations:()=>Vo,loadJobs:()=>bt,loadPeople:()=>Q,loadProfileHistory:()=>Jo,loadQuota:()=>$t,loadSyncState:()=>Wo,logApplicationQuestions:()=>Ve,migrateFromDailyFiles:()=>Go,profileSlug:()=>be,recordConnectionSent:()=>Ct,resetCaches:()=>Wt,resolveCanonicalKey:()=>Ue,safeLoadJSON:()=>Te,saveConversations:()=>Ho,saveJobs:()=>wt,savePeople:()=>Se,saveQuota:()=>Yt,saveSyncState:()=>Yo,updateConnectionStatus:()=>xt,upsertJob:()=>St,upsertPerson:()=>we});import"dotenv/config";import*as P from"fs";import*as V from"path";import{fileURLToPath as Er}from"url";import{execSync as Bt}from"child_process";function Wt(){Oe=null,Pe=null,me=null,_e=null,Me=null,Ae=null}function Z(){P.existsSync(z)||P.mkdirSync(z,{recursive:!0})}function he(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";P.writeFileSync(r,o);for(let n=0;n<3;n++)try{P.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Te(e,t){if(!P.existsSync(e))return null;try{let o=JSON.parse(P.readFileSync(e,"utf-8"));try{P.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${V.resolve(e)}`);let r=e+".backup";if(P.existsSync(r))try{let n=JSON.parse(P.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{P.copyFileSync(r,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{P.copyFileSync(e,e+".corrupted")}catch{}return null}}function Be(){return new Date().toISOString().split("T")[0]}function be(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function No(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Ue(e,t,o=null){if(!t||e[t])return t;let r=be(t);if(!r)return t;let n=null;for(let[s,i]of Object.entries(e)){if(be(i.profileUrl||s)===r)return s;!n&&Array.isArray(i.aliases)&&i.aliases.includes(r)&&(n=s)}if(n){let s=No(o),i=No(e[n].name);if(s&&i&&s===i)return n}return t}function _r(){P.existsSync(Gt)||P.mkdirSync(Gt,{recursive:!0})}function Bo(e){let t=be(e);return t?V.join(Gt,`${t}.json`):null}function Jo(e){let t=Bo(e);return t?Te(t,`profile-history/${be(e)}.json`)||[]:[]}function Tr(e,t){let o=Bo(e);if(!o)return;_r();let r=Jo(e);r.unshift(t);try{he(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${be(e)}: ${n.message}`)}}function Fo(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function qo(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Ir(e,t){if(!e)return[];let o=[];for(let r of Ar){let n=e[r],s=t[r];Fo(n)||Fo(s)||qo(n)!==qo(s)&&o.push(r)}return o}function Rr(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function Q(){return Oe||(Z(),Oe=Te(Jt,"people.json")||{},Oe)}function Se(e){Z(),Oe=e;try{he(Jt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(Jt)}`)}}function bt(){return Pe||(Z(),Pe=Te(Vt,"jobs.json")||{},Pe)}function wt(e){Z(),Pe=e;try{he(Vt,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(Vt)}`)}}function Vo(){return _e||(Z(),_e=Te(gt,"conversations.json")||{},Lr(_e),_e)}function Lr(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(s=>s.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{he(gt,e)}catch{}}}function Ho(e){Z(),_e=e;try{he(gt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve(gt)}`)}}function we(e,t={}){if(!e)return null;let o=Q(),r=Be(),n=new Date().toISOString(),s=Ue(o,e,t.name),i=o[s];if(i){let a=Ir(i,t);a.length>0&&(Tr(s,{capturedAt:n,previousLastUpdated:i.lastUpdated||null,changedFields:a,snapshot:Rr(i)}),i.lastSnapshotAt=n),i.seenCount=(i.seenCount||1)+1,i.lastSeen=r,i.lastUpdated=n,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of Uo)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(i[l])&&i[l].length>0)continue;i[l]=t[l]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=n)}else o[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:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return Se(o),o[s]}function St(e,t={}){if(!e)return null;let o=bt(),r=Be(),n=o[e];if(n){let s=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let i of s)t[i]!=null&&(n[i]=t[i])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return wt(o),o[e]}function vt(e,t){if(!e||!t)return;let o=Q(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),Se(o)))}function Je(e,t){if(!e||!t)return;let o=Q(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:Be(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(s.jobId=String(t.jobId)),t.jobTitle&&(s.jobTitle=t.jobTitle),t.jobCompany&&(s.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===s.date&&a.source===s.source&&a.action===s.action&&(a.jobId||"")===(s.jobId||""))&&(r.encounters.push(s),r.lastUpdated=new Date().toISOString(),Se(o))}function kt(e){return e&&Q()[e]?.connectionStatus||null}function xt(e,t,o={}){if(!e)return;if(o.profileInfo)we(e,o.profileInfo);else{let a=Q(),l=Ue(a,e,o.profileInfo?.name);a[l]||we(e,{})}let r=Q(),n=Ue(r,e,o.profileInfo?.name),s=r[n];if(!s)return;let i=Be();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=o.method||s.connectionMethod,s.messageSent=o.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),Se(r)}function Et(e,t,o={}){if(o.dryRun||!e||!t)return;let r=be(t);if(!r)return;let n=Q(),s=Ue(n,e),i=n[s];if(!i)return;let a=be(i.profileUrl||s);r!==a&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(r)||(i.aliases.push(r),i.lastUpdated=new Date().toISOString(),Se(n)))}function $t(){return me||(Z(),me=Te(Oo,"quota.json"),(!me||!me.connections)&&(me={connections:[]}),me)}function Yt(e){Z(),me=e;try{he(Oo,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Ct(e,t="unknown"){let o=$t(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Yt(o)}function At(){let e=$t(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function ot(){let e=At(),t=Be(),o=e.filter(l=>l.date===t).length,r=e.length,n=o>=et,s=r>=tt,i=!n&&!s,a={allowed:i,daily:{sent:o,max:et},weekly:{sent:r,max:tt}};return i||(a.reason=n?`Daily limit reached (${o}/${et})`:`Weekly limit reached (${r}/${tt})`),a}function nt(){let e=At(),t=Be(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:et,remaining:et-o},weekly:{sent:r,max:tt,remaining:tt-r}}}function Dr(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function Go(){Z();let e=P.readdirSync(z).filter(s=>s.endsWith(".json")&&s!=="people.json"&&s!=="jobs.json"&&s!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
1
|
+
var ti=Object.defineProperty;var me=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{for(var o in t)ti(e,o,{get:t[o],enumerable:!0})};async function w(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function on(e){return parseInt(e,10)||0}async function oe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",i=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),s=n.includes("Try for")||n.includes("free trial")||n.includes("/month")||n.includes("per month")||n.includes("Start my")||n.includes("Subscribe"),a=n.includes("Get hired faster")||n.includes("Get hired 2x");if(i||s||a){let l=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:n.substring(0,80)};let u=r.querySelectorAll("button");for(let c of u){let f=c.innerText?.trim().toLowerCase()||"",d=c.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return c.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Ue=me(()=>{});var an={};te(an,{default:()=>ci,getAllUnprocessedProfiles:()=>Et,getSummary:()=>He,getUnprocessedProfiles:()=>At,listFiles:()=>ln,loadProfiles:()=>Ct,markProfileProcessed:()=>sn,saveProfile:()=>lt,saveProfiles:()=>rn});import"dotenv/config";import*as H from"fs";import*as ne from"path";import{fileURLToPath as ii}from"url";function st(){H.existsSync(he)||H.mkdirSync(he,{recursive:!0})}function ai(e,t){try{let o=`${e}-${oo()}.json`,r=H.readdirSync(he).filter(i=>i.startsWith(e)&&i.endsWith(".json")&&i!==o),n=0;for(let i of r)JSON.parse(H.readFileSync(ne.join(he,i),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function oo(){return new Date().toISOString().split("T")[0]}function no(e,t=null){let o=t||oo();return ne.join(he,`${e}-${o}.json`)}function Ct(e,t=null){st();let o=no(e,t);try{if(H.existsSync(o)){let r=H.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function lt(e,t){st();let o=no(e),r={source:e,date:oo(),lastUpdated:new Date().toISOString(),profiles:[]};try{H.existsSync(o)&&(r=JSON.parse(H.readFileSync(o,"utf-8")))}catch(s){console.error(`Error reading ${o}:`,s.message)}if(r.profiles.some(s=>s.profileUrl===t.profileUrl))return!1;let i=ai(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:i}),r.lastUpdated=new Date().toISOString();try{H.writeFileSync(o,JSON.stringify(r,null,2));let s=i>0?` (seen ${i} day${i>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${s} (total: ${r.profiles.length})`),!0}catch(s){return console.error(`Error saving to ${o}:`,s.message),!1}}function rn(e,t){let o=0;for(let r of t)lt(e,r)&&o++;return o}function At(e,t=null){return Ct(e,t).filter(r=>!r.processed)}function sn(e,t,o,r=null){st();let n=no(e,r);try{if(!H.existsSync(n))return;let i=JSON.parse(H.readFileSync(n,"utf-8")),s=i.profiles.find(a=>a.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof o=="string")s.status=o;else if(typeof o=="object"){if(s.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(s.name=a.name),a.title&&(s.title=a.title),a.location&&(s.location=a.location),a.company&&(s.company=a.company),a.connectionDegree&&(s.connectionDegree=a.connectionDegree),a.connectionsCount&&(s.connectionsCount=a.connectionsCount),a.mutualConnections&&(s.mutualConnections=a.mutualConnections),a.photoUrl&&(s.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=a.hasVerifiedBadge)}s.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),H.writeFileSync(n,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function He(e){let t=Ct(e),o=t.filter(n=>n.processed),r=t.filter(n=>!n.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((n,i)=>(n[i.status]=(n[i.status]||0)+1,n),{})}}function ln(){st();try{return H.readdirSync(he).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(H.readFileSync(ne.join(he,t),"utf-8"));return{file:t,source:o,date:r,count:n.profiles?.length||0,unprocessed:n.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function Et(e){st();let t=[];try{let n=H.readdirSync(he).filter(i=>i.startsWith(e+"-")&&i.endsWith(".json")).sort().reverse();for(let i of n)try{let s=JSON.parse(H.readFileSync(ne.join(he,i),"utf-8"));s.profiles&&t.push({file:i,date:s.date,profiles:s.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:i}of t)for(let s of i)!s.processed&&s.profileUrl&&!o.has(s.profileUrl)&&(o.add(s.profileUrl),r.push({...s,_fromDate:n}));return r}var si,li,he,ci,ro=me(()=>{si=ii(import.meta.url),li=ne.dirname(ne.dirname(si)),he=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(li,"collected-profiles");ci={loadProfiles:Ct,saveProfile:lt,saveProfiles:rn,getUnprocessedProfiles:At,getAllUnprocessedProfiles:Et,markProfileProcessed:sn,getSummary:He,listFiles:ln}});import{getPluginConfig as ui}from"@ilivemylife/graph-sdk";var di,ke,ye,io,so,lo=me(async()=>{di=await ui();for(let[e,t]of Object.entries(di))process.env[e]===void 0&&(process.env[e]=t);ke=process.env.LINKEDIN_NAME,ye=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),io=Object.freeze(new Set([ye.DRAFT,ye.CONFIRMED,ye.NEEDS_REVIEW])),so=Object.freeze(new Set([ye.DRAFT,ye.CONFIRMED,ye.REJECTED,ye.NEEDS_REVIEW]))});var $n={};te($n,{addEncounter:()=>Ke,addProfileAlias:()=>Lt,atomicWriteJSON:()=>be,canSendConnection:()=>ut,commitDataSnapshot:()=>En,default:()=>xi,getAllApplications:()=>Cn,getPersonStatus:()=>Dt,getQuestionStats:()=>An,getQuotaStatus:()=>dt,getRecentConnections:()=>Ft,linkPersonToJob:()=>It,loadApplicationQuestions:()=>yo,loadConversations:()=>bn,loadJobs:()=>_t,loadPeople:()=>Q,loadProfileHistory:()=>gn,loadQuota:()=>Nt,loadSyncState:()=>kn,logApplicationQuestions:()=>ze,migrateFromDailyFiles:()=>Sn,profileSlug:()=>ve,recordConnectionSent:()=>Pt,resetCaches:()=>mo,resolveCanonicalKey:()=>xe,safeLoadJSON:()=>Le,saveConversations:()=>wn,saveJobs:()=>Tt,savePeople:()=>Ae,saveQuota:()=>ho,saveSyncState:()=>vn,updateConnectionStatus:()=>jt,upsertJob:()=>Rt,upsertPerson:()=>Ce});import"dotenv/config";import*as U from"fs";import*as V from"path";import{fileURLToPath as fi}from"url";import{execSync as ao}from"child_process";function mo(){Ve=null,Ge=null,ge=null,je=null,We=null,De=null}function Z(){U.existsSync(z)||U.mkdirSync(z,{recursive:!0})}function be(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";U.writeFileSync(r,o);for(let n=0;n<3;n++)try{U.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Le(e,t){if(!U.existsSync(e))return null;try{let o=JSON.parse(U.readFileSync(e,"utf-8"));try{U.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${V.resolve(e)}`);let r=e+".backup";if(U.existsSync(r))try{let n=JSON.parse(U.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{U.copyFileSync(r,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{U.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ye(){return new Date().toISOString().split("T")[0]}function ve(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function cn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function xe(e,t,o=null){if(!t||e[t])return t;let r=ve(t);if(!r)return t;let n=null;for(let[i,s]of Object.entries(e)){if(ve(s.profileUrl||i)===r)return i;!n&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}if(n){let i=cn(o),s=cn(e[n].name);if(i&&s&&i===s)return n}return t}function yi(){U.existsSync(po)||U.mkdirSync(po,{recursive:!0})}function yn(e){let t=ve(e);return t?V.join(po,`${t}.json`):null}function gn(e){let t=yn(e);return t?Le(t,`profile-history/${ve(e)}.json`)||[]:[]}function gi(e,t){let o=yn(e);if(!o)return;yi();let r=gn(e);r.unshift(t);try{be(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${ve(e)}: ${n.message}`)}}function un(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function dn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function bi(e,t){if(!e)return[];let o=[];for(let r of hi){let n=e[r],i=t[r];un(n)||un(i)||dn(n)!==dn(i)&&o.push(r)}return o}function wi(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function Q(){return Ve||(Z(),Ve=Le(co,"people.json")||{},Ve)}function Ae(e){Z(),Ve=e;try{be(co,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(co)}`)}}function _t(){return Ge||(Z(),Ge=Le(uo,"jobs.json")||{},Ge)}function Tt(e){Z(),Ge=e;try{be(uo,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(uo)}`)}}function bn(){return je||(Z(),je=Le($t,"conversations.json")||{},Si(je),je)}function Si(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(i=>i.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{be($t,e)}catch{}}}function wn(e){Z(),je=e;try{be($t,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve($t)}`)}}function Ce(e,t={}){if(!e)return null;let o=Q(),r=Ye(),n=new Date().toISOString(),i=xe(o,e,t.name),s=o[i];if(s){let a=bi(s,t);a.length>0&&(gi(i,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:a,snapshot:wi(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of hn)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return Ae(o),o[i]}function Rt(e,t={}){if(!e)return null;let o=_t(),r=Ye(),n=o[e];if(n){let i=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let s of i)t[s]!=null&&(n[s]=t[s])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return Tt(o),o[e]}function It(e,t){if(!e||!t)return;let o=Q(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),Ae(o)))}function Ke(e,t){if(!e||!t)return;let o=Q(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:Ye(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!r.encounters.some(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),Ae(o))}function Dt(e){return e&&Q()[e]?.connectionStatus||null}function jt(e,t,o={}){if(!e)return;if(o.profileInfo)Ce(e,o.profileInfo);else{let a=Q(),l=xe(a,e,o.profileInfo?.name);a[l]||Ce(e,{})}let r=Q(),n=xe(r,e,o.profileInfo?.name),i=r[n];if(!i)return;let s=Ye();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=o.method||i.connectionMethod,i.messageSent=o.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Ae(r)}function Lt(e,t,o={}){if(o.dryRun||!e||!t)return;let r=ve(t);if(!r)return;let n=Q(),i=xe(n,e),s=n[i];if(!s)return;let a=ve(s.profileUrl||i);r!==a&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(r)||(s.aliases.push(r),s.lastUpdated=new Date().toISOString(),Ae(n)))}function Nt(){return ge||(Z(),ge=Le(fn,"quota.json"),(!ge||!ge.connections)&&(ge={connections:[]}),ge)}function ho(e){Z(),ge=e;try{be(fn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Pt(e,t="unknown"){let o=Nt(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),ho(o)}function Ft(){let e=Nt(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function ut(){let e=Ft(),t=Ye(),o=e.filter(l=>l.date===t).length,r=e.length,n=o>=at,i=r>=ct,s=!n&&!i,a={allowed:s,daily:{sent:o,max:at},weekly:{sent:r,max:ct}};return s||(a.reason=n?`Daily limit reached (${o}/${at})`:`Weekly limit reached (${r}/${ct})`),a}function dt(){let e=Ft(),t=Ye(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:at,remaining:at-o},weekly:{sent:r,max:ct,remaining:ct-r}}}function ki(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function Sn(){Z();let e=U.readdirSync(z).filter(i=>i.endsWith(".json")&&i!=="people.json"&&i!=="jobs.json"&&i!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
2
2
|
Migrating from ${e.length} daily files...
|
|
3
|
-
`);let t=Q(),o=
|
|
4
|
-
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${n} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function
|
|
3
|
+
`);let t=Q(),o=_t(),r=0,n=0;e.sort();for(let i of e){let s=V.join(z,i),a;try{a=JSON.parse(U.readFileSync(s,"utf-8"))}catch(c){console.log(` Skipping ${i}: ${c.message}`);continue}let l=a.date||i.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,u=a.source||i.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${i}: no profiles array`);continue}console.log(` ${i}: ${a.profiles.length} profiles`);for(let c of a.profiles){let f=c.profileUrl;if(!f)continue;let d=t[f];if(d){d.seenCount=(d.seenCount||1)+1,l&&(!d.lastSeen||l>d.lastSeen)&&(d.lastSeen=l),l&&(!d.firstSeen||l<d.firstSeen)&&(d.firstSeen=l),u&&!d.sources?.includes(u)&&(d.sources=d.sources||[],d.sources.push(u));for(let p of hn)c[p]!=null&&(d[p]=c[p]);c.status&&c.processed&&(d.connectionStatus=c.status,d.connectionDate=l,c.funnelResult&&(d.connectionMethod=c.funnelResult.method||d.connectionMethod,d.messageSent=c.funnelResult.message||d.messageSent)),d.lastUpdated=new Date().toISOString()}else t[f]={name:c.name||null,title:c.title||null,location:c.location||null,company:c.company||null,connectionDegree:c.connectionDegree||null,connectionsCount:c.connectionsCount||null,mutualConnections:c.mutualConnections||null,photoUrl:c.photoUrl||null,hasVerifiedBadge:c.hasVerifiedBadge||!1,firstSeen:l,lastSeen:l,seenCount:1,sources:u?[u]:[],connectionStatus:c.processed&&c.status||null,connectionDate:c.processed?l:null,connectionMethod:c.funnelResult?.method||null,messageSent:c.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(c.fromJob?.url){let p=ki(c.fromJob.url);p&&(t[f].jobIds||(t[f].jobIds=[]),t[f].jobIds.includes(p)||t[f].jobIds.push(p),o[p]?o[p].recruiterUrl||(o[p].recruiterUrl=f):(o[p]={title:c.fromJob.title||null,company:c.fromJob.company||null,location:null,salary:null,url:c.fromJob.url,applied:!0,appliedDate:l,recruiterUrl:f,firstSeen:l},n++))}}}return Ae(t),Tt(o),console.log(`
|
|
4
|
+
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${n} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function kn(){return We||(Z(),We=Le(pn,"sync-state.json")||{},We)}function vn(e){Z(),We=e;try{be(pn,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function yo(){if(De)return De;Z();try{U.existsSync(fo)&&(De=JSON.parse(U.readFileSync(fo,"utf-8")))}catch{}return De||(De={}),De}function xn(e){return Array.isArray(e.applications)}function Cn(){let e=yo();if(xn(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function ze(e){if(!e||!e.questions||e.questions.length===0)return;let t=yo(),o=e.jobId||"unknown",n={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(i=>{let s={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=vi?s.options=i.options:s.optionsOmitted=!0),i.page&&(s.page=i.page),i.wasPreFilled&&(s.wasPreFilled=!0),i.wasRetry&&(s.wasRetry=!0),typeof i.isRequired=="boolean"&&(s.isRequired=i.isRequired),i.wasOptional&&(s.wasOptional=!0),s})};xn(t)?(n.jobId=o,n.jobTitle=e.jobTitle||null,n.jobCompany=e.jobCompany||null,n.jobUrl=e.jobUrl||null,t.applications.push(n)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(n));try{be(fo,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function An(){let e=Cn(),t=new Map;for(let i of e)for(let s of i.questions||[]){let a=s.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:s.question,count:0,answers:new Map});let l=t.get(a);l.count++;let u=(s.answer||"").trim();l.answers.set(u,(l.answers.get(u)||0)+1)}let o=[...t.values()].sort((i,s)=>s.count-i.count),r=o.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((s,a)=>a[1]-s[1])[0]?.[0]||""})),n=o.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((s,a)=>a[1]-s[1]).map(([s,a])=>`${s} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function En(e){if(U.existsSync(V.join(z,".git")))try{let t={cwd:z,stdio:"pipe",timeout:1e4};ao("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{ao("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');ao(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var pi,mi,z,co,uo,fn,$t,pn,fo,po,mn,at,ct,Ve,Ge,ge,je,We,De,hn,hi,vi,xi,Qe=me(async()=>{await lo();pi=fi(import.meta.url),mi=V.dirname(V.dirname(pi)),z=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(mi,"collected-profiles"),co=V.join(z,"people.json"),uo=V.join(z,"jobs.json"),fn=V.join(z,"quota.json"),$t=V.join(z,"conversations.json"),pn=V.join(z,"sync-state.json"),fo=V.join(z,"application-questions.json"),po=V.join(z,"profile-history"),mn=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},at=mn(process.env.CONNECT_MAX_DAILY,20),ct=mn(process.env.CONNECT_MAX_WEEKLY,100),Ve=null,Ge=null,ge=null,je=null,We=null,De=null;hn=["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"],hi=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];vi=50;xi={loadPeople:Q,savePeople:Ae,loadJobs:_t,saveJobs:Tt,loadConversations:bn,saveConversations:wn,upsertPerson:Ce,upsertJob:Rt,linkPersonToJob:It,addEncounter:Ke,getPersonStatus:Dt,updateConnectionStatus:jt,addProfileAlias:Lt,resolveCanonicalKey:xe,migrateFromDailyFiles:Sn,loadQuota:Nt,saveQuota:ho,recordConnectionSent:Pt,canSendConnection:ut,getRecentConnections:Ft,getQuotaStatus:dt,loadSyncState:kn,saveSyncState:vn,commitDataSnapshot:En,logApplicationQuestions:ze,getQuestionStats:An}});var _n={};te(_n,{extractCertificationsFromDetails:()=>_i,extractEducationFromDetails:()=>Ei,extractExperienceFromDetails:()=>Ci,extractFeaturedFromDetails:()=>Ai,extractRecommendationsFromDetails:()=>Ti,extractSkillsFromDetails:()=>$i});async function Ci(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let n=0;for(;n<5&&await e.evaluate(()=>{for(let s of document.querySelectorAll("button"))if(/^Load more$/i.test((s.textContent||"").trim()))return s.click(),!0;return!1});)n++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function s(c){let f=[];for(let d of c.querySelectorAll("div")){let p=Array.from(d.children).filter(h=>h.tagName==="DIV");if(p.length<3)continue;let m=p.filter(h=>(h.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 a=s(i);if(!a)return[];let l=Array.from(a.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function u(c){let f=c[0]||null,d=null,p=null;if(c[1]){let E=c[1].split("\xB7").map(D=>D.trim());d=E[0]||null,E[1]&&(p=E[1])}let m=c.findIndex(E=>/(\d{4}|present)/i.test(E)&&/(-|–|—)/i.test(E)&&E.length<80),h=null,g=null;if(m>=0){let E=c[m].split("\xB7").map(D=>D.trim());h=E[0]||null,E[1]&&(g=E[1])}let y=null,S=-1;if(m>=0&&c[m+1]){let E=c[m+1],D=/^[>*\-•]|^>/.test(E),K=/https?:\/\//.test(E),B=/\d{4}/.test(E),Y=/,/.test(E)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(E);!D&&!K&&!B&&E.length<100&&Y&&(y=E,S=m+1)}let C=null,b=-1,v=c[c.length-1];if(v&&/and\s+\+\d+\s+skills?$/i.test(v)){b=c.length-1;let E=v.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);E&&(C={listed:E[1].split(",").map(D=>D.trim()),additional:parseInt(E[2],10)})}let L=new Set([0,1,m,S,b].filter(E=>E>=0)),I=c.filter((E,D)=>!L.has(D)),N=I.length>0?I.join(`
|
|
5
5
|
|
|
6
|
-
`):null;return{title:
|
|
7
|
-
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return
|
|
8
|
-
${
|
|
6
|
+
`):null;return{title:f,company:d,employmentType:p,dates:h,duration:g,location:y,description:N,skills:C,_raw:c}}return l.map(c=>{let d=(c.innerText||"").trim().split(`
|
|
7
|
+
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return u(d)}).filter(c=>c.title)})}catch(r){if(/session expired|bounced to|authwall|checkpoint/i.test(r.message||""))throw r;return console.error(`extractExperienceFromDetails failed for ${t}: ${r.message?.slice(0,120)}`),[]}}async function ft(e,t,o){let r=t.replace(/\/+$/,"")+`/details/${o}/`;await e.goto(r,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let n=e.url();if(/\/(login|authwall|checkpoint)/i.test(n))throw new Error(`Session expired \u2014 bounced to ${n} when fetching /details/${o}/`);if(!n.toLowerCase().includes(`/details/${o.toLowerCase()}/`))throw new Error(`Section /details/${o}/ not available on profile (landed on ${n})`);for(let s=0;s<4;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)i++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function mt(e,t,o,r){try{return await r()}catch(n){let i=n.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw n;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${o} failed for ${e}: ${i.slice(0,120)}`),[])}}async function Ai(e,t){return mt(t,"featured","extractFeaturedFromDetails",async()=>(await ft(e,t,"featured"),await e.evaluate(`(() => {
|
|
8
|
+
${pt}
|
|
9
9
|
|
|
10
10
|
const main = document.querySelector('main');
|
|
11
11
|
if (!main) return [];
|
|
@@ -45,8 +45,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
45
45
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
46
46
|
return true;
|
|
47
47
|
});
|
|
48
|
-
})()`)))}async function
|
|
49
|
-
${
|
|
48
|
+
})()`)))}async function Ei(e,t){return mt(t,"education","extractEducationFromDetails",async()=>(await ft(e,t,"education"),await e.evaluate(`(() => {
|
|
49
|
+
${pt}
|
|
50
50
|
|
|
51
51
|
const main = document.querySelector('main');
|
|
52
52
|
if (!main) return [];
|
|
@@ -82,8 +82,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
82
82
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
83
83
|
return true;
|
|
84
84
|
});
|
|
85
|
-
})()`)))}async function
|
|
86
|
-
${
|
|
85
|
+
})()`)))}async function $i(e,t){return mt(t,"skills","extractSkillsFromDetails",async()=>(await ft(e,t,"skills"),await e.evaluate(`(() => {
|
|
86
|
+
${pt}
|
|
87
87
|
|
|
88
88
|
const main = document.querySelector('main');
|
|
89
89
|
if (!main) return [];
|
|
@@ -114,8 +114,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
114
114
|
skills.push({ name, endorsements, _raw: lines });
|
|
115
115
|
}
|
|
116
116
|
return skills;
|
|
117
|
-
})()`)))}async function
|
|
118
|
-
${
|
|
117
|
+
})()`)))}async function _i(e,t){return mt(t,"certifications","extractCertificationsFromDetails",async()=>(await ft(e,t,"certifications"),await e.evaluate(`(() => {
|
|
118
|
+
${pt}
|
|
119
119
|
|
|
120
120
|
const main = document.querySelector('main');
|
|
121
121
|
if (!main) return [];
|
|
@@ -139,8 +139,8 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
139
139
|
|
|
140
140
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
141
141
|
}).filter(e => e.name);
|
|
142
|
-
})()`)))}async function
|
|
143
|
-
${
|
|
142
|
+
})()`)))}async function Ti(e,t){return mt(t,"recommendations","extractRecommendationsFromDetails",async()=>(await ft(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
143
|
+
${pt}
|
|
144
144
|
|
|
145
145
|
const main = document.querySelector('main');
|
|
146
146
|
if (!main) return [];
|
|
@@ -175,7 +175,7 @@ Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r
|
|
|
175
175
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
176
176
|
return true;
|
|
177
177
|
});
|
|
178
|
-
})()`)))}var
|
|
178
|
+
})()`)))}var pt,Tn=me(()=>{Ue();pt=`
|
|
179
179
|
function findEntryContainer(root) {
|
|
180
180
|
const candidates = [];
|
|
181
181
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -238,85 +238,85 @@ function findEntryContainer(root) {
|
|
|
238
238
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
239
239
|
return candidates[0]?.el;
|
|
240
240
|
}
|
|
241
|
-
`});je();import Yn from"puppeteer";import*as nr from"fs";import{createGraphClient as mr,resolveToken as hr}from"@ilivemylife/graph-sdk";import{config as yr}from"dotenv";yr();var To=hr()||process.env.TOKEN;To||(console.error(`
|
|
241
|
+
`});var Rn={};te(Rn,{extractSidePanelProfiles:()=>Ii,normalizeFundUrl:()=>Ot,normalizeProfileUrl:()=>Xe});function Xe(e){if(!e||typeof e!="string"||/custom-invite|\/search\/|miniProfile/.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let o=t[1].trim();return o?`https://www.linkedin.com/in/${o}/`:null}function Ot(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}async function Ii(e,t={}){let o=Number.isInteger(t.perBlockCap)?t.perBlockCap:10;try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(a=>setTimeout(a,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(a=>setTimeout(a,1200))}catch{}let r;try{r=await e.evaluate(a=>{let l=p=>(p||"").replace(/\s+/g," ").trim(),u=p=>l(p).replace(/^View\s+/i,"").split(/\s*[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\b(1st|2nd|3rd)\b.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),c=p=>{let m=p;for(let h=0;h<6&&m.parentElement;h++)if(m=m.parentElement,m.querySelectorAll('a[href*="/in/"]').length>=2)return m;return p.parentElement},f=[],d=Array.from(document.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let p of d){let m=l(p.textContent).toLowerCase();if(!m)continue;let h=a.find(([v])=>m.includes(v));if(!h)continue;let[,g]=h,y=c(p);if(!y)continue;let S=Array.from(y.querySelectorAll('a[href*="/in/"]')),C=0,b=new Set;for(let v of S){let L=v.href||v.getAttribute("href")||"";if(!/\/in\//.test(L))continue;let I=v.querySelector('span[aria-hidden="true"]'),N=u(I?I.textContent:v.getAttribute("aria-label")||v.textContent);if(!N||b.has(L))continue;b.add(L);let E=v.closest("li")||v.parentElement,D="";E&&(D=Array.from(E.querySelectorAll("p, span")).map(B=>l(B.textContent)).filter(B=>B&&B!==N&&!/^view\b/i.test(B)&&B.length>2)[0]||""),f.push({href:L,name:N,headline:D,block:g,rank:C++})}}return f},Ri)}catch{return[]}let n=Xe(t.seedUrl||""),i=new Map,s={};for(let a of r){let l=Xe(a.href);l&&(n&&l===n||(s[a.block]=s[a.block]||0,!(s[a.block]>=o)&&(i.has(l)||(s[a.block]++,i.set(l,{url:l,name:a.name,headline:a.headline||null,block:a.block,rank:a.rank})))))}return Array.from(i.values())}var Ri,go=me(()=>{Ri=[["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 Pn={};te(Pn,{getJobDecision:()=>Co,getLastVisit:()=>Ui,getScoutStats:()=>Bi,loadCompanies:()=>Ao,loadDiscoveredPeople:()=>St,loadJobDecisions:()=>xo,loadScoutedJobs:()=>ko,loadVisitLog:()=>Bt,recordCompany:()=>qi,recordDiscoveredEdge:()=>Fi,recordDiscoveredEdges:()=>Oi,recordVisit:()=>Mi,resetCaches:()=>So,saveCompany:()=>Ut,saveDiscoveredPerson:()=>Ni,saveScoutedJob:()=>vo,setJobDecision:()=>Fe});import"dotenv/config";import*as re from"fs";import*as ee from"path";import{fileURLToPath as Di}from"url";function Ee(){re.existsSync(Pe)||re.mkdirSync(Pe,{recursive:!0})}function $e(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";re.writeFileSync(r,o);for(let n=0;n<3;n++)try{re.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function wt(e){try{if(re.existsSync(e))return JSON.parse(re.readFileSync(e,"utf-8"))}catch{}return null}function So(){ht=null,yt=null,gt=null,bt=null,Ne=null}function ko(){return ht||(ht=wt(In)||{},ht)}function vo(e,t){if(!e)return;Ee();let o=ko(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,i]of Object.entries(t))i!=null&&(o[e][n]=i);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{$e(In,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}function xo(){return yt||(yt=wt(jn)||{},yt)}function Fe(e,t,o={}){if(!e||!t)return;Ee();let r=xo(),n=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=n,o.reason&&(r[e].reason=o.reason),o.score!=null&&(r[e].score=o.score),o.source&&(r[e].source=o.source)):r[e]={status:t,decidedAt:n,updatedAt:n,reason:o.reason||null,score:o.score??null,source:o.source||null};try{$e(jn,r)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Co(e){return xo()[e]||null}function St(){return gt||(gt=wt(Mt)||{},gt)}function Ze(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Ln(e,t){let o=Xe(t)||t;if(e[o])return o;let r=Ze(t);if(!r)return o;let n=null;for(let[i,s]of Object.entries(e)){if(Ze(s&&(s.canonicalUrl||s.profileUrl)||i)===r)return i;!n&&s&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}return n||o}function Ni(e,t){if(!e)return;Ee();let o=St(),r=new Date().toISOString().slice(0,10),n=Ln(o,e),i=Ze(e);if(o[n]){let s=o[n];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&Ze(s.canonicalUrl||s.profileUrl||n)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[n]={canonicalUrl:n,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:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{$e(Mt,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function Pi(e,t){let o=e.kind||"similar-panel";return o==="list-post"?{edge:{kind:o,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:r=>r.kind==="list-post"&&r.postUrl===(e.postUrl||null)&&r.fund===(e.fund||null)}:o==="scout"?{edge:{kind:o,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:r=>r.kind==="scout"&&r.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:r=>r.kind!=="list-post"&&r.kind!=="scout"&&r.seedUrl===(e.seedUrl||null)&&r.block===(e.block||"unknown")}}function Nn(e,t,o={},r){if(!t)return;let n=Ze(t);t=Ln(e,t);let i=o.seedUrl?{...o,seedUrl:Xe(o.seedUrl)||o.seedUrl}:o,s=r.slice(0,10),{edge:a,match:l}=Pi(i,r),u=e[t];u||(u=e[t]={canonicalUrl:t,aliases:[],name:o.name||null,headline:o.headline||null,location:o.location||null,company:o.company||null,companyUrl:o.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:a.kind,sources:[],connectionsCount:o.connectionsCount??null,selectivity:o.selectivity||"unknown",connectGate:o.connectGate||"unknown",score:null,fitScore:null,isConnected:o.isConnected||!1,graphRefs:[],note:o.note||"",whyUseful:o.whyUseful||"",extra:{},source:a.kind,role:Array.isArray(o.categories)&&o.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:s,firstSeen:s,lastSeen:s}),o.name&&(u.name=o.name),o.headline&&(u.headline=u.headline||o.headline),o.location&&(u.location=u.location||o.location),o.company&&(u.company=o.company),o.companyUrl&&(u.companyUrl=u.companyUrl||o.companyUrl),o.isConnected!=null&&(u.isConnected=o.isConnected),o.connectionsCount!=null&&(u.connectionsCount=o.connectionsCount),o.selectivity&&o.selectivity!=="unknown"&&(u.selectivity=o.selectivity),o.connectGate&&o.connectGate!=="unknown"&&(u.connectGate=o.connectGate),o.note&&!u.note&&(u.note=o.note),o.whyUseful&&!u.whyUseful&&(u.whyUseful=o.whyUseful),o.extra&&typeof o.extra=="object"&&(u.extra={...u.extra||{},...o.extra}),Array.isArray(u.sources)||(u.sources=[]);let c=u.sources.find(l);if(c?(a.rank!=null&&(c.rank==null||a.rank<c.rank)&&(c.rank=a.rank),c.at=a.at):u.sources.push(a),Array.isArray(u.categories)||(u.categories=[]),Array.isArray(u.sectors)||(u.sectors=[]),Array.isArray(u.aliases)||(u.aliases=[]),Array.isArray(u.graphRefs)||(u.graphRefs=[]),bo(u.categories,o.category),qt(u.categories,o.categories),qt(u.sectors,o.sectors),qt(u.aliases,o.aliases),n&&Ze(u.canonicalUrl||t)!==n&&bo(u.aliases,n),qt(u.graphRefs,o.graphRefs),Array.isArray(o.affiliations)){Array.isArray(u.affiliations)||(u.affiliations=[]);for(let f of o.affiliations)!f||!f.companyKey||u.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||u.affiliations.push(f)}u.lastSeen=s,u.seenCount=(u.seenCount||0)+1}function Fi(e,t={}){if(!e)return;Ee();let o=St();Nn(o,e,t,new Date().toISOString());try{$e(Mt,o)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function Oi(e){if(!Array.isArray(e)||e.length===0)return;Ee();let t=St(),o=new Date().toISOString(),r=0;for(let n of e)!n||!n.url||(Nn(t,n.url,n,o),r++);if(r)try{$e(Mt,t)}catch(n){console.error(`[!] Failed to save discovered-people.json: ${n.message}`)}}function qi(e={}){if(!e||!e.name)return;Ee();let t=e.key||Ot(e.website)||Ot(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,o=Ao(),r=new Date().toISOString().slice(0,10),n=(l,u)=>{u&&Array.isArray(l)&&!l.includes(u)&&l.push(u)},i=(l,u)=>{if(Array.isArray(u))for(let c of u)n(l,c)},s=o[t];s||(s=o[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:r,lastSeen:r}),e.name&&(s.name=e.name),e.website&&(s.website=s.website||e.website),e.linkedinUrl&&(s.linkedinUrl=s.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!s[l]&&(s[l]=e[l]);e.note&&!s.note&&(s.note=e.note),e.whyUseful&&!s.whyUseful&&(s.whyUseful=e.whyUseful),e.fitScore!=null&&(s.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(s.extra={...s.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(s[l])||(s[l]=[]),i(s[l],e[l]);Array.isArray(s.people)||(s.people=[]);let a=l=>{if(!l||!l.url)return;let u=s.people.find(c=>c.url===l.url&&(c.role||null)===(l.role||null));u?l.current!=null&&(u.current=l.current):s.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(a),(e.partners||[]).forEach(l=>a({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(s.portfolio)||(s.portfolio=[]);for(let l of e.portfolio||[]){let u=l&&(l.key||l.name);u&&!s.portfolio.some(c=>(c.key||c.name)===u)&&s.portfolio.push(l)}s.lastSeen=r,s.seenCount=(s.seenCount||0)+1;try{$e(wo,o)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function Ao(){return bt||(bt=wt(wo)||{},bt)}function Ut(e,t){if(!e)return;Ee();let o=Ao(),r=new Date().toISOString().slice(0,10);if(o[e]){let n=o[e];t.name&&(n.name=t.name),t.about&&(n.about=t.about),t.size&&(n.size=t.size),t.industries&&(n.industries=t.industries),t.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(t.jobId)||n.jobIds.push(t.jobId)),t.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(t.recruiterUrl)||n.recruiterUrls.push(t.recruiterUrl)),n.lastSeen=r,n.jobCount=n.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{$e(wo,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}function Bt(){return Ne||(Ne=wt(Dn)||{visits:[]},Array.isArray(Ne.visits)||(Ne.visits=[]),Ne)}function Mi(e,t={}){if(!e)return;Ee();let o=Bt();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let r=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(n=>new Date(n.date).getTime()>r);try{$e(Dn,o)}catch(n){console.error(`[!] Failed to save visit-log.json: ${n.message}`)}}function Ui(e){let t=Bt();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function Bi(){let e=ko(),t=St(),o=Object.values(e),r=Object.values(t),n={};for(let d of o)d.company&&(n[d.company]=(n[d.company]||0)+1);let i=Object.entries(n).sort((d,p)=>p[1]-d[1]).slice(0,5).map(([d,p])=>`${d} (${p})`),s={};for(let d of o)for(let p of d.techStack||[])s[p]=(s[p]||0)+1;let a=Object.entries(s).sort((d,p)=>p[1]-d[1]).slice(0,8).map(([d,p])=>`${d} (${p})`),l=Bt(),u=new Date().toISOString().slice(0,10),c=l.visits.filter(d=>d.date.startsWith(u)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:a,totalVisited:f,todayVisited:c,lastScoutDate:o.length>0?o.sort((d,p)=>(p.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var ji,Li,Pe,In,Mt,Dn,wo,jn,ht,yt,gt,bo,qt,bt,Ne,Jt=me(()=>{go();ji=Di(import.meta.url),Li=ee.dirname(ee.dirname(ji)),Pe=process.env.DATA_DIR?ee.resolve(process.env.DATA_DIR,"market-research"):ee.join(Li,"market-research"),In=ee.join(Pe,"scouted-jobs.json"),Mt=ee.join(Pe,"discovered-people.json"),Dn=ee.join(Pe,"visit-log.json"),wo=ee.join(Pe,"companies.json"),jn=ee.join(Pe,"job-decisions.json");ht=null;yt=null;gt=null;bo=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},qt=(e,t)=>{if(Array.isArray(t))for(let o of t)bo(e,o)};bt=null;Ne=null});var Wn={};te(Wn,{computeEngagement:()=>$o,detectCategory:()=>qn,detectCategoryFromTitle:()=>Ht,determineAction:()=>Vn,determineLastMessageBy:()=>Un,determineSituation:()=>Mn,enrichConversation:()=>Ji,enrichPerson:()=>Ki,enrichPersonContext:()=>Gn,extractAutoTags:()=>Jn,generateSummary:()=>Bn,normPreview:()=>Eo});function Ji(e,t,o){if(!e)return e;let n=(e.messages||[]).filter(l=>!so.has(l.status)),i=Vi(t,e.profileUrl,o),s=Un(n,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=qn(n,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Mn(n,s,t),n.length>0){let l=n[n.length-1];e.lastMessageTime=l.time}if(n.length>0&&!e.initiatedBy){let l=n[0];l.sender===ke?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=$o(n,t),e.personContext=Gn(i),e.summary=Bn(e,t,i),e.autoTags=Jn(e,t,i);let a=Vn(e);return e.actionNeeded=a.action,e.actionDetail=a.detail,e.suggestedPriority=Hi(e),e}function qn(e,t,o){if(!e||e.length===0)return o?.title?Ht(o.title):null;let r=e.filter(n=>n.sender!==ke&&n.sender!=="Unknown"&&n.sender!=="").map(n=>n.text).join(" ");for(let[n,i]of Object.entries(On))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(r))return n}if(o?.title){let n=Ht(o.title);if(n)return n}return null}function Ht(e){if(!e)return null;for(let[t,o]of Object.entries(On))if(o.title){for(let r of o.title)if(r.test(e))return t}return null}function Mn(e,t,o){if(!e||e.length===0)return"no_messages";let r=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return Fn.test(r.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let n=[...e].reverse().find(i=>i.sender!==ke&&i.sender!=="Unknown");return Fn.test(n?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Un(e,t){if(!e||e.length===0)return"them";let o=[...e].map(n=>({m:n,t:Date.parse(n.time)})).filter(n=>Number.isFinite(n.t)).sort((n,i)=>i.t-n.t).map(n=>n.m),r=o.length>0?o:[...e].reverse();for(let n of r){let i=n.sender;if(i===ke)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function Bn(e,t,o){let r=e.messages||[];if(r.length===0)return null;let n=[],i=e.category,s=o?.title,a=o?.company,l=o?.location;i==="recruiter"&&a?n.push(`Recruiter from ${a}`):i==="hiring_manager"&&a?n.push(`Hiring manager at ${a}`):i==="founder"&&a?n.push(`Founder of ${a}`):i&&s?n.push(`${_o(i)}: ${et(s,40)}`):s?n.push(et(s,50)):n.push(t.split(" ")[0]);let u=r.filter(m=>m.sender!==ke&&m.sender!=="Unknown").map(m=>m.text).join(" "),c=Gi(u),f=Wi(u),d=Yi(u),p=[];return c&&p.push(c),d&&d!==l&&p.push(d),f&&p.push(f),p.length>0&&n.push(p.join(", ")),e.situation==="they_want_to_schedule_call"?n.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?n.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?n.push("needs reply"):e.conversationStatus==="awaiting_reply"&&n.push("waiting on them"),n.join(". ").replace(/\.\./g,".")}function Jn(e,t,o){let r=[],n=(e.messages||[]).filter(u=>!so.has(u.status)),i=n.map(u=>u.text).join(" "),s=n.filter(u=>u.sender!==ke&&u.sender!=="Unknown").map(u=>u.text).join(" "),a=Hn(s,o?.location);r.push(...a),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&r.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&r.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&r.push("remote"),/\b(hybrid)\b/i.test(i)&&r.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&r.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&r.push("java"),/\b(python)\b/i.test(i)&&r.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&r.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&r.push("backend"),/\b(full.?stack)\b/i.test(i)&&r.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&r.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&r.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&r.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&r.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&r.push("has-salary");let l=e.engagement||$o(n,t);return l.messageCount>=6&&r.push("active-thread"),l.theirCount===0&&l.ourCount>0&&r.push("no-response"),l.ourCount===0&&l.theirCount>0&&r.push("unanswered"),e.situation==="they_want_to_schedule_call"&&r.push("hot-lead"),(e.messages||[]).some(u=>io.has(u.status))&&r.push("has-draft"),[...new Set(r)]}function Hn(e,t){let o=[],r=["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"],n=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let s of r)i.includes(s)&&o.push(s.replace(/\s+/g,"-"));for(let[s,a]of n)i.includes(s)&&o.push(a);return o}function Vn(e){let{category:t,situation:o,conversationStatus:r}=e;if(e.dismissedAtPreview&&Eo(e.lastMessagePreview)===Eo(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let n=(e.messages||[]).find(i=>io.has(i.status));return n?n.status===ye.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:r==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:o==="no_messages"?{action:"none",detail:"No messages read yet."}:o==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:o==="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:`${_o(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:o==="active_conversation_needs_our_reply"||o==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function $o(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let o=0,r=0,n=0,i=!1,s=!1,a=e.map(l=>l.text).join(" ");for(let l of e)l.sender===ke?o++:l.sender==="Unknown"||l.sender===""?n++:r++;return i=/\b(job|role|position|opening)\b/i.test(a),s=/\$[\d,]+|\d+k|\d+\/hr/i.test(a),{messageCount:e.length,theirCount:r,ourCount:o,unknownCount:n,hasJob:i,hasSalary:s}}function Gn(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Hi(e){let{category:t,situation:o,engagement:r}=e;return o==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(o==="active_conversation_needs_our_reply"||o==="needs_our_reply")?r?.messageCount>=4?"high":"medium":t==="recruiter"&&o==="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 Vi(e,t,o){if(!o)return null;if(t&&o[t])return o[t];if(t){let n=xe(o,t,e);if(o[n])return o[n]}if(!e)return null;let r=Object.values(o).filter(n=>n.name===e);return r.length===1?r[0]:null}function Eo(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function _o(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function et(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Gi(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 o=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return o?o[1]:null}function Wi(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 Yi(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 Ki(e,t){if(!e)return e;if(e.categorySource!=="manual"){let r=Ht(e.title);r&&(e.category=r,e.categorySource=e.categorySource||"title")}zi(e),e.personSummary=Qi(e),e.personAutoTags=Xi(e);let o=Zi(e);return e.personActionNeeded=o.action,e.personActionDetail=o.detail,e.personPriorityManual||(e.personPriority=es(e)),e}function zi(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(o=>o.jobTitle).sort((o,r)=>(r.date||"").localeCompare(o.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 Qi(e){let t=[],o=e.category,r=e.title,n=e.company,i=e.location;if(o==="recruiter"&&n?t.push(`Recruiter at ${n}`):o==="hiring_manager"&&n?t.push(`Hiring manager at ${n}`):o==="founder"&&n?t.push(`Founder of ${n}`):r&&n?t.push(`${et(r,40)} at ${et(n,30)}`):r?t.push(et(r,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let s=new Date(e.connectionDate);if(!isNaN(s)){let a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${a[s.getMonth()]} ${s.getDate()}`)}}if(e.jobCount>0){let s=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(s+=` (last: ${et(e.lastJobTitle,30)}`,e.lastJobDate){let a=new Date(e.lastJobDate);isNaN(a)||(s+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()]} ${a.getDate()}`)}s+=")"}t.push(s)}return t.join(". ").replace(/\.\./g,".")||null}function Xi(e){let t=[],o=[e.title,e.company,e.location].filter(Boolean).join(" "),r=Hn("",e.location);return t.push(...r),e.category&&t.push(e.category),/\b(java)\b/i.test(o)&&!/javascript/i.test(o)&&t.push("java"),/\b(python)\b/i.test(o)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(o)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(o)&&t.push("backend"),/\b(full.?stack)\b/i.test(o)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(o)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(o)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(o)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(o)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(o)&&t.push("staffing"),[...new Set(t)]}function Zi(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:`${_o(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function es(e){let t=e.category;if(!t)return null;let o=ts(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&o?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&o?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function ts(e,t){if(!e.connectionDate)return!1;let o=new Date(e.connectionDate);if(isNaN(o))return!1;let r=new Date;return r.setDate(r.getDate()-t),o>=r}var On,Fn,Yn=me(async()=>{await lo();await Qe();On={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]}};Fn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var zn={};te(zn,{DEFAULT_PROFILE_INTERESTS:()=>Kn,computeFit:()=>rs,detectSectors:()=>ns});function ns(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),o=[];for(let[r,n]of Object.entries(os))n.some(i=>i.test(t))&&o.push(r);return o}function rs(e,t=Kn){if(!Array.isArray(e)||e.length===0)return 0;let o=i=>typeof i=="number"&&Number.isFinite(i)?i:0,r=Math.max(1,...Object.values(t||{}).map(o)),n=0;for(let i of e){let s=o(t&&t[i]);s>n&&(n=s)}return Math.min(1,n/r)}var os,Kn,Qn=me(()=>{os={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/]};Kn={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});Ue();import Pr from"puppeteer";import*as Vr from"fs";import{createGraphClient as oi,resolveToken as ni}from"@ilivemylife/graph-sdk";import{config as ri}from"dotenv";ri();var nn=ni()||process.env.TOKEN;nn||(console.error(`
|
|
242
242
|
[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.
|
|
243
243
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
244
244
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
245
|
-
`),process.exit(1));var $e=mr({token:To});var Ne=12e4;async function Fe(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await $e.askLifebot(o,e,{timeout:Ne});return Ne=Math.max(12e4,Ne*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Ne=Math.min(Ne*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Ne/1e3)}s...`);continue}throw n}}async function Ot(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await Fe(o)}async function pt(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Fe(o)}async function Qe(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Fe(o)}Ut();import{LIFEBOT_MESSAGE_TYPES as Kn}from"@ilivemylife/graph-sdk";je();await rt();async function nn(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function on(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function Br(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await nn(e,t));let c=0;for(let b=0;b<2;b++){let $=await e.evaluate(()=>document.body.scrollHeight);for(let N=1;N<=6;N++)await e.evaluate(U=>window.scrollTo(0,U),$*N/6),await w(900);let M=await e.evaluate(()=>document.body.scrollHeight);if(M===c)break;c=M}await w(800);let d=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(d=b.split("?")[0].replace(/\/+$/,""))}catch{}let u=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),$=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),M=A=>{let R=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(R)},N={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},U=document.querySelector("main");if(!U)return N;let C=[...Array.from(U.querySelectorAll("h1")),...Array.from(U.querySelectorAll("h2"))],j=Array.from(U.querySelectorAll("h2")),K=C.find(A=>{let R=A.textContent&&A.textContent.trim(),L=(R||"").replace(/\s*\(\d+\)$/,"").trim();return R&&R.length>1&&R.length<100&&!b.has(L)&&!$.has(L)}),Y=K?K.textContent.trim():null,W=K?K.parentElement:null;for(;W&&W!==U&&!Array.from(W.children).filter(R=>R.tagName==="P").some(R=>{let L=R.textContent&&R.textContent.trim();return L&&L.length>5&&!M(L)});)W=W.parentElement;let H=null,_=null,B=null,T=null;if(W&&W!==U){let A=Array.from(W.children).filter(L=>L.tagName==="P").filter(L=>{let ge=L.textContent&&L.textContent.trim();return ge&&ge.length>5&&!M(ge)});if(A[0]&&(H=A[0].textContent.trim()),A[1]){let L=A[1].textContent.trim().split(/\s*[·•]\s*/);_=L[0]||null,L.length>1&&(B=L.slice(1).join(" \xB7 "))}let R=Array.from(W.children).filter(L=>L.tagName==="DIV");for(let L=R.length-1;L>=0;L--){let ge=R[L].textContent&&R[L].textContent.trim();if(ge&&!(Y&&ge.startsWith(Y))&&(T=ge.split(/[·•]/)[0].trim(),T))break}}let F=null;if(W){let A=W.querySelectorAll("p, span, div");for(let R of A){let L=(R.textContent||"").trim().replace(/^[·•]\s*/,"");if(L==="1st"||L==="2nd"||L==="3rd"){F=L;break}}}let k=!!U.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),O=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),q=O&&O.src||null,I=U.textContent||"",G=null,ce=I.match(/(\d+\+?)\s+connections\b/i);ce&&(G=ce[1]+" connections");let ue=null,Ft=I.match(/(\d+)\s+mutual connection/i),ko=I.match(/and\s+(\d+)\s+other mutual/i),ar=I.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Ft?ue=parseInt(Ft[1],10):ko?ue=2+parseInt(ko[1],10):ar&&(ue=2);let xo=null,Eo=null,$o=j.find(A=>A.textContent&&A.textContent.trim()==="About");if($o){let A=$o.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let R=(A.textContent||"").trim();R=R.replace(/^About\s*/,"").trim();let L=R.match(/Top skills\s*(.+?)$/i);if(L){let qt=L[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(fr=>fr.trim()).filter(Boolean);qt.length>0&&qt.length<10&&(Eo=qt)}R=R.split(/\n?…\s*more/i)[0].trim(),R=R.split(/\n?\.\.\.\s*more/i)[0].trim(),R=R.split(/\bTop skills\b/i)[0].trim(),R=R.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),xo=R||null}}let Co=null,Ao=j.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(Ao){let A=Ao.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let R=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);R&&(Co=parseInt(R[1].replace(/,/g,""),10))}}let cr=[...new Set(j.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==Y).filter(A=>b.has(A)))],Ke=document.body.textContent||"",ur=/#OpenToWork\b/i.test(Ke)||/\bOpen to work\b/.test(Ke),dr=/#Hiring\b/i.test(Ke)||/\bI'?m hiring\b/i.test(Ke)||/\bWe are hiring\b/i.test(Ke);return{name:Y,title:H,location:T,currentCompany:_,currentSchool:B,connectionDegree:F,hasVerifiedBadge:k,photoUrl:q,connectionsLevel:G,mutualConnectionsCount:ue,followers:Co,openToWork:ur,hiring:dr,about:xo,topSkills:Eo,availableSections:cr}});console.log(`Viewed: ${u.name} - ${u.title}`);let p=null,m=null,h=null,g=null,y=null,S=null;if(r||n||s||i||a||l){let b=await Promise.resolve().then(()=>(tn(),en));r&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),n&&(m=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),s&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),i&&(g=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),a&&(y=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(S=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...u,profileUrl:t,resolvedUrl:d,...p!==null&&{experience:p},...m!==null&&{featured:m},...h!==null&&{education:h},...g!==null&&{skillsFull:g},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(f){console.error(`Error viewing profile ${t}:`,f.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(f.message||""))throw f;return null}}async function He(e,{detail:t=!1}={}){let o=()=>e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',s=d=>d&&!d.closest(n),i=d=>Array.from(document.querySelectorAll(d)).filter(s),a=i('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=i('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,f=i('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,c={pendingCount:a.length,pendingLabels:a.map(d=>d.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!f};return a.length>0?{status:"pending",debug:c}:l&&!f?{status:"connected",debug:c}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:c}:{status:"not_connected",debug:c}}),r=await o();return!r.debug.pendingCount&&!r.debug.hasMessageBtn&&!r.debug.hasConnectBtn&&(await w(1500),r=await o()),console.log(" DEBUG connection status:",JSON.stringify(r.debug)),t?r:r.status}async function zt(e){let t=null,o=await e.evaluate(()=>{let f=document.querySelector("h1")?.textContent?.trim();if(f&&!f.includes("notification"))return f;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(f=c.textContent?.trim(),f&&!f.includes("notification")))return f;let d=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(d)return d.textContent?.trim()||"";let u=document.title;return u&&u.includes("|")?u.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let f=await e.evaluate(()=>{let d=document.querySelectorAll('a[href*="custom-invite"]');return{count:d.length,labels:Array.from(d).map(u=>u.getAttribute("aria-label")?.slice(0,50))}});f.count>0&&console.log(` S0: ${f.count} custom-invite links: ${JSON.stringify(f.labels)}`),t=await e.evaluateHandle(d=>{let u=document.querySelectorAll('a[href*="custom-invite"]'),p=d.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of u){let g=h.getBoundingClientRect();if(g.width===0||g.height===0||h.closest(m))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},o);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(o){let f=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${f}"`);let c=await e.evaluate(u=>{let p=new RegExp("\\b"+u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(g=>{let y=g.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},f);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(u=>{let p=document.querySelectorAll("button[aria-label]"),m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',h=new RegExp("\\b"+u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of p){if(g.closest(m))continue;let y=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return g}return null},f);let d=t?.asElement?.()||null;if(d||await t?.dispose?.().catch(()=>{}),d)return console.log(" Found: button matching profile name"),{button:d,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let f=await e.evaluate(d=>(d.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();f.includes("invite")&&!f.includes(c)&&(console.log(` Skipping primary button: wrong person (${f})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",s=null;for(let f of r){let c=await e.evaluate((d,u)=>{let p=d.className.includes("muted"),m=d.className.includes("sticky-header")||d.className.includes("sticky"),h=d.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(d.getAttribute("aria-label")||"").toLowerCase(),y=g.includes("invite"),S=u?g.includes(u):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:S,ariaLabel:g}},f,n);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}s=f;break}}for(let f of r)f!==s&&await f.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,a=await e.$$('button[id*="profile-overflow-action"]');for(let f of a){let c=await e.evaluate(d=>{let u=d.getBoundingClientRect(),p=u.width>0&&u.height>0,m=d.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:m,top:u.top}},f);if(c.isVisible&&!c.isInStickyHeader){i=f,console.log(" Found More button by ID pattern (main)");break}}for(let f of a)f!==i&&await f.dispose().catch(()=>{});if(!i&&a.length>0&&(i=a[a.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 f=await e.evaluateHandle(()=>{let d=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",g=p.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!d)return null;let u=d.parentElement;for(let p=0;p<8&&u;p++){for(let m of u.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==d)return m;u=u.parentElement}return null});i=f?.asElement?.()||null,i||await f?.dispose?.().catch(()=>{}),i&&console.log(" Found More button by text (near profile actions)")}if(i)try{if(await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),i),await w(500),await e.evaluate(u=>u.click(),i),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!c){let u=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let h=m.querySelector('a[href*="custom-invite"]');if(h)return h;for(let g of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});c=u?.asElement?.()||null,c||await u?.dispose?.().catch(()=>{})}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};let d=await e.evaluate(()=>{let u=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let m of u)for(let h of m.querySelectorAll('[role="menuitem"], a, div')){let g=h.innerText?.trim();g&&g.length<40&&p.push(g)}return[...new Set(p)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(d)}`),await e.keyboard.press("Escape"),d.some(u=>/remove (your )?connection/i.test(u)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(f){console.log(" More dropdown click failed:",f.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(f=>{let c='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',d=(f||"").split(" ")[0].toLowerCase();for(let u of document.querySelectorAll("button[aria-label]")){if(u.closest(c))continue;let p=(u.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(p))continue;let m=u.getBoundingClientRect();if(!(m.width===0||m.height===0)){if(p.includes("invite")){if(d&&p.includes(d))return u;continue}if(p==="connect")return u}}return null},o||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Jr(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let o=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),s=o.tag==="DIV",i=(o.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(i))return console.log(` \u2717 Guard: refusing a non-connect control ("${o.ariaLabel}")`),"wrong_target";if(i.includes("invite")){let c=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(c&&!i.includes(c))return console.log(` \u2717 Identity guard: control is for someone else ("${o.ariaLabel}") \u2014 refusing to click (target: ${c})`),"wrong_target"}if(n){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await w(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else s?(await e.evaluate(c=>c.click(),t),await w(3e3)):(await e.evaluate(c=>c.click(),t),await w(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),f=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${f}`:` \u26A0 No modal after connect click \u2014 ${f}`),"success"}async function Vr(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await w(1500);let o=await zt(e);if(o){await e.evaluate(n=>n.click(),o),await w(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r)return await Ge(e,r)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Ge(e,t){let o='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',r=()=>e.evaluate(i=>{let a=l=>!!(l&&l.querySelector(i));return!(a(document)||a(document.querySelector("#interop-outlet")?.shadowRoot))},o),n=()=>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 a=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,o);return i=a?.asElement?.()||null,i||await a?.dispose?.().catch(()=>{}),i};for(let i=0;i<2;i++){try{await t.evaluate(a=>a.click())}catch{}if(await w(3e3),await n())return!1;if(await r())return!0;if(i===0){let a=await s();if(!a)return await r();t=a,await w(600)}}return await r()}async function Hr(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:s=!1}=o;if(!n){let a=ot();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let i=await Gr(e,t,o);return i.connectionSent&&!s&&Ct(t,r),i}async function Gr(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:s=!0,skipIfConnected:i=!0,excludeLocations:a=[]}=o,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let f=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
246
|
-
--- Connecting: ${f} ---`),a.length>0){let y=Q()[t]?.location;if(on(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),l.reason="excluded_location",l.profileInfo={location:y},l}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await nn(e,t),await w(2e3)),l.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"]),S=k=>{let O=(k||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(O)},E={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return E;let $=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],M=Array.from(b.querySelectorAll("h2")),N=$.find(k=>{let O=k.textContent&&k.textContent.trim();return O&&O.length>1&&O.length<100&&!y.has(O)&&O!=="0 notifications"}),U=N?N.textContent.trim():null,C=N?N.parentElement:null;for(;C&&C!==b&&!Array.from(C.children).filter(q=>q.tagName==="P").some(q=>{let I=q.textContent&&q.textContent.trim();return I&&I.length>5&&!S(I)});)C=C.parentElement;let j=null,K=null,Y=null;if(C&&C!==b){let k=Array.from(C.children),O=k.filter(I=>I.tagName==="P").filter(I=>{let G=I.textContent&&I.textContent.trim();return G&&G.length>5&&!S(G)});O[0]&&(j=O[0].textContent.trim()),O[1]&&(K=O[1].textContent.trim());let q=k.filter(I=>I.tagName==="DIV");for(let I=q.length-1;I>=0;I--){let G=q[I].textContent&&q[I].textContent.trim();if(G&&!(U&&G.startsWith(U))&&(Y=G.split(/[·•]/)[0].trim(),Y))break}}let W=null;if(C){let k=C.querySelectorAll("p, span, div");for(let O of k){let q=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(q==="1st"||q==="2nd"||q==="3rd"){W=q;break}}}let H=null,_=M.find(k=>k.textContent&&k.textContent.trim()==="About");if(_){let k=_.parentElement;for(;k&&k.tagName!=="SECTION";)k=k.parentElement;k&&(H=(k.textContent||"").trim().replace(/^About\s*/,"").trim()||null,H&&(H=H.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let B=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),T=B&&B.src||null,F=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:U,title:j,location:Y,about:H,company:K,connectionDegree:W,connectionsCount:null,mutualConnections:null,photoUrl:T,hasVerifiedBadge:F}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(l.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(a.length>0){let y=l.profileInfo?.location,S=Q()[t]?.location,E=y||S;if(on(E,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${E}`),l.reason="excluded_location",l;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await He(e,{detail:!0})).status==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await te(e);let u=await zt(e);if(u||await te(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),u=await zt(e)),u&&u.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!u){let y=await He(e,{detail:!0});return i&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=u.method;let p=await Jr(e,u.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await He(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await te(e),await w(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),S),await w(500),await S.click().catch(()=>e.evaluate(b=>b.click(),S)),await w(2e3);let E=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(E){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(M=>M.click(),E),await w(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),l.reason="premium_required",l;if(await He(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),l.reason="premium_required",l}catch(E){return console.log(" More dropdown failed:",E.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of y){let E=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!E)continue;let b=(E.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||E.querySelector('input[type="email"], input[name="email"]'))return!0;let $=E.querySelector('button[aria-label="Send without a note"]');if($&&($.disabled||$.getAttribute("aria-disabled")==="true"||($.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 w(500),l.reason="email_required",l}let h=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!h&&!g){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let E=S.querySelector('button[aria-label="Add a note"]'),b=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!E,sendWithout:!!b}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=S?.asElement?.()||null,h||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}}if(n)if(h&&r){if(console.log(" Adding personalized note..."),await h.click(),await w(1500),await e.$("div.modal-upsell")){let E=await Vr(e);return l.success=E,l.connectionSent=E,l.reason=E?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let E=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=r.replace("{name}",E);await S.type(b,{delay:20}),await w(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($)return await Ge(e,$)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=b,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(g)return console.log(" Sending without note..."),await Ge(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(h&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await Ge(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let y=g;if(y)return await Ge(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(u.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await te(e),await w(500);let S=await e.$$('button[id*="profile-overflow-action"]'),E=null;for(let b of S){let $=await e.evaluate(M=>{let N=M.getBoundingClientRect();return{visible:N.width>0&&N.height>0,inSticky:!!M.closest('.sticky-header, [class*="sticky"]')}},b);if($.visible&&!$.inSticky){E=b;break}}!E&&S.length>0&&(E=S[S.length-1]);for(let b of S)b!==E&&await b.dispose().catch(()=>{});if(E)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),E),await w(500),await E.click().catch(()=>e.evaluate($=>$.click(),E)),await w(2e3);let b=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(b){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(U=>U.click(),b),await w(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await He(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await He(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let N=await e.$('button[aria-label="Send without a note"]');if(N)return console.log(" Modal appeared via More dropdown, sending without note..."),await Ge(e,N)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(f){console.error(` \u2717 Error: ${f.message}`),l.reason="error",l.error=f.message;let c=f.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{l.fatal=!0}return l}}async function Qt(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:s=20,viewOnly:i=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:l=null,excludeLocations:f=[],source:c="unknown"}=o,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
247
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${
|
|
245
|
+
`),process.exit(1));var Ie=oi({token:nn});var Be=12e4;async function Je(e,{retries:t=2}={}){let o=process.env.NODE_EASY_APPLY_MAIN;if(!o||o.startsWith("YOUR_"))throw new Error('NODE_EASY_APPLY_MAIN is not configured in .env. Create a node in iLiveMyLife, add "assist" tag, and set the node ID in .env. See README.md for setup instructions.');for(let r=1;r<=t;r++)try{let n=await Ie.askLifebot(o,e,{timeout:Be});return Be=Math.max(12e4,Be*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Be=Math.min(Be*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Be/1e3)}s...`);continue}throw n}}async function to(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let o=`Job application form field "${e}" \u2014 reply with ONLY the value to fill in, nothing else. `;return t&&(t==="Enter a decimal number larger than 0.0"&&(t="Enter a decimal number larger than 0"),o+=`Additional info: ${t}`),await Je(o)}async function xt(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}async function it(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Je(o)}ro();import{LIFEBOT_MESSAGE_TYPES as Fr}from"@ilivemylife/graph-sdk";Ue();await Qe();async function Zn(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function Xn(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function is(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await Zn(e,t));let c=0;for(let b=0;b<2;b++){let v=await e.evaluate(()=>document.body.scrollHeight);for(let I=1;I<=6;I++)await e.evaluate(N=>window.scrollTo(0,N),v*I/6),await w(900);let L=await e.evaluate(()=>document.body.scrollHeight);if(L===c)break;c=L}await w(800);let f=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(f=b.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let b=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"]),v=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"]),L=$=>{let j=($||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(j)},I={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:[]},N=document.querySelector("main");if(!N)return I;let E=[...Array.from(N.querySelectorAll("h1")),...Array.from(N.querySelectorAll("h2"))],D=Array.from(N.querySelectorAll("h2")),K=E.find($=>{let j=$.textContent&&$.textContent.trim(),P=(j||"").replace(/\s*\(\d+\)$/,"").trim();return j&&j.length>1&&j.length<100&&!b.has(P)&&!v.has(P)}),B=K?K.textContent.trim():null,Y=K?K.parentElement:null;for(;Y&&Y!==N&&!Array.from(Y.children).filter(j=>j.tagName==="P").some(j=>{let P=j.textContent&&j.textContent.trim();return P&&P.length>5&&!L(P)});)Y=Y.parentElement;let G=null,_=null,J=null,T=null;if(Y&&Y!==N){let $=Array.from(Y.children).filter(P=>P.tagName==="P").filter(P=>{let Se=P.textContent&&P.textContent.trim();return Se&&Se.length>5&&!L(Se)});if($[0]&&(G=$[0].textContent.trim()),$[1]){let P=$[1].textContent.trim().split(/\s*[·•]\s*/);_=P[0]||null,P.length>1&&(J=P.slice(1).join(" \xB7 "))}let j=Array.from(Y.children).filter(P=>P.tagName==="DIV");for(let P=j.length-1;P>=0;P--){let Se=j[P].textContent&&j[P].textContent.trim();if(Se&&!(B&&Se.startsWith(B))&&(T=Se.split(/[·•]/)[0].trim(),T))break}}let O=null;if(Y){let $=Y.querySelectorAll("p, span, div");for(let j of $){let P=(j.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){O=P;break}}}let x=!!N.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),M=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),q=M&&M.src||null,R=N.textContent||"",W=null,ue=R.match(/(\d+\+?)\s+connections\b/i);ue&&(W=ue[1]+" connections");let de=null,Zt=R.match(/(\d+)\s+mutual connection/i),zo=R.match(/and\s+(\d+)\s+other mutual/i),zr=R.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Zt?de=parseInt(Zt[1],10):zo?de=2+parseInt(zo[1],10):zr&&(de=2);let Qo=null,Xo=null,Zo=D.find($=>$.textContent&&$.textContent.trim()==="About");if(Zo){let $=Zo.parentElement;for(;$&&$.tagName!=="SECTION";)$=$.parentElement;if($){let j=($.textContent||"").trim();j=j.replace(/^About\s*/,"").trim();let P=j.match(/Top skills\s*(.+?)$/i);if(P){let eo=P[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(ei=>ei.trim()).filter(Boolean);eo.length>0&&eo.length<10&&(Xo=eo)}j=j.split(/\n?…\s*more/i)[0].trim(),j=j.split(/\n?\.\.\.\s*more/i)[0].trim(),j=j.split(/\bTop skills\b/i)[0].trim(),j=j.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Qo=j||null}}let en=null,tn=D.find($=>$.textContent&&$.textContent.trim()==="Activity");if(tn){let $=tn.parentElement;for(;$&&$.tagName!=="SECTION";)$=$.parentElement;if($){let j=($.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);j&&(en=parseInt(j[1].replace(/,/g,""),10))}}let Qr=[...new Set(D.map($=>($.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter($=>$&&$.length>1&&$.length<60&&$!==B).filter($=>b.has($)))],rt=document.body.textContent||"",Xr=/#OpenToWork\b/i.test(rt)||/\bOpen to work\b/.test(rt),Zr=/#Hiring\b/i.test(rt)||/\bI'?m hiring\b/i.test(rt)||/\bWe are hiring\b/i.test(rt);return{name:B,title:G,location:T,currentCompany:_,currentSchool:J,connectionDegree:O,hasVerifiedBadge:x,photoUrl:q,connectionsLevel:W,mutualConnectionsCount:de,followers:en,openToWork:Xr,hiring:Zr,about:Qo,topSkills:Xo,availableSections:Qr}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,m=null,h=null,g=null,y=null,S=null;if(r||n||i||s||a||l){let b=await Promise.resolve().then(()=>(Tn(),_n));r&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),n&&(m=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),s&&(g=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),a&&(y=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(S=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...p!==null&&{experience:p},...m!==null&&{featured:m},...h!==null&&{education:h},...g!==null&&{skillsFull:g},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function tt(e,{detail:t=!1}={}){let o=()=>e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(n),s=f=>Array.from(document.querySelectorAll(f)).filter(i),a=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,u=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,c={pendingCount:a.length,pendingLabels:a.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!u};return a.length>0?{status:"pending",debug:c}:l&&!u?{status:"connected",debug:c}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:c}:{status:"not_connected",debug:c}}),r=await o();return!r.debug.pendingCount&&!r.debug.hasMessageBtn&&!r.debug.hasConnectBtn&&(await w(1500),r=await o()),console.log(" DEBUG connection status:",JSON.stringify(r.debug)),t?r:r.status}async function To(e){let t=null,o=await e.evaluate(()=>{let u=document.querySelector("h1")?.textContent?.trim();if(u&&!u.includes("notification"))return u;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(u=c.textContent?.trim(),u&&!u.includes("notification")))return u;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: "${o}"`),o){let u=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))}});u.count>0&&console.log(` S0: ${u.count} custom-invite links: ${JSON.stringify(u.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 h of d){let g=h.getBoundingClientRect();if(g.width===0||g.height===0||h.closest(m))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},o);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(o){let u=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${u}"`);let c=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(g=>{let y=g.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&p.test(y)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},u);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),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',h=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of p){if(g.closest(m))continue;let y=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return g}return null},u);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&&o){let u=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();u.includes("invite")&&!u.includes(c)&&(console.log(` Skipping primary button: wrong person (${u})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let n=o?o.split(" ")[0].toLowerCase():"",i=null;for(let u of r){let c=await e.evaluate((f,d)=>{let p=f.className.includes("muted"),m=f.className.includes("sticky-header")||f.className.includes("sticky"),h=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(f.getAttribute("aria-label")||"").toLowerCase(),y=g.includes("invite"),S=d?g.includes(d):!0;return{isMuted:p,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:S,ariaLabel:g}},u,n);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}i=u;break}}for(let u of r)u!==i&&await u.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let u of a){let c=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}},u);if(c.isVisible&&!c.isInStickyHeader){s=u,console.log(" Found More button by ID pattern (main)");break}}for(let u of a)u!==s&&await u.dispose().catch(()=>{});if(!s&&a.length>0&&(s=a[a.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let u=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(p=>{let m=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",g=p.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.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});s=u?.asElement?.()||null,s||await u?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),s),await w(500),await e.evaluate(d=>d.click(),s),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!c){let d=await e.evaluateHandle(()=>{let p=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of p){let h=m.querySelector('a[href*="custom-invite"]');if(h)return h;for(let g of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});c=d?.asElement?.()||null,c||await d?.dispose?.().catch(()=>{})}if(c)return console.log(" Found: More dropdown"),{button:c,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 h of m.querySelectorAll('[role="menuitem"], a, div')){let g=h.innerText?.trim();g&&g.length<40&&p.push(g)}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(u){console.log(" More dropdown click failed:",u.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(u=>{let c='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(u||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(c))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},o||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function ss(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let o=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),n=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV",s=(o.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${o.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let c=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(c&&!s.includes(c))return console.log(` \u2717 Identity guard: control is for someone else ("${o.ariaLabel}") \u2014 refusing to click (target: ${c})`),"wrong_target"}if(n){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 w(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await w(3e3)):(await e.evaluate(c=>c.click(),t),await w(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function ls(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await w(1500);let o=await To(e);if(o){await e.evaluate(n=>n.click(),o),await w(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r)return await ot(e,r)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function ot(e,t){let o='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',r=()=>e.evaluate(s=>{let a=l=>!!(l&&l.querySelector(s));return!(a(document)||a(document.querySelector("#interop-outlet")?.shadowRoot))},o),n=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let a=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,o);return s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(a=>a.click())}catch{}if(await w(3e3),await n())return!1;if(await r())return!0;if(s===0){let a=await i();if(!a)return await r();t=a,await w(600)}}return await r()}async function as(e,t,o={}){let{source:r="unknown",skipQuotaGate:n=!1,skipQuotaRecord:i=!1}=o;if(!n){let a=ut();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let s=await cs(e,t,o);return s.connectionSent&&!i&&Pt(t,r),s}async function cs(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:a=[]}=o,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
246
|
+
--- Connecting: ${u} ---`),a.length>0){let y=Q()[t]?.location;if(Xn(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),l.reason="excluded_location",l.profileInfo={location:y},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await oe(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await Zn(e,t),await w(2e3)),process.env.LINKEDIN_DISCOVERY==="1")try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(go(),Rn)),{recordDiscoveredEdges:C}=await Promise.resolve().then(()=>(Jt(),Pn)),{detectCategoryFromTitle:b}=await Yn().then(()=>Wn),{detectSectors:v}=await Promise.resolve().then(()=>(Qn(),zn)),L=S(t)||t,I=await y(e,{seedUrl:L}),N=I.map(E=>{let D=E.headline?b(E.headline):null;return{url:E.url,seedUrl:L,block:E.block,rank:E.rank,name:E.name,headline:E.headline,categories:D?[D]:[],sectors:v(E.headline||"")}});C(N),I.length&&console.log(` \xB7 discovery: harvested ${I.length} related profiles`)}catch(y){process.env.LINKEDIN_DISCOVERY_DEBUG==="1"&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}l.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"]),S=x=>{let M=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(M)},C={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return C;let v=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],L=Array.from(b.querySelectorAll("h2")),I=v.find(x=>{let M=x.textContent&&x.textContent.trim();return M&&M.length>1&&M.length<100&&!y.has(M)&&M!=="0 notifications"}),N=I?I.textContent.trim():null,E=I?I.parentElement:null;for(;E&&E!==b&&!Array.from(E.children).filter(q=>q.tagName==="P").some(q=>{let R=q.textContent&&q.textContent.trim();return R&&R.length>5&&!S(R)});)E=E.parentElement;let D=null,K=null,B=null;if(E&&E!==b){let x=Array.from(E.children),M=x.filter(R=>R.tagName==="P").filter(R=>{let W=R.textContent&&R.textContent.trim();return W&&W.length>5&&!S(W)});M[0]&&(D=M[0].textContent.trim()),M[1]&&(K=M[1].textContent.trim());let q=x.filter(R=>R.tagName==="DIV");for(let R=q.length-1;R>=0;R--){let W=q[R].textContent&&q[R].textContent.trim();if(W&&!(N&&W.startsWith(N))&&(B=W.split(/[·•]/)[0].trim(),B))break}}let Y=null;if(E){let x=E.querySelectorAll("p, span, div");for(let M of x){let q=(M.textContent||"").trim().replace(/^[·•]\s*/,"");if(q==="1st"||q==="2nd"||q==="3rd"){Y=q;break}}}let G=null,_=L.find(x=>x.textContent&&x.textContent.trim()==="About");if(_){let x=_.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;x&&(G=(x.textContent||"").trim().replace(/^About\s*/,"").trim()||null,G&&(G=G.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let J=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),T=J&&J.src||null,O=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:N,title:D,location:B,about:G,company:K,connectionDegree:Y,connectionsCount:null,mutualConnections:null,photoUrl:T,hasVerifiedBadge:O}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(l.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(a.length>0){let y=l.profileInfo?.location,S=Q()[t]?.location,C=y||S;if(Xn(C,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${C}`),l.reason="excluded_location",l;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await tt(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await oe(e);let d=await To(e);if(d||await oe(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),d=await To(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let y=await tt(e,{detail:!0});return s&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=d.method;let p=await ss(e,d.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await tt(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await oe(e),await w(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),S),await w(500),await S.click().catch(()=>e.evaluate(b=>b.click(),S)),await w(2e3);let C=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(C){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(L=>L.click(),C),await w(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),l.reason="premium_required",l;if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),l.reason="premium_required",l}catch(C){return console.log(" More dropdown failed:",C.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of y){let C=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!C)continue;let b=(C.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||C.querySelector('input[type="email"], input[name="email"]'))return!0;let v=C.querySelector('button[aria-label="Send without a note"]');if(v&&(v.disabled||v.getAttribute("aria-disabled")==="true"||(v.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 w(500),l.reason="email_required",l}let h=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!h&&!g){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let C=S.querySelector('button[aria-label="Add a note"]'),b=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!C,sendWithout:!!b}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=S?.asElement?.()||null,h||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}}if(n)if(h&&r){if(console.log(" Adding personalized note..."),await h.click(),await w(1500),await e.$("div.modal-upsell")){let C=await ls(e);return l.success=C,l.connectionSent=C,l.reason=C?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let C=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=r.replace("{name}",C);await S.type(b,{delay:20}),await w(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v)return await ot(e,v)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=b,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(g)return console.log(" Sending without note..."),await ot(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(h&&!r){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let y=g;if(y)return await ot(e,y)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await oe(e),await w(500);let S=await e.$$('button[id*="profile-overflow-action"]'),C=null;for(let b of S){let v=await e.evaluate(L=>{let I=L.getBoundingClientRect();return{visible:I.width>0&&I.height>0,inSticky:!!L.closest('.sticky-header, [class*="sticky"]')}},b);if(v.visible&&!v.inSticky){C=b;break}}!C&&S.length>0&&(C=S[S.length-1]);for(let b of S)b!==C&&await b.dispose().catch(()=>{});if(C)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),C),await w(500),await C.click().catch(()=>e.evaluate(v=>v.click(),C)),await w(2e3);let b=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(b){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(N=>N.click(),b),await w(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await tt(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await tt(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let I=await e.$('button[aria-label="Send without a note"]');if(I)return console.log(" Modal appeared via More dropdown, sending without note..."),await ot(e,I)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(u){console.error(` \u2717 Error: ${u.message}`),l.reason="error",l.error=u.message;let c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{l.fatal=!0}return l}}async function Ro(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:l=null,excludeLocations:u=[],source:c="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
247
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!s){let p=dt();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(`
|
|
248
248
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
249
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=
|
|
250
|
-
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),
|
|
251
|
-
\u26A0 ${
|
|
252
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!i){let p=nt();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}await rt();je();async function rn(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,s=null;for(let d of r)if(n=document.querySelector(d),n){s=d;break}if(!n){let d=document.querySelector("li.scaffold-layout__list-item");if(d){let u=d.parentElement;for(;u&&u!==document.body;){if(u.scrollHeight>u.clientHeight){n=u,s="parent of li.scaffold-layout__list-item";break}u=u.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let i=n.scrollTop,a=300,l=300,f=50,c=0;for(;c<f&&(n.scrollBy(0,a),await new Promise(d=>setTimeout(d,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)c++;return{found:!0,usedSelector:s,initialScroll:i,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:c}},t)}async function sn(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let i=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let l=a.getAttribute("href").split("?")[0],f=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),c=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),u=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:i,applyType:i?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:f,companyName:c,location:d,salary:u||null,jobLink:i?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function ln(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await w(2e3),t.success}async function Xt(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let n=e.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function an(e,t,o,r){for(let n of t){await Xt(e,r)&&(await te(e),await w(2e3));let i=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!i){let l=n.id?.match(/\d+/)?.[0];l&&(i=await e.$(`a[href*="/jobs/view/${l}/"]`),i&&(a="href"))}if(i){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let l=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(u=>u.scrollIntoView({block:"center"}),i),await w(300),await i.click(),await w(1500);let f=!1;for(let u=0;u<8;u++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){f=!0;break}await w(500)}if(!f){await e.evaluate(u=>u.click(),i),await w(1500);for(let u=0;u<6;u++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){f=!0;break}await w(500)}f||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let c=await e.evaluate(()=>{let u=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of u)for(let m of p.querySelectorAll("button")){let h=m.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return m.click(),h}return null});c&&console.log(` Dismissed popup before processing (${c})`);let{keepGoing:d}=await o(e,n);if(!d)return{keepGoing:!1}}else{let l=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${l})`)}}return{keepGoing:!0}}async function cn(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let i=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(i)return{name:a?.textContent?.trim()||i.textContent?.trim(),profileUrl:i.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let i=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(i)return{name:r.textContent?.trim(),profileUrl:i.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let i=n.querySelector('a[href*="/in/"]');if(i)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||i.textContent?.trim(),profileUrl:i.href?.split("?")[0],source:"people_section"}}let s=t.querySelectorAll('a[href*="/in/"]');for(let i of s){let a=i.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:i.href?.split("?")[0],source:"details_link"}}return null})}async function un(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},s=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let G of s){let ce=G.querySelector(".job-criteria__subheader")?.textContent?.trim(),ue=G.querySelector(".job-criteria__text")?.textContent?.trim();ce&&ue&&(n[ce.toLowerCase()]=ue)}let i=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let G of i)new RegExp("\\b"+G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(G.replace(/\\\+/g,"+"));let f=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,d=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,u=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=u?.innerText?.trim()||null,h=(u?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",E=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,b=y.match(/(\d[\d,]*)\s+applicant/i),$=b?parseInt(b[1].replace(/,/g,"")):null,M=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),N=Array.from(M).map(G=>G.innerText?.trim()?.replace(/\s+/g," ")),C=N.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,j=N.join(" ")+" "+y,K=/\bremote\b/i.test(j)?"remote":/\bhybrid\b/i.test(j)?"hybrid":/\bon-?site\b/i.test(j)?"onsite":null,Y=/\bcontract\b/i.test(j)?"contract":/\bfull-?time\b/i.test(j)?"full-time":/\bpart-?time\b/i.test(j)?"part-time":/\bfreelance\b/i.test(j)?"freelance":/\btemporary\b/i.test(j)?"temporary":null,H=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",B=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",T=(H+" "+r+" "+B).toLowerCase(),F=H.toLowerCase(),k=[];/\bremote\b/.test(T)&&k.push("remote"),/\bhybrid\b/.test(T)&&k.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(T)&&k.push("onsite"),(k.length===0||!k.includes("remote")&&!k.includes("hybrid")&&!k.includes("onsite"))&&/remote/i.test(B)&&k.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(F)&&k.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(F)&&k.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(F)&&!k.includes("managerial")&&k.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(F)?k.push("junior"):/\b(senior|sr\.?)\b/i.test(F)?k.push("senior"):/\b(staff|principal|distinguished)\b/i.test(F)?k.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(F)?k.push("executive"):/\b(lead|team lead)\b/i.test(F)&&k.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(T)&&k.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(T)&&k.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(T)&&k.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(T)&&k.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(T)&&k.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(T)&&k.push("mobile"),/\b(architect)\b/i.test(F)&&k.push("architect"),/\b(consultant|consulting)\b/i.test(F)&&k.push("consultant");let O=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(O)||/\bcontract\b/i.test(T))&&k.push("contract"),/full.?time|permanent/i.test(O)&&k.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(B)&&k.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(B)&&k.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&k.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:d,companyName:p,companyUrl:h?h.startsWith("/")?"https://www.linkedin.com"+h:h:null,aboutCompany:f,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:E,applicantCount:$,companySize:C,workplaceType:K,contractType:Y,techStack:[...new Set(a)],jobTags:[...new Set(k)]}})}import"dotenv/config";import*as ne from"fs";import*as ee from"path";import{fileURLToPath as Wr}from"url";var Yr=Wr(import.meta.url),Kr=ee.dirname(ee.dirname(Yr)),Ie=process.env.DATA_DIR?ee.resolve(process.env.DATA_DIR,"market-research"):ee.join(Kr,"market-research"),dn=ee.join(Ie,"scouted-jobs.json"),Qi=ee.join(Ie,"discovered-people.json"),Xi=ee.join(Ie,"visit-log.json"),fn=ee.join(Ie,"companies.json"),pn=ee.join(Ie,"job-decisions.json");function Zt(){ne.existsSync(Ie)||ne.mkdirSync(Ie,{recursive:!0})}function eo(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ne.writeFileSync(r,o);for(let n=0;n<3;n++)try{ne.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function to(e){try{if(ne.existsSync(e))return JSON.parse(ne.readFileSync(e,"utf-8"))}catch{}return null}function mn(){at=null,ct=null,Qr=null,ut=null,Zr=null}var at=null;function zr(){return at||(at=to(dn)||{},at)}function hn(e,t){if(!e)return;Zt();let o=zr(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,s]of Object.entries(t))s!=null&&(o[e][n]=s);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{eo(dn,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var ct=null;function yn(){return ct||(ct=to(pn)||{},ct)}function We(e,t,o={}){if(!e||!t)return;Zt();let r=yn(),n=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=n,o.reason&&(r[e].reason=o.reason),o.score!=null&&(r[e].score=o.score),o.source&&(r[e].source=o.source)):r[e]={status:t,decidedAt:n,updatedAt:n,reason:o.reason||null,score:o.score??null,source:o.source||null};try{eo(pn,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function gn(e){return yn()[e]||null}var Qr=null;var ut=null;function Xr(){return ut||(ut=to(fn)||{},ut)}function oo(e,t){if(!e)return;Zt();let o=Xr(),r=new Date().toISOString().slice(0,10);if(o[e]){let n=o[e];t.name&&(n.name=t.name),t.about&&(n.about=t.about),t.size&&(n.size=t.size),t.industries&&(n.industries=t.industries),t.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(t.jobId)||n.jobIds.push(t.jobId)),t.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(t.recruiterUrl)||n.recruiterUrls.push(t.recruiterUrl)),n.lastSeen=r,n.jobCount=n.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{eo(fn,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var Zr=null;import"dotenv/config";import*as x from"fs";import*as uo from"os";import*as D from"path";import{fileURLToPath as xs}from"url";var so={};Ee(so,{NAME:()=>ts,VERSION:()=>es,up:()=>rs});import*as re from"fs";import*as _t from"path";var es=1,ts="normalize-jobs-and-questions",os=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],ns=50;function no(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function ro(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{re.writeFileSync(r,o)}catch(n){try{re.unlinkSync(r)}catch{}throw n}try{re.renameSync(r,e)}catch(n){try{re.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function rs(e,t){let o=_t.join(e,"jobs.json"),r=_t.join(t,"scouted-jobs.json"),n=_t.join(e,"application-questions.json"),s=no(o)||{},i=no(r)||{},a=0,l=[];for(let c of Object.keys(s)){if(!i[c])continue;let d=i[c],u=s[c];for(let p of os)d[p]!=null&&u[p]==null&&(u[p]=d[p]);l.push(c),a++}a>0?(ro(o,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=no(n);if(f&&Array.isArray(f.applications)){let c={},d=0;for(let u of f.applications){let p=u.jobId||"unknown";c[p]||(c[p]={applications:[]});let m=(u.questions||[]).map(h=>{let g={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=ns?g.options=h.options:(g.optionsOmitted=!0,d++)),h.page&&(g.page=h.page),h.wasPreFilled&&(g.wasPreFilled=!0),h.wasRetry&&(g.wasRetry=!0),g});c[p].applications.push({applicationId:u.applicationId,date:u.date,result:u.result||"submitted",formPages:u.formPages||null,duration:u.duration||null,retries:u.retries||0,failedField:u.failedField||null,questionCount:u.questionCount||m.length,questions:m})}ro(n,c),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let c of l)delete i[c];ro(r,i),console.log(` Phase 3: Removed ${l.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 io={};Ee(io,{NAME:()=>is,VERSION:()=>ss,up:()=>cs});import*as se from"fs";import*as bn from"path";var ss=2,is="reset-unread-flags";function ls(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function as(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{se.writeFileSync(r,o)}catch(n){try{se.unlinkSync(r)}catch{}throw n}try{se.renameSync(r,e)}catch(n){try{se.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function cs(e){let t=bn.join(e,"conversations.json"),o=ls(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}as(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var lo={};Ee(lo,{NAME:()=>ds,VERSION:()=>us,up:()=>ys});import*as ie from"fs";import*as wn from"path";var us=3,ds="recompute-last-message-by",fs=new Set(["draft","confirmed","rejected","needs_review"]);function ps(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function ms(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ie.writeFileSync(r,o)}catch(n){try{ie.unlinkSync(r)}catch{}throw n}try{ie.renameSync(r,e)}catch(n){try{ie.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}function hs(e,t){if(!e||e.length===0)return"them";let o=e.filter(s=>!fs.has(s.status));if(o.length===0)return"them";let r=o.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),n=r.length>0?r:[...o].reverse();for(let s of n){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function ys(e){let t=wn.join(e,"conversations.json"),o=ps(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.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 n=0,s=0,i=0;for(let a of Object.keys(o)){let l=o[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,s++);let f=Array.isArray(l.messages)?l.messages:[],c=hs(f,r),d=c==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==c&&i++,l.lastMessageBy=c,l.conversationStatus=d,n++}if(n===0){console.log(" No conversations to recompute.");return}ms(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} 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 ao={};Ee(ao,{NAME:()=>bs,VERSION:()=>gs,up:()=>ks});import*as le from"fs";import*as Sn from"path";var gs=4,bs="split-connection-timestamps",ws=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ss(e){if(!le.existsSync(e))return null;let t=le.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function vs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{le.writeFileSync(r,o)}catch(n){try{le.unlinkSync(r)}catch{}throw n}try{le.renameSync(r,e)}catch(n){try{le.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function ks(e){let t=Sn.join(e,"people.json"),o=Ss(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let s of Object.keys(o)){let i=o[s];!i||typeof i!="object"||(n++,ws.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}vs(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await rt();var Es=xs(import.meta.url),$s=D.dirname(Es),Cs=D.dirname(D.dirname($s));function As(e){return e&&(e==="~"?uo.homedir():e.startsWith("~/")||e.startsWith("~\\")?D.join(uo.homedir(),e.slice(2)):e)}var de=process.env.DATA_DIR?D.resolve(As(process.env.DATA_DIR)):Cs,Le=D.join(de,"collected-profiles"),De=D.join(de,"market-research"),X=D.join(de,".schema-version"),vn=[D.join(Le,".schema-version"),D.join(De,".schema-version")],ve=4,ye=[{version:1,module:so},{version:2,module:io},{version:3,module:lo},{version:4,module:ao}];(function(){ye.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of ye){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=ye.length?ye[ye.length-1].version:0;if(o!==ve)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${ve}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<ye.length;r++){let n=r+1;if(ye[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${ye[r].version}`)}})();function $n(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
249
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=Dt(m.profileUrl);if(h==="pending"||h==="connected"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${h})`),h==="pending"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,l&&await l(m,f,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${m.name||m.profileUrl}`);let g=null;if(s){let y=await is(e,m.profileUrl);y?(Ce(m.profileUrl,{...y,source:c}),f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,g={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=ut();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(g=await as(e,m.profileUrl,{message:r,useCustomMessage:n,excludeLocations:u,source:c,skipQuotaGate:!0}),g.success)f.connectionsSent++;else switch(g.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(g?.fatal){console.log(`
|
|
250
|
+
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(d++,d>=3){console.log(`
|
|
251
|
+
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(g&&g.reason&&(jt(m.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),g.resolvedUrl&&Lt(m.profileUrl,g.resolvedUrl),Ke(m.profileUrl,{source:c||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:g.reason})),l&&await l(m,f,g),p<t.length-1){let y=a+Math.random()*2e3;await w(y)}}if(console.log(`
|
|
252
|
+
=== 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}`),!s){let p=dt();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return f}await Qe();Ue();async function er(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,i=null;for(let f of r)if(n=document.querySelector(f),n){i=f;break}if(!n){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let d=f.parentElement;for(;d&&d!==document.body;){if(d.scrollHeight>d.clientHeight){n=d,i="parent of li.scaffold-layout__list-item";break}d=d.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,a=300,l=300,u=50,c=0;for(;c<u&&(n.scrollBy(0,a),await new Promise(f=>setTimeout(f,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)c++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:c}},t)}async function tr(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let s=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let l=a.getAttribute("href").split("?")[0],u=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),c=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:s,applyType:s?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:u,companyName:c,location:f,salary:d||null,jobLink:s?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function or(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await w(2e3),t.success}async function Io(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let n=e.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function nr(e,t,o,r){for(let n of t){await Io(e,r)&&(await oe(e),await w(2e3));let s=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!s){let l=n.id?.match(/\d+/)?.[0];l&&(s=await e.$(`a[href*="/jobs/view/${l}/"]`),s&&(a="href"))}if(s){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let l=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");await e.evaluate(d=>d.scrollIntoView({block:"center"}),s),await w(300),await s.click(),await w(1500);let u=!1;for(let d=0;d<8;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){u=!0;break}await w(500)}if(!u){await e.evaluate(d=>d.click(),s),await w(1500);for(let d=0;d<6;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==l){u=!0;break}await w(500)}u||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let c=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of d)for(let m of p.querySelectorAll("button")){let h=m.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return m.click(),h}return null});c&&console.log(` Dismissed popup before processing (${c})`);let{keepGoing:f}=await o(e,n);if(!f)return{keepGoing:!1}}else{let l=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${l})`)}}return{keepGoing:!0}}async function rr(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:a?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let a=s.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function ir(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let W of i){let ue=W.querySelector(".job-criteria__subheader")?.textContent?.trim(),de=W.querySelector(".job-criteria__text")?.textContent?.trim();ue&&de&&(n[ue.toLowerCase()]=de)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],a=[];for(let W of s)new RegExp("\\b"+W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(W.replace(/\\\+/g,"+"));let u=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,d=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=d?.innerText?.trim()||null,h=(d?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",C=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,b=y.match(/(\d[\d,]*)\s+applicant/i),v=b?parseInt(b[1].replace(/,/g,"")):null,L=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),I=Array.from(L).map(W=>W.innerText?.trim()?.replace(/\s+/g," ")),E=I.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,D=I.join(" ")+" "+y,K=/\bremote\b/i.test(D)?"remote":/\bhybrid\b/i.test(D)?"hybrid":/\bon-?site\b/i.test(D)?"onsite":null,B=/\bcontract\b/i.test(D)?"contract":/\bfull-?time\b/i.test(D)?"full-time":/\bpart-?time\b/i.test(D)?"part-time":/\bfreelance\b/i.test(D)?"freelance":/\btemporary\b/i.test(D)?"temporary":null,G=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",J=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",T=(G+" "+r+" "+J).toLowerCase(),O=G.toLowerCase(),x=[];/\bremote\b/.test(T)&&x.push("remote"),/\bhybrid\b/.test(T)&&x.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(T)&&x.push("onsite"),(x.length===0||!x.includes("remote")&&!x.includes("hybrid")&&!x.includes("onsite"))&&/remote/i.test(J)&&x.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(O)&&x.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(O)&&x.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(O)&&!x.includes("managerial")&&x.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(O)?x.push("junior"):/\b(senior|sr\.?)\b/i.test(O)?x.push("senior"):/\b(staff|principal|distinguished)\b/i.test(O)?x.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(O)?x.push("executive"):/\b(lead|team lead)\b/i.test(O)&&x.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(T)&&x.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(T)&&x.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(T)&&x.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(T)&&x.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(T)&&x.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(T)&&x.push("mobile"),/\b(architect)\b/i.test(O)&&x.push("architect"),/\b(consultant|consulting)\b/i.test(O)&&x.push("consultant");let M=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(M)||/\bcontract\b/i.test(T))&&x.push("contract"),/full.?time|permanent/i.test(M)&&x.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(J)&&x.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(J)&&x.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&x.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:p,companyUrl:h?h.startsWith("/")?"https://www.linkedin.com"+h:h:null,aboutCompany:u,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:C,applicantCount:v,companySize:E,workplaceType:K,contractType:B,techStack:[...new Set(a)],jobTags:[...new Set(x)]}})}Jt();import"dotenv/config";import*as A from"fs";import*as qo from"os";import*as F from"path";import{fileURLToPath as js}from"url";var Lo={};te(Lo,{NAME:()=>ds,VERSION:()=>us,up:()=>ms});import*as ie from"fs";import*as Vt from"path";var us=1,ds="normalize-jobs-and-questions",fs=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],ps=50;function Do(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function jo(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ie.writeFileSync(r,o)}catch(n){try{ie.unlinkSync(r)}catch{}throw n}try{ie.renameSync(r,e)}catch(n){try{ie.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function ms(e,t){let o=Vt.join(e,"jobs.json"),r=Vt.join(t,"scouted-jobs.json"),n=Vt.join(e,"application-questions.json"),i=Do(o)||{},s=Do(r)||{},a=0,l=[];for(let c of Object.keys(i)){if(!s[c])continue;let f=s[c],d=i[c];for(let p of fs)f[p]!=null&&d[p]==null&&(d[p]=f[p]);l.push(c),a++}a>0?(jo(o,i),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Do(n);if(u&&Array.isArray(u.applications)){let c={},f=0;for(let d of u.applications){let p=d.jobId||"unknown";c[p]||(c[p]={applications:[]});let m=(d.questions||[]).map(h=>{let g={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=ps?g.options=h.options:(g.optionsOmitted=!0,f++)),h.page&&(g.page=h.page),h.wasPreFilled&&(g.wasPreFilled=!0),h.wasRetry&&(g.wasRetry=!0),g});c[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})}jo(n,c),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let c of l)delete s[c];jo(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var No={};te(No,{NAME:()=>ys,VERSION:()=>hs,up:()=>ws});import*as se from"fs";import*as sr from"path";var hs=2,ys="reset-unread-flags";function gs(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function bs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{se.writeFileSync(r,o)}catch(n){try{se.unlinkSync(r)}catch{}throw n}try{se.renameSync(r,e)}catch(n){try{se.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function ws(e){let t=sr.join(e,"conversations.json"),o=gs(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}bs(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Po={};te(Po,{NAME:()=>ks,VERSION:()=>Ss,up:()=>Es});import*as le from"fs";import*as lr from"path";var Ss=3,ks="recompute-last-message-by",vs=new Set(["draft","confirmed","rejected","needs_review"]);function xs(e){return le.existsSync(e)?JSON.parse(le.readFileSync(e,"utf-8")):null}function Cs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{le.writeFileSync(r,o)}catch(n){try{le.unlinkSync(r)}catch{}throw n}try{le.renameSync(r,e)}catch(n){try{le.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function As(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!vs.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function Es(e){let t=lr.join(e,"conversations.json"),o=xs(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.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 n=0,i=0,s=0;for(let a of Object.keys(o)){let l=o[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let u=Array.isArray(l.messages)?l.messages:[],c=As(u,r),f=c==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==c&&s++,l.lastMessageBy=c,l.conversationStatus=f,n++}if(n===0){console.log(" No conversations to recompute.");return}Cs(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Fo={};te(Fo,{NAME:()=>_s,VERSION:()=>$s,up:()=>Ds});import*as ae from"fs";import*as ar from"path";var $s=4,_s="split-connection-timestamps",Ts=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Rs(e){if(!ae.existsSync(e))return null;let t=ae.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Is(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ae.writeFileSync(r,o)}catch(n){try{ae.unlinkSync(r)}catch{}throw n}try{ae.renameSync(r,e)}catch(n){try{ae.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function Ds(e){let t=ar.join(e,"people.json"),o=Rs(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,Ts.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Is(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Qe();Jt();var Ls=js(import.meta.url),Ns=F.dirname(Ls),Ps=F.dirname(F.dirname(Ns));function Fs(e){return e&&(e==="~"?qo.homedir():e.startsWith("~/")||e.startsWith("~\\")?F.join(qo.homedir(),e.slice(2)):e)}var fe=process.env.DATA_DIR?F.resolve(Fs(process.env.DATA_DIR)):Ps,qe=F.join(fe,"collected-profiles"),Me=F.join(fe,"market-research"),X=F.join(fe,".schema-version"),cr=[F.join(qe,".schema-version"),F.join(Me,".schema-version")],_e=4,we=[{version:1,module:Lo},{version:2,module:No},{version:3,module:Po},{version:4,module:Fo}];(function(){we.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of we){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=we.length?we[we.length-1].version:0;if(o!==_e)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${_e}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<we.length;r++){let n=r+1;if(we[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${we[r].version}`)}})();function pr(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
253
253
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
254
|
-
`),process.exit(1));try{
|
|
255
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
256
|
-
`),process.exit(1))}let e;try{e=
|
|
257
|
-
[FATAL] DATA_DIR (${
|
|
254
|
+
`),process.exit(1));try{A.mkdirSync(fe,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
255
|
+
[FATAL] Cannot create DATA_DIR (${fe}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
256
|
+
`),process.exit(1))}let e;try{e=A.statSync(fe)}catch(t){console.error(`
|
|
257
|
+
[FATAL] DATA_DIR (${fe}) is not accessible: ${t.message}
|
|
258
258
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
259
|
-
[FATAL] DATA_DIR (${
|
|
260
|
-
`),process.exit(1));for(let t of[
|
|
259
|
+
[FATAL] DATA_DIR (${fe}) 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.
|
|
260
|
+
`),process.exit(1));for(let t of[qe,Me]){let o;try{o=A.lstatSync(t)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
|
|
261
261
|
[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.
|
|
262
|
-
`),process.exit(1))}}var
|
|
263
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
262
|
+
`),process.exit(1))}}var Oe=F.join(fe,".migration-lock");function Os(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return A.writeFileSync(Oe,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse(A.readFileSync(Oe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(s){s.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}r&&i<n&&(console.error(`
|
|
263
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Oe}
|
|
264
264
|
`),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.
|
|
265
|
-
`),process.exit(1)),r&&
|
|
266
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let
|
|
265
|
+
`),process.exit(1)),r&&i>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Oe+".tmp";try{return A.writeFileSync(o,e),A.renameSync(o,Oe),!0}catch(r){try{A.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function Mo(){try{if(JSON.parse(A.readFileSync(Oe,"utf-8")).pid!==process.pid)return;A.unlinkSync(Oe)}catch{}}var ur=!1;function qs(){if(ur)return;ur=!0;let e=()=>{try{Mo()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ms(){if(A.existsSync(X))return;let e=[],t=[];for(let i of cr)if(A.existsSync(i))try{e.push({file:i,schema:Gt(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
|
|
266
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
267
267
|
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.
|
|
268
|
-
`),process.exit(1)}if(e.length===0)return;let o=e.map(
|
|
269
|
-
[FATAL] Legacy .schema-version files disagree:`);for(let
|
|
270
|
-
`),process.exit(1)}let r=e[0].schema,n=X+".tmp";try{
|
|
268
|
+
`),process.exit(1)}if(e.length===0)return;let o=e.map(i=>i.schema.version);if(new Set(o).size>1){console.error(`
|
|
269
|
+
[FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
270
|
+
`),process.exit(1)}let r=e[0].schema,n=X+".tmp";try{A.writeFileSync(n,JSON.stringify(r,null,2)),A.renameSync(n,X)}catch(i){try{A.unlinkSync(n)}catch{}throw i}for(let i of cr)if(A.existsSync(i))try{A.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${X}`)}function Us(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 Gt(e){let t=A.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function dr(){if(Ms(),!A.existsSync(X))return{version:0,migrations:[]};let e;try{e=Gt(X)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
271
271
|
[FATAL] ${X} is not valid JSON: ${o.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
272
|
-
`),process.exit(1)}let t=
|
|
272
|
+
`),process.exit(1)}let t=Us(e);return t===null&&(console.error(`
|
|
273
273
|
[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.
|
|
274
|
-
`),process.exit(1)),t}function
|
|
275
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
276
|
-
`),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${
|
|
274
|
+
`),process.exit(1)),t}function mr(e){try{A.chmodSync(e,384)}catch{}}function Bs(e){if(pr(),A.existsSync(X))try{if(A.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(o){if(o.message?.includes("symbolic link"))throw o}let t=X+".tmp";try{A.writeFileSync(t,JSON.stringify(e,null,2)),mr(t),A.renameSync(t,X)}catch(o){try{A.unlinkSync(t)}catch{}throw o}}function fr(e,t){if(!A.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=A.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return A.statSync(F.join(e,a)).isFile()}catch{return!1}}),n=0,i=0,s=[];for(let a of r){let l=F.join(e,a),u=F.join(e,a+o);if(A.existsSync(u)){i++;continue}try{yr(l,u),n++}catch(c){s.push({file:a,err:c.message})}}if(s.length>0){let a=new Error(`Failed to back up ${s.length} file(s) in ${F.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(n>0||i>0){let a=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${F.basename(e)}/ (${o})${a}`)}}var Oo=!1;async function hr(){if(Oo)return;pr(),Ws();let t=dr().version;if(t===_e){Oo=!0;return}qs(),Os(),process.on("exit",Mo),t>_e&&(console.error(`
|
|
275
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${_e}.`),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.
|
|
276
|
+
`),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${_e}.
|
|
277
277
|
`),process.exit(1)),console.log(`
|
|
278
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
278
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${_e}`);let o=Ys();if(!o.ok){console.error(`
|
|
279
279
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of o.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
|
|
280
280
|
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'.
|
|
281
|
-
`),process.exit(1)}let r=
|
|
282
|
-
Running migration v${String(n.version).padStart(3,"0")}...`);let
|
|
283
|
-
[FATAL] Pre-migration backup failed for ${
|
|
284
|
-
`),process.exit(1)}let a=n.module;try{await a.up(
|
|
285
|
-
[FATAL] Migration ${
|
|
286
|
-
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${
|
|
287
|
-
`))}catch(
|
|
288
|
-
`)}process.exit(1)}try{let l=new Date().toISOString(),
|
|
289
|
-
[FATAL] Migration ${
|
|
290
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${
|
|
291
|
-
\u2713 Schema is now at v${
|
|
292
|
-
`)}var
|
|
281
|
+
`),process.exit(1)}let r=we.filter(n=>n.version>t);for(let n of r){console.log(`
|
|
282
|
+
Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{fr(qe,n.version),fr(Me,n.version)}catch(l){console.error(`
|
|
283
|
+
[FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
284
|
+
`),process.exit(1)}let a=n.module;try{await a.up(qe,Me)}catch(l){console.error(`
|
|
285
|
+
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let u=Ks(s);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
286
|
+
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
287
|
+
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
288
|
+
`)}process.exit(1)}try{let l=new Date().toISOString(),u={version:n.version,name:a.NAME||i,appliedAt:l},c=dr();c.version=n.version,c.migratedAt=l,c.migrations=c.migrations||[],c.migrations.push(u),Bs(c)}catch(l){console.error(`
|
|
289
|
+
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${n.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
290
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{mo()}catch{}try{So()}catch{}Oo=!0,Mo(),console.log(`
|
|
291
|
+
\u2713 Schema is now at v${_e}
|
|
292
|
+
`)}var Js=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Hs(e){let t=e.toLowerCase();return Js.some(o=>o.test(t))}var Vs=6e4;function Gs(){let e=Date.now(),t=[];for(let o of[fe,qe,Me]){if(!A.existsSync(o))continue;let r;try{r=A.readdirSync(o)}catch{continue}for(let n of r){if(!Hs(n))continue;let i=F.join(o,n);try{let s=A.statSync(i);if(!s.isFile()||e-s.mtimeMs<Vs)continue;t.push({dir:o,file:n,fullPath:i})}catch{}}}return t}function Ws({verbose:e=!1}={}){let t=Gs();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{A.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${F.basename(r.dir)}/${r.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${r.fullPath}: ${n.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function Ys(){let e=[];for(let t of[qe,Me]){if(!A.existsSync(t))continue;let o=A.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=F.join(t,r);try{Gt(n)}catch(i){e.push({dir:F.basename(t),file:r,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ks(e){let t=[],o=[];for(let i of[qe,Me]){if(!A.existsSync(i))continue;let s=A.readdirSync(i).filter(a=>a.endsWith(e));for(let a of s){let l=F.join(i,a),u=a.slice(0,-e.length),c=F.join(i,u);try{u.toLowerCase().endsWith(".json")?Gt(l):A.accessSync(l,A.constants.R_OK),t.push({backupPath:l,originalPath:c,fileName:a,dir:i})}catch(f){o.push(`${F.basename(i)}/${a}: ${f.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:i,originalPath:s,fileName:a,dir:l}of t)try{yr(i,s),r++}catch(u){n.push(`${F.basename(l)}/${a}: ${u.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function yr(e,t){let o=t+".tmp";try{A.copyFileSync(e,o),mr(o)}catch(r){try{A.unlinkSync(o)}catch{}throw r}try{A.renameSync(o,t)}catch(r){try{A.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let n=new Error(`File locked: ${t} (${r.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 n.code=r.code,n}throw r}}import"dotenv/config";import*as ce from"fs";import*as Te from"path";import{fileURLToPath as Xs}from"url";import"dotenv/config";function zs(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),r=t%60;return r?`${o}m ${r}s`:`${o}m`}function Qs({scriptName:e,mode:t,status:o,error:r,duration:n}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),a=n?` ${zs(n)}`:"",l=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${l} \u2014 ${s}${a}`}async function gr({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(r)||r.length===0)return;let l=`**${Qs({scriptName:e,mode:t,status:o,error:n,duration:i})}**
|
|
293
293
|
|
|
294
294
|
${r.join(`
|
|
295
|
-
`)}`;try{await $e.addMessage(i,l)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Js=Bs(import.meta.url),Vs=ke.dirname(ke.dirname(Js)),po=process.env.DATA_DIR?ke.resolve(process.env.DATA_DIR,"collected-profiles"):ke.join(Vs,"collected-profiles"),mo=ke.join(po,"run-log.json");function Hs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ae.writeFileSync(r,o);for(let n=0;n<3;n++)try{ae.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function In(){try{if(!ae.existsSync(mo))return{runs:[]};let e=JSON.parse(ae.readFileSync(mo,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Rn(e){ae.existsSync(po)||ae.mkdirSync(po,{recursive:!0});try{Hs(mo,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ln(e,t="default"){let o=In();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let s=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>s),Rn(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Dn(e,t,o=null,r=null){if(!e)return;let n=null;try{let i=In(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=r,n=a.duration;else{let l=i.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}Rn(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Tn({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import fe from"fs";import xe from"path";var Gs="cookies.json";function jn(){let e=process.env.ILML_SCOPE_DIR;return e?xe.join(e,"plugins-state","linkedin","cookies.json"):Gs}function It(){let e=jn();if(!fe.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=fe.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function Nn(){return fe.existsSync(jn())}function Ws(){let e=process.env.ILML_SCOPE_DIR;return e?xe.join(e,"plugins-state","linkedin"):"."}function Fn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Ys(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Fn(t[1]):"default"}function qn(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return fe.existsSync(t)||fe.mkdirSync(t,{recursive:!0}),xe.resolve(t);let o=Fn(e||Ys()),r=xe.join(Ws(),"chrome-profile",o);return fe.existsSync(r)||fe.mkdirSync(r,{recursive:!0}),xe.resolve(r)}var On=".ilml-seeded";function Pn(e){return!fe.existsSync(xe.join(e,On))}function Mn(e){try{fe.writeFileSync(xe.join(e,On),new Date().toISOString())}catch{}}function Un(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{fe.rmSync(xe.join(e,o),{force:!0}),t++}catch{}return t}var Ks={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function ho(e,t={}){let o=qn(),r={...Ks,...t,userDataDir:o},n;try{n=await e.launch(r)}catch{Un(o);try{n=await e.launch(r)}catch(i){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${i.message})`)}}return{browser:n,profileDir:o,needsSeed:Pn(o)}}async function Bn(e,t){if(!t||!t.needsSeed)return!1;if(!Nn())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(...It()),Mn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}je();async function dt(e,t,o="op"){let r,n=new Promise((s,i)=>{r=setTimeout(()=>i(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function Ye(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let o=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(o)||/Target closed/i.test(o)||/Session closed/i.test(o)||/Connection closed/i.test(o)||/Most likely the page has been closed/i.test(o)||/Navigating frame was detached/i.test(o)||/Protocol error.*timed out/i.test(o)}async function Jn(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await dt(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function Vn(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await Jn(e,t)?!0:(await w(o),await Jn(e,t))}async function Hn(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await dt(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function Gn(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){try{await dt(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let i=await e.newPage();if(s)try{await s(i)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await i.setCookie(...a)}catch{}if(o){await i.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=i.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return i}async function Wn(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");let i=null;try{i=e.process()}catch{}let a=!1;try{await dt(e.close(),5e3,"oldBrowser.close"),a=!0}catch{}if(!a&&i&&i.pid&&i.exitCode===null){try{i.kill("SIGKILL")}catch{}try{await dt(new Promise(c=>i.once("exit",c)),5e3,"oldBrowser.kill")}catch{}}let l=await t(),f=await l.newPage();if(s)try{await s(f)}catch{}if(n)try{let c=n();Array.isArray(c)&&c.length>0&&await f.setCookie(...c)}catch{}if(o){await f.goto(o,{waitUntil:"domcontentloaded",timeout:r});let c=f.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(c))throw new Error(`Session expired after browser restart \u2014 landed on ${c}. Run: ilml linkedin login`)}return{browser:l,page:f}}await An();var Nt=0,zs=process.env.FUNNEL_CONNECT_RECRUITERS==="true",Qs=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Xs=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Zs=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",yo=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],Rt=-1;async function ei(){if(Rt===-1){let e=await Fe("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${e}`),!/^\d+$/.test(e.trim()))throw new Error(`Last Counter is not a number, got: "${e}"`);Rt=_o(e)+1,console.log(`lastIndex initialized as: ${Rt}`)}return Rt++}var rr=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${rr}`);var ti=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{if(e.code==="PROCESSING_ERROR"||e.constructor?.name==="LifebotProcessingError")return!1;let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"lifebot-provider-error",match:e=>e.code==="PROCESSING_ERROR"||e.constructor.name==="LifebotProcessingError"||/AI provider returned an unexpected error/i.test(e.message||""),severity:"transient",maxConsecutive:3,cleanup:"popup",cooldownMs:3e3,instructions:"The AI provider had a hiccup. If it keeps failing, switch the provider in your Lifebot node settings."},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],ft={};function sr(e){let t=e;for(let o=0;t&&o<5;o++){let r=ti.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function oi(e){return ft[e]=(ft[e]||0)+1,ft[e]}function zn(){for(let e of Object.keys(ft))ft[e]=0}var go=0;function ni(){return go++,go>=rr?(console.log(`Max run counter reached with ${go}`),!1):!0}async function ri(e){let t=await rn(e)}async function si(e){return sn(e,{easyApplyOnly:!0})}async function ii(e){return ln(e)}async function So(e,t){return Xt(e,t)}var bo=3,li=2;async function Dt(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:s}=e.recoveryCtx,i=await Hn(e.browser);if(!i||e._pageRecoveryStreak>=bo){if(v.browserRestarts>=li)throw new Error(`CDP unrecoverable: ${v.browserRestarts} browser restart${v.browserRestarts===1?"":"s"} and ${v.cdpRecoveries} page recover${v.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let l=i?`${bo} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${l}). Reason: ${t}`);let f=await Wn(e.browser,{launchFn:r,setupPage:n,cookiesProvider:s,returnUrl:o});e.browser=f.browser,e.page=f.page,e._pageRecoveryStreak=0,v.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${v.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${bo}). Reason: ${t}`),e.page=await Gn(e.browser,e.page,{returnUrl:o,cookiesProvider:s,setupPage:n}),e._pageRecoveryStreak+=1,v.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${v.cdpRecoveries}).`)}async function ai(e){let{searchUrl:t}=e.recoveryCtx,o=3;e._pageRecoveryStreak=e._pageRecoveryStreak||0;for(let r=1;r<=o;r++){if(r>1){console.log(`
|
|
296
|
-
--- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(c){if(Ye(c))await Dt(e,`pass-${r} navigation: ${c.message?.slice(0,80)}`);else throw c}await w(3e3)}let n=v.submitted,s=v.cdpRecoveries+v.browserRestarts,i=!0,a=!0;for(;i&&a;){if(!await Vn(e.page)){await Dt(e,"liveness probe failed twice");continue}try{await So(e.page,t);let d=await xi(e.page,lr,ri);a=d.keepGoing;let u=d.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(u.length),!a)break;i=await ii(e.page),e._pageRecoveryStreak=0}catch(d){if(!Ye(d))throw d;await Dt(e,`mid-iteration: ${d.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let l=v.submitted-n,f=v.cdpRecoveries+v.browserRestarts-s;if(l===0){if(f>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${f} CDP recover${f===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${l} new jobs in pass ${r}.`)}}async function Qn(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return an(e,t,o,r)}async function Xn(e,t){let o=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${o}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${o} from list`)):console.log(` Dismiss button not found for ${o}`)}async function ci(e,t){try{let o=await cn(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},Ze("recruiters-from-jobs",o)?(Nt++,console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F3AF} RECRUITER FOUND \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Name: ${o.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${o.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(Nt).padEnd(23)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")):console.log(` \u2139 Recruiter already saved: ${o.name}`),we(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){vt(o.profileUrl,n),Je(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=o.fromJob?.companyUrl;s&&oo(s,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function jt(e){return await e.evaluate(()=>{let t=document.body.innerText||"",o=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+o;return r.includes("We limit daily submissions")||r.includes("We limit Easy Apply submissions")||r.includes("Easy Apply limit")||r.includes("reached today")||r.includes("apply tomorrow")})}async function ir(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let s=n.querySelectorAll("button");for(let i of s){let a=i.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return i.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function Zn(e){await e.evaluate(()=>{let i=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of i)for(let l of a.querySelectorAll("button")){let f=l.innerText?.trim();if(f==="Continue applying"||f==="Got it"||f==="Dismiss"){l.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let i=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let l of a){let f=l.innerText?.trim();if(f==="Easy Apply"||f==="Apply")return l}return null});r=i?.asElement?.()||null,r||await i.dispose().catch(()=>{})}r||await new Promise(i=>setTimeout(i,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(f=>f.disabled,r))return await jt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(f=>f.tagName==="A",r)){await e.evaluate(f=>f.click(),r),await w(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await w(2e3)}}else await r.click(),await w(1500);return await jt(e)?(await ir(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await jt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function ui(e){return await e.evaluate(async()=>{function t(){let l=document.querySelectorAll(".artdeco-inline-feedback__message");if(l.length>0)return l;let f=document.querySelector("#interop-outlet")?.shadowRoot;return f&&(l=f.querySelectorAll(".artdeco-inline-feedback__message")),l}let o=3e3,r=t();if(r?.length===0&&(await new Promise(l=>setTimeout(l,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let s=n?.textContent.trim(),i=n.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=n.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(i),a||i){console.log("parentElement"),console.log(a);let l=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),f=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),c=a.querySelectorAll('input[type="radio"]'),d=a.querySelector("select[data-test-text-entity-list-form-select]"),u=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(u),l&&f)return{type:"input",labelText:l.textContent.trim(),errorMsgText:s};if(l&&c.length){let m=l?l.querySelector("span:nth-of-type(1)")?.textContent.trim():null,h=Array.from(c).map(y=>{let E=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:E||y.value}}),g=h.map(y=>y.label);return{type:"radio",labelText:m,errorMsgText:s,options:g,optionsData:h}}else if(d){let m=a.querySelector('label[for="'+d.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),h=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(d.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:h,errorMsgText:s,options:g}}else if(u){let m=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:m}}else{if(p)return{type:"datePicker",errorMsgText:s};{let m=l?l.querySelector("span:nth-of-type(2)")?.textContent.trim():null,h=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(h.length>0){let g=Array.from(h).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:s,options:g}}else return null}}}return null})}async function di(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));l.value=n;let f=new Event("input",{bubbles:!0});if(l.dispatchEvent(f),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let c=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},d=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),d(p),await new Promise(m=>setTimeout(m,100)),c(p)})(l)}}return null},t,o)}async function fi(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('input[type="radio"]'),f=n;if(r.optionsData){let c=r.optionsData.find(d=>d.label.toLowerCase()===n.toLowerCase());c&&(f=c.value,console.log(`Radio: matched label "${n}" to value "${f}"`))}for(let c of l){let u=(document.querySelector(`label[for="${c.id}"]`)||c.nextElementSibling)?.textContent?.trim()||"";if(c.value.toLowerCase()===f.toLowerCase()||u.toLowerCase()===n.toLowerCase()){c.checked=!0;let p=new Event("change",{bubbles:!0});c.dispatchEvent(p),console.log(`Radio selected: value="${c.value}", label="${u}"`);break}}}return null},t,o)}async function pi(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector("select[data-test-text-entity-list-form-select]");if(!l)return null;let f=Array.from(l.options),c=f.find(u=>u.text.toLowerCase()===n.toLowerCase())||f.find(u=>u.text.toLowerCase().includes(n.toLowerCase()));c?l.value=c.value:l.value=n;let d=new Event("change",{bubbles:!0});l.dispatchEvent(d)}return null},t,o)}async function mi(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');l.length>0&&l.forEach(f=>{if(f.nextElementSibling.textContent.trim()===n.trim()){f.checked=!0;let c=new Event("change",{bubbles:!0});f.dispatchEvent(c)}})}return null},t,o)}async function hi(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s?.length===0)return null;let i=s[0],a=i.closest(".fb-dash-form-element"),l=i.parentElement.parentElement.querySelector('input[type="file"]');if(a&&l){async function f(c,d,u){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(d)]),h=new File([m],u,{type:"application/pdf"}),g=new DataTransfer;g.items.add(h),c.files=g.files;let y=new Event("change",{bubbles:!0});c.dispatchEvent(y)}await f(l,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function er(e){let t=await ui(e);if(t===null)return null;if(t?.type==="input"){let n=await Ot(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await di(e,t,n)}else if(t?.type==="radio"){let n=await pt(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[];!s.find(a=>a.toLowerCase()===n?.toLowerCase())&&s.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await pt(t.labelText,t.options),n=n?.trim()||n,s.find(l=>l.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])),t.answer=n,await fi(e,t,n)}else if(t?.type==="select"){let n=await Qe(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[],i=s.find(a=>a.toLowerCase()===n?.toLowerCase());if(i)n=i;else if(s.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await Qe(t.labelText,t.options),n=n?.trim()||n;let a=s.find(l=>l.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])}t.answer=n,await pi(e,t,n)}else if(t?.type==="checkbox"){let n=await Qe(t.labelText,t.options);t.answer=n,await mi(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let s=await fetch(n);if(!s.ok)throw new Error("Network response was not ok");let i=await s.arrayBuffer();await hi(e,t,i)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function yi(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),s=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),i=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),l=r.querySelector("select[data-test-text-entity-list-form-select]"),f=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),c=r.querySelector('input[type="file"]');if(n&&i&&a.length===0){let d=n.textContent.trim();t.push({type:"input",labelText:d,answer:i.value,isRequired:s,wasPreFilled:!!i.value})}else if(n&&a.length){let d=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,u=Array.from(a).map(m=>m.value),p=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:d,options:u,answer:p,isRequired:s,wasPreFilled:!!p})}else if(l){let d=r.querySelector('label[for="'+l.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),u=d?.querySelector("span:nth-of-type(2)")?.textContent.trim()||d?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||d?.querySelector("span")?.textContent.trim()||d?.textContent?.trim()||null,p=Array.from(l.options).map(h=>h.value).filter(h=>h!=="Select an option"),m=l.value!=="Select an option"?l.value:"";t.push({type:"select",labelText:u,options:p,answer:m,isRequired:s,wasPreFilled:!!m})}else if(f.length>0){let d=r.querySelector("legend span")?.textContent?.trim(),u=Array.from(f).map(h=>({label:h.nextElementSibling?.textContent?.trim()||h.value,checked:h.checked})),p=u.some(h=>h.checked),m=u.filter(h=>h.checked).map(h=>h.label).join(", ");t.push({type:"checkbox",labelText:d,options:u.map(h=>h.label),answer:m,isRequired:s,wasPreFilled:p})}else if(c){let d=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:d,answer:c.value?"uploaded":"",isRequired:s,wasPreFilled:!!c.value})}}return t})}async function vo(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let i of s){let a=i.querySelector(".artdeco-text-input--label")||i.querySelector("legend .fb-dash-form-element__label-title--is-required")||i.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||i.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),l=i.querySelector(".artdeco-text-input--input")||i.querySelector("input");if(a&&l&&r===a.textContent.trim()){l.value=n;let f=new Event("input",{bubbles:!0});if(l.dispatchEvent(f),r==="City"||r==="Location (city)"){let c=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},d=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),d(p),await new Promise(m=>setTimeout(m,100)),c(p)})(l)}return!0}}return!1},t,o)}async function gi(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let i of s){let a=i.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let l=i.querySelector("legend .fb-dash-form-element__label-title--is-required")||i.querySelector('legend [class*="fb-dash-form-element__label"]')||i.querySelector("legend span");if((l?.querySelector("span:nth-of-type(1)")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let c=(n||"").toLowerCase();for(let d of a){let u=d.getRootNode(),m=(d.id&&u.querySelector(`label[for="${d.id}"]`)||d.nextElementSibling)?.textContent?.trim()||"";if(d.value.toLowerCase()===c||m.toLowerCase()===c)return d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function bi(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let i of s){let a=i.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let l=i.querySelector(`label[for="${a.id}"]`)||i.querySelector(".fb-dash-form-element__label-title--is-required");if((l?.querySelector("span:nth-of-type(2)")?.textContent.trim()||l?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||l?.querySelector("span")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let c=Array.from(a.options),d=(n||"").toLowerCase(),u=c.find(p=>p.text.toLowerCase()===d)||c.find(p=>p.value.toLowerCase()===d)||c.find(p=>p.text.toLowerCase().includes(d));return u?(a.value=u.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function wi(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(s=a.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;let i=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(i.length===0)return!1;for(let a of s){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(l.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let c=!1;for(let d of l){let u=(d.nextElementSibling?.textContent||d.value||"").trim().toLowerCase();i.includes(u)&&!d.checked&&(d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),c=!0)}return c}return!1},t,o)}async function Si(e,t){for(let o of t){if(!o.labelText||o.isRequired||o.wasPreFilled||o.answer||o.type==="datePicker"||o.type==="file")continue;let r="";try{if(o.type==="input")r=await Ot(o.labelText,"");else if(o.type==="radio")r=await pt(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await Qe(o.labelText,o.options||[]);else continue}catch(i){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${i.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await vo(e,o.labelText,r):o.type==="radio"?n=await gi(e,o.labelText,r):o.type==="select"?n=await bi(e,o.labelText,r):o.type==="checkbox"&&(n=await wi(e,o.labelText,r))}catch(i){console.log(` \u26A0 setter failed for "${o.labelText}": ${i.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function tr(e,t){let o=[],r=!0,n=0,s=null,i=0;for(;r;){if(n++,await jt(e))return console.log(" Daily limit reached during form navigation"),await ir(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let f=(await yi(e)).filter(p=>!o.some(m=>m.labelText===p.labelText));o.push(...f);try{let p=o.find(h=>h.labelText==="City"||h.labelText==="Location (city)"),m=o.filter(h=>h.labelText!=null).find(h=>h.labelText!==null&&h.labelText.trim()!==null&&(h.labelText.trim().toLowerCase()==="cv"||h.labelText.trim().toLowerCase()==="curriculum vitae"||h.labelText.trim().toLowerCase()==="cover letter"||h.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let h=process.env.City;await vo(e,p.labelText,h),p.answer=h}else if(m){let h=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==h)&&(await w(1e4),await vo(e,m.labelText,h),m.answer=h,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Si(e,f)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let c=null;try{c=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(c!==null){if(c.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:c};let p=c&&o.find(h=>h.errorMsgText&&h.labelText===c.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(c,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:c};let m=o.findIndex(h=>h.labelText===c.labelText&&!h.answer);m!==-1&&o.splice(m,1),o.push(c)}let d=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of p){let h=m.querySelectorAll("button");for(let g of h){let y=g.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return g.click(),y}}return null});d&&console.log(` Dismissed safety popup (${d})`);let u=await e.evaluate(async()=>{function p(b){let $=document.querySelector(b);if($)return $;let M=document.querySelector("#interop-outlet")?.shadowRoot;return M?M.querySelector(b):null}function m(b){let $=document.querySelectorAll(b),M=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(b);return[...$||[],...M||[]]}let h=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(b=>b.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(b=>b.innerText.trim()==="Review")||m("button").some(b=>b.innerText.trim()==="Review"&&b.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),S=async()=>{let b=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find($=>$.innerText?.trim()==="Next");b?b.click():console.log("Next button not found")},E=()=>{let b=m("button").find($=>$.innerText?.trim()==="Review");b&&b.click()};return h?(await S(),{type:"next"}):g?(await E(),{type:"review"}):y?{type:"submit"}:{type:null}});if(u==null)return{filledFields:o,formPages:n,skip:!0};if(u.type&&console.log(` \u2192 ${u.type}`),u.type===null){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of m){let g=h.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of g){let S=y.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let E of y.querySelectorAll("button")){let b=E.innerText?.trim();if(b==="Not now"||b==="Done"||b==="Dismiss"||b==="Got it")return E.click(),b}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await w(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(i===0){let m=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],y=[];for(let S of h){for(let b of S.querySelectorAll("button")){let $=b.innerText?.trim();$&&$.length<60&&g.push($)}let E=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');E&&y.push(E.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(u.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(c===null&&u.type===s?i++:i=0,s=u.type,i>=5){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),h=[],g=[];for(let y of m){for(let S of y.querySelectorAll(".artdeco-inline-feedback__message"))h.push(S.textContent?.trim()?.slice(0,60));for(let S of y.querySelectorAll(".fb-dash-form-element")){let E=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),b=S.querySelector("input, select, textarea"),$=!!S.querySelector(".artdeco-inline-feedback__message");E&&($||b&&!b.value)&&g.push({label:E.slice(0,40),hasError:$,value:b?.value?.slice(0,20)||""})}}return{errors:h,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${u.type}" for ${i} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${u.type}`}}}await w(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function or(e){try{await e.evaluate(()=>{let t=document.getElementById("follow-company-checkbox");t?(t.checked=!1,t.dispatchEvent(new Event("change",{bubbles:!0}))):console.warn("Unfollow checkbox not found.")})}catch(t){console.error("Error in unfollowJobCheckbox:",t)}}async function vi(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let o=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=o?.asElement?.()||null,t||await o.dispose().catch(()=>{})}t&&await t.click()}async function ki(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let s of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(s.innerText?.trim()==="Done")return s.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let s of n){let i=s.innerText||"";if(i.includes("application was sent")||i.includes("Application sent")||i.includes("resume into a profile")||i.includes("Next best action"))for(let a of s.querySelectorAll("button")){let l=a.innerText?.trim();if(l==="Not now"||l==="Dismiss")return a.click(),l}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await w(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function Lt(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await w(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function wo(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await w(500))}catch{console.log("No discard confirmation needed")}}async function lr(e,t){let o=[],r=t._fromQueue;try{v.attempted++,console.log(`
|
|
297
|
-
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&
|
|
295
|
+
`)}`;try{await Ie.addMessage(s,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Zs=Xs(import.meta.url),el=Te.dirname(Te.dirname(Zs)),Uo=process.env.DATA_DIR?Te.resolve(process.env.DATA_DIR,"collected-profiles"):Te.join(el,"collected-profiles"),Bo=Te.join(Uo,"run-log.json");function tl(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ce.writeFileSync(r,o);for(let n=0;n<3;n++)try{ce.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function br(){try{if(!ce.existsSync(Bo))return{runs:[]};let e=JSON.parse(ce.readFileSync(Bo,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function wr(e){ce.existsSync(Uo)||ce.mkdirSync(Uo,{recursive:!0});try{tl(Bo,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Sr(e,t="default"){let o=br();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),wr(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function kr(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=br(),a=s.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=r,n=a.duration;else{let l=s.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}wr(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";gr({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import pe from"fs";import Re from"path";var ol="cookies.json";function vr(){let e=process.env.ILML_SCOPE_DIR;return e?Re.join(e,"plugins-state","linkedin","cookies.json"):ol}function Wt(){let e=vr();if(!pe.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=pe.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function xr(){return pe.existsSync(vr())}function nl(){let e=process.env.ILML_SCOPE_DIR;return e?Re.join(e,"plugins-state","linkedin"):"."}function Cr(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function rl(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Cr(t[1]):"default"}function Ar(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return pe.existsSync(t)||pe.mkdirSync(t,{recursive:!0}),Re.resolve(t);let o=Cr(e||rl()),r=Re.join(nl(),"chrome-profile",o);return pe.existsSync(r)||pe.mkdirSync(r,{recursive:!0}),Re.resolve(r)}var Er=".ilml-seeded";function $r(e){return!pe.existsSync(Re.join(e,Er))}function _r(e){try{pe.writeFileSync(Re.join(e,Er),new Date().toISOString())}catch{}}function Tr(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{pe.rmSync(Re.join(e,o),{force:!0}),t++}catch{}return t}var il={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function Jo(e,t={}){let o=Ar(),r={...il,...t,userDataDir:o},n;try{n=await e.launch(r)}catch{Tr(o);try{n=await e.launch(r)}catch(s){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${s.message})`)}}return{browser:n,profileDir:o,needsSeed:$r(o)}}async function Rr(e,t){if(!t||!t.needsSeed)return!1;if(!xr())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(...Wt()),_r(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}Ue();async function kt(e,t,o="op"){let r,n=new Promise((i,s)=>{r=setTimeout(()=>s(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function nt(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let o=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(o)||/Target closed/i.test(o)||/Session closed/i.test(o)||/Connection closed/i.test(o)||/Most likely the page has been closed/i.test(o)||/Navigating frame was detached/i.test(o)||/Protocol error.*timed out/i.test(o)}async function Ir(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await kt(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function Dr(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await Ir(e,t)?!0:(await w(o),await Ir(e,t))}async function jr(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await kt(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function Lr(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){try{await kt(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let s=await e.newPage();if(i)try{await i(s)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await s.setCookie(...a)}catch{}if(o){await s.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=s.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return s}async function Nr(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:i=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");let s=null;try{s=e.process()}catch{}let a=!1;try{await kt(e.close(),5e3,"oldBrowser.close"),a=!0}catch{}if(!a&&s&&s.pid&&s.exitCode===null){try{s.kill("SIGKILL")}catch{}try{await kt(new Promise(c=>s.once("exit",c)),5e3,"oldBrowser.kill")}catch{}}let l=await t(),u=await l.newPage();if(i)try{await i(u)}catch{}if(n)try{let c=n();Array.isArray(c)&&c.length>0&&await u.setCookie(...c)}catch{}if(o){await u.goto(o,{waitUntil:"domcontentloaded",timeout:r});let c=u.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(c))throw new Error(`Session expired after browser restart \u2014 landed on ${c}. Run: ilml linkedin login`)}return{browser:l,page:u}}await hr();var Xt=0,sl=process.env.FUNNEL_CONNECT_RECRUITERS==="true",ll=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",al=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),cl=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Ho=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],Yt=-1;async function ul(){if(Yt===-1){let e=await Je("What is last counter? Answer only number!!");if(console.log(`Lifebot answered about lastIndex:${e}`),!/^\d+$/.test(e.trim()))throw new Error(`Last Counter is not a number, got: "${e}"`);Yt=on(e)+1,console.log(`lastIndex initialized as: ${Yt}`)}return Yt++}var Gr=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${Gr}`);var dl=[{label:"linkedin-session-expired",match:e=>/redirected to login|cookies expired|Session expired after recovery/i.test(e.message),severity:"fatal",instructions:"Run: ilml linkedin login"},{label:"ilml-auth-expired",match:e=>{if(e.code==="PROCESSING_ERROR"||e.constructor?.name==="LifebotProcessingError")return!1;let t=e.message||"";return/Token is invalid or expired/i.test(t)||/\b401\b/.test(t)||/Unauthorized/i.test(t)||/authentication.*(failed|required)/i.test(t)},severity:"fatal",instructions:"Run: ilml login (this is the iLiveMyLife platform login, not the LinkedIn one)"},{label:"lifebot-timeout",match:e=>e.constructor.name==="LifebotTimeoutError",severity:"transient",maxConsecutive:3,cleanup:"popup"},{label:"lifebot-provider-error",match:e=>e.code==="PROCESSING_ERROR"||e.constructor.name==="LifebotProcessingError"||/AI provider returned an unexpected error/i.test(e.message||""),severity:"transient",maxConsecutive:3,cleanup:"popup",cooldownMs:3e3,instructions:"The AI provider had a hiccup. If it keeps failing, switch the provider in your Lifebot node settings."},{label:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],vt={};function Wr(e){let t=e;for(let o=0;t&&o<5;o++){let r=dl.find(n=>{try{return n.match(t)}catch{return!1}});if(r)return r;t=t.cause}return null}function fl(e){return vt[e]=(vt[e]||0)+1,vt[e]}function Or(){for(let e of Object.keys(vt))vt[e]=0}var Vo=0;function pl(){return Vo++,Vo>=Gr?(console.log(`Max run counter reached with ${Vo}`),!1):!0}async function ml(e){let t=await er(e)}async function hl(e){return tr(e,{easyApplyOnly:!0})}async function yl(e){return or(e)}async function Yo(e,t){return Io(e,t)}var Go=3,gl=2;async function zt(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:i}=e.recoveryCtx,s=await jr(e.browser);if(!s||e._pageRecoveryStreak>=Go){if(k.browserRestarts>=gl)throw new Error(`CDP unrecoverable: ${k.browserRestarts} browser restart${k.browserRestarts===1?"":"s"} and ${k.cdpRecoveries} page recover${k.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let l=s?`${Go} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${l}). Reason: ${t}`);let u=await Nr(e.browser,{launchFn:r,setupPage:n,cookiesProvider:i,returnUrl:o});e.browser=u.browser,e.page=u.page,e._pageRecoveryStreak=0,k.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${k.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${Go}). Reason: ${t}`),e.page=await Lr(e.browser,e.page,{returnUrl:o,cookiesProvider:i,setupPage:n}),e._pageRecoveryStreak+=1,k.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${k.cdpRecoveries}).`)}async function bl(e){let{searchUrl:t}=e.recoveryCtx,o=3;e._pageRecoveryStreak=e._pageRecoveryStreak||0;for(let r=1;r<=o;r++){if(r>1){console.log(`
|
|
296
|
+
--- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(c){if(nt(c))await zt(e,`pass-${r} navigation: ${c.message?.slice(0,80)}`);else throw c}await w(3e3)}let n=k.submitted,i=k.cdpRecoveries+k.browserRestarts,s=!0,a=!0;for(;s&&a;){if(!await Dr(e.page)){await zt(e,"liveness probe failed twice");continue}try{await Yo(e.page,t);let f=await jl(e.page,Kr,ml);a=f.keepGoing;let d=f.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(d.length),!a)break;s=await yl(e.page),e._pageRecoveryStreak=0}catch(f){if(!nt(f))throw f;await zt(e,`mid-iteration: ${f.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let l=k.submitted-n,u=k.cdpRecoveries+k.browserRestarts-i;if(l===0){if(u>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${u} CDP recover${u===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${l} new jobs in pass ${r}.`)}}async function qr(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return nr(e,t,o,r)}async function Mr(e,t){let o=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${o}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${o} from list`)):console.log(` Dismiss button not found for ${o}`)}async function wl(e,t){try{let o=await rr(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},lt("recruiters-from-jobs",o)?(Xt++,console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F3AF} RECRUITER FOUND \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Name: ${o.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${o.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(Xt).padEnd(23)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")):console.log(` \u2139 Recruiter already saved: ${o.name}`),Ce(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){It(o.profileUrl,n),Ke(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let i=o.fromJob?.companyUrl;i&&Ut(i,{recruiterUrl:o.profileUrl,jobId:n})}return o}else console.log(" \u26AA No recruiter found on this job page");return null}catch(o){return console.error("Error extracting recruiter:",o.message),null}}async function Qt(e){return await e.evaluate(()=>{let t=document.body.innerText||"",o=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+o;return r.includes("We limit daily submissions")||r.includes("We limit Easy Apply submissions")||r.includes("Easy Apply limit")||r.includes("reached today")||r.includes("apply tomorrow")})}async function Yr(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let n of o){let i=n.querySelectorAll("button");for(let s of i){let a=s.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return s.click(),!0}}let r=document.querySelector('button[aria-label="Dismiss"]');return r?(r.click(),!0):!1});return t&&console.log(" Daily limit popup closed"),t}catch{return!1}}async function Ur(e){await e.evaluate(()=>{let s=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of s)for(let l of a.querySelectorAll("button")){let u=l.innerText?.trim();if(u==="Continue applying"||u==="Got it"||u==="Dismiss"){l.click();return}}});let t=Date.now(),o=3e3,r=null;for(;!r&&Date.now()-t<o;){if(r=await e.$(".jobs-apply-button"),r||(r=await e.$('button[aria-label*="Easy Apply"]')),r||(r=await e.$('a[aria-label*="Easy Apply"]')),r||(r=await e.$('a[href*="/apply/"]')),!r){let s=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let l of a){let u=l.innerText?.trim();if(u==="Easy Apply"||u==="Apply")return l}return null});r=s?.asElement?.()||null,r||await s.dispose().catch(()=>{})}r||await new Promise(s=>setTimeout(s,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(u=>u.disabled,r))return await Qt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(u=>u.tagName==="A",r)){await e.evaluate(u=>u.click(),r),await w(3e3);try{await e.waitForFunction(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[data-easy-apply-next-button], button[aria-label="Submit application"]'),{timeout:1e4})}catch{await w(2e3)}}else await r.click(),await w(1500);return await Qt(e)?(await Yr(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await Qt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Sl(e){return await e.evaluate(async()=>{function t(){let l=document.querySelectorAll(".artdeco-inline-feedback__message");if(l.length>0)return l;let u=document.querySelector("#interop-outlet")?.shadowRoot;return u&&(l=u.querySelectorAll(".artdeco-inline-feedback__message")),l}let o=3e3,r=t();if(r?.length===0&&(await new Promise(l=>setTimeout(l,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let i=n?.textContent.trim(),s=n.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=n.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(s),a||s){console.log("parentElement"),console.log(a);let l=a.querySelector(".artdeco-text-input--label")||a.querySelector("legend .fb-dash-form-element__label-title--is-required")||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"] span[aria-hidden="true"]')||a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][data-test-single-typeahead-entity-form-title="true"] span[aria-hidden="true"]')||a.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),u=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),c=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),d=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(d),l&&u)return{type:"input",labelText:l.textContent.trim(),errorMsgText:i};if(l&&c.length){let m=l?l.querySelector("span:nth-of-type(1)")?.textContent.trim():null,h=Array.from(c).map(y=>{let C=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:C||y.value}}),g=h.map(y=>y.label);return{type:"radio",labelText:m,errorMsgText:i,options:g,optionsData:h}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),h=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:h,errorMsgText:i,options:g}}else if(d){let m=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:i,labelText:m}}else{if(p)return{type:"datePicker",errorMsgText:i};{let m=l?l.querySelector("span:nth-of-type(2)")?.textContent.trim():null,h=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(h.length>0){let g=Array.from(h).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:i,options:g}}else return null}}}return null})}async function kl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for"));l.value=n;let u=new Event("input",{bubbles:!0});if(l.dispatchEvent(u),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let c=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),c(p)})(l)}}return null},t,o)}async function vl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('input[type="radio"]'),u=n;if(r.optionsData){let c=r.optionsData.find(f=>f.label.toLowerCase()===n.toLowerCase());c&&(u=c.value,console.log(`Radio: matched label "${n}" to value "${u}"`))}for(let c of l){let d=(document.querySelector(`label[for="${c.id}"]`)||c.nextElementSibling)?.textContent?.trim()||"";if(c.value.toLowerCase()===u.toLowerCase()||d.toLowerCase()===n.toLowerCase()){c.checked=!0;let p=new Event("change",{bubbles:!0});c.dispatchEvent(p),console.log(`Radio selected: value="${c.value}", label="${d}"`);break}}}return null},t,o)}async function xl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelector("select[data-test-text-entity-list-form-select]");if(!l)return null;let u=Array.from(l.options),c=u.find(d=>d.text.toLowerCase()===n.toLowerCase())||u.find(d=>d.text.toLowerCase().includes(n.toLowerCase()));c?l.value=c.value:l.value=n;let f=new Event("change",{bubbles:!0});l.dispatchEvent(f)}return null},t,o)}async function Cl(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');l.length>0&&l.forEach(u=>{if(u.nextElementSibling.textContent.trim()===n.trim()){u.checked=!0;let c=new Event("change",{bubbles:!0});u.dispatchEvent(c)}})}return null},t,o)}async function Al(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i?.length===0)return null;let s=i[0],a=s.closest(".fb-dash-form-element"),l=s.parentElement.parentElement.querySelector('input[type="file"]');if(a&&l){async function u(c,f,d){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),h=new File([m],d,{type:"application/pdf"}),g=new DataTransfer;g.items.add(h),c.files=g.files;let y=new Event("change",{bubbles:!0});c.dispatchEvent(y)}await u(l,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function Br(e){let t=await Sl(e);if(t===null)return null;if(t?.type==="input"){let n=await to(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await kl(e,t,n)}else if(t?.type==="radio"){let n=await xt(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[];!i.find(a=>a.toLowerCase()===n?.toLowerCase())&&i.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await xt(t.labelText,t.options),n=n?.trim()||n,i.find(l=>l.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])),t.answer=n,await vl(e,t,n)}else if(t?.type==="select"){let n=await it(t.labelText,t.options);n=n?.trim()||n;let i=t.options||[],s=i.find(a=>a.toLowerCase()===n?.toLowerCase());if(s)n=s;else if(i.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),n=await it(t.labelText,t.options),n=n?.trim()||n;let a=i.find(l=>l.toLowerCase()===n?.toLowerCase());a?n=a:(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${i[0]}"`),n=i[0])}t.answer=n,await xl(e,t,n)}else if(t?.type==="checkbox"){let n=await it(t.labelText,t.options);t.answer=n,await Cl(e,t,n)}else if(t?.type==="file"){let n=process.env.RESUME_PDF_URL;t.answer=n;let i=await fetch(n);if(!i.ok)throw new Error("Network response was not ok");let s=await i.arrayBuffer();await Al(e,t,s)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let o=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${o}" \u2192 ${r}`),t}async function El(e){return await e.evaluate(async()=>{let t=[],o=document.querySelectorAll(".fb-dash-form-element");if(!o||o.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(o=r.querySelectorAll(".fb-dash-form-element"))}if(!o||o.length===0)return[];for(let r of o){let n=r.querySelector(".artdeco-text-input--label")||r.querySelector("legend .fb-dash-form-element__label-title--is-required")||r.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||r.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=!!r.querySelector(".fb-dash-form-element__label-title--is-required")||!!r.querySelector('[class*="required"]')||!!r.querySelector(".artdeco-inline-feedback__message"),s=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),l=r.querySelector("select[data-test-text-entity-list-form-select]"),u=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),c=r.querySelector('input[type="file"]');if(n&&s&&a.length===0){let f=n.textContent.trim();t.push({type:"input",labelText:f,answer:s.value,isRequired:i,wasPreFilled:!!s.value})}else if(n&&a.length){let f=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,d=Array.from(a).map(m=>m.value),p=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:d,answer:p,isRequired:i,wasPreFilled:!!p})}else if(l){let f=r.querySelector('label[for="'+l.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),d=f?.querySelector("span:nth-of-type(2)")?.textContent.trim()||f?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||f?.querySelector("span")?.textContent.trim()||f?.textContent?.trim()||null,p=Array.from(l.options).map(h=>h.value).filter(h=>h!=="Select an option"),m=l.value!=="Select an option"?l.value:"";t.push({type:"select",labelText:d,options:p,answer:m,isRequired:i,wasPreFilled:!!m})}else if(u.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),d=Array.from(u).map(h=>({label:h.nextElementSibling?.textContent?.trim()||h.value,checked:h.checked})),p=d.some(h=>h.checked),m=d.filter(h=>h.checked).map(h=>h.label).join(", ");t.push({type:"checkbox",labelText:f,options:d.map(h=>h.label),answer:m,isRequired:i,wasPreFilled:p})}else if(c){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:c.value?"uploaded":"",isRequired:i,wasPreFilled:!!c.value})}}return t})}async function Ko(e,t,o){return await e.evaluate(async(r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector(".artdeco-text-input--label")||s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||s.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),l=s.querySelector(".artdeco-text-input--input")||s.querySelector("input");if(a&&l&&r===a.textContent.trim()){l.value=n;let u=new Event("input",{bubbles:!0});if(l.dispatchEvent(u),r==="City"||r==="Location (city)"){let c=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(m)},f=p=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(m)};await(async p=>{await new Promise(m=>setTimeout(m,500)),f(p),await new Promise(m=>setTimeout(m,100)),c(p)})(l)}return!0}}return!1},t,o)}async function $l(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let l=s.querySelector("legend .fb-dash-form-element__label-title--is-required")||s.querySelector('legend [class*="fb-dash-form-element__label"]')||s.querySelector("legend span");if((l?.querySelector("span:nth-of-type(1)")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let c=(n||"").toLowerCase();for(let f of a){let d=f.getRootNode(),m=(f.id&&d.querySelector(`label[for="${f.id}"]`)||f.nextElementSibling)?.textContent?.trim()||"";if(f.value.toLowerCase()===c||m.toLowerCase()===c)return f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function _l(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let s of i){let a=s.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let l=s.querySelector(`label[for="${a.id}"]`)||s.querySelector(".fb-dash-form-element__label-title--is-required");if((l?.querySelector("span:nth-of-type(2)")?.textContent.trim()||l?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||l?.querySelector("span")?.textContent.trim()||l?.textContent?.trim())!==r)continue;let c=Array.from(a.options),f=(n||"").toLowerCase(),d=c.find(p=>p.text.toLowerCase()===f)||c.find(p=>p.value.toLowerCase()===f)||c.find(p=>p.text.toLowerCase().includes(f));return d?(a.value=d.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function Tl(e,t,o){return await e.evaluate((r,n)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let a=document.querySelector("#interop-outlet")?.shadowRoot;a&&(i=a.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;let s=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(s.length===0)return!1;for(let a of i){let l=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(l.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let c=!1;for(let f of l){let d=(f.nextElementSibling?.textContent||f.value||"").trim().toLowerCase();s.includes(d)&&!f.checked&&(f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),c=!0)}return c}return!1},t,o)}async function Rl(e,t){for(let o of t){if(!o.labelText||o.isRequired||o.wasPreFilled||o.answer||o.type==="datePicker"||o.type==="file")continue;let r="";try{if(o.type==="input")r=await to(o.labelText,"");else if(o.type==="radio")r=await xt(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await it(o.labelText,o.options||[]);else continue}catch(s){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${s.message?.slice(0,80)}`);continue}if(r=(r||"").trim(),o.wasOptional=!0,!r){o.answer="",console.log(` ? [opt ${o.type}] "${o.labelText.slice(0,55)}" \u2192 (empty)`);continue}let n=!1;try{o.type==="input"?n=await Ko(e,o.labelText,r):o.type==="radio"?n=await $l(e,o.labelText,r):o.type==="select"?n=await _l(e,o.labelText,r):o.type==="checkbox"&&(n=await Tl(e,o.labelText,r))}catch(s){console.log(` \u26A0 setter failed for "${o.labelText}": ${s.message?.slice(0,80)}`)}o.answer=r,console.log(` ? [${n?"opt":"opt-noapply"} ${o.type}] "${o.labelText.slice(0,55)}" \u2192 "${r.slice(0,50)}"`)}}async function Jr(e,t){let o=[],r=!0,n=0,i=null,s=0;for(;r;){if(n++,await Qt(e))return console.log(" Daily limit reached during form navigation"),await Yr(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let u=(await El(e)).filter(p=>!o.some(m=>m.labelText===p.labelText));o.push(...u);try{let p=o.find(h=>h.labelText==="City"||h.labelText==="Location (city)"),m=o.filter(h=>h.labelText!=null).find(h=>h.labelText!==null&&h.labelText.trim()!==null&&(h.labelText.trim().toLowerCase()==="cv"||h.labelText.trim().toLowerCase()==="curriculum vitae"||h.labelText.trim().toLowerCase()==="cover letter"||h.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let h=process.env.City;await Ko(e,p.labelText,h),p.answer=h}else if(m){let h=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==h)&&(await w(1e4),await Ko(e,m.labelText,h),m.answer=h,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Rl(e,u)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let c=null;try{c=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(c!==null){if(c.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:c};let p=c&&o.find(h=>h.errorMsgText&&h.labelText===c.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(c,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:c};let m=o.findIndex(h=>h.labelText===c.labelText&&!h.answer);m!==-1&&o.splice(m,1),o.push(c)}let f=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of p){let h=m.querySelectorAll("button");for(let g of h){let y=g.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return g.click(),y}}return null});f&&console.log(` Dismissed safety popup (${f})`);let d=await e.evaluate(async()=>{function p(b){let v=document.querySelector(b);if(v)return v;let L=document.querySelector("#interop-outlet")?.shadowRoot;return L?L.querySelector(b):null}function m(b){let v=document.querySelectorAll(b),L=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(b);return[...v||[],...L||[]]}let h=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(b=>b.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(b=>b.innerText.trim()==="Review")||m("button").some(b=>b.innerText.trim()==="Review"&&b.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),S=async()=>{let b=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(v=>v.innerText?.trim()==="Next");b?b.click():console.log("Next button not found")},C=()=>{let b=m("button").find(v=>v.innerText?.trim()==="Review");b&&b.click()};return h?(await S(),{type:"next"}):g?(await C(),{type:"review"}):y?{type:"submit"}:{type:null}});if(d==null)return{filledFields:o,formPages:n,skip:!0};if(d.type&&console.log(` \u2192 ${d.type}`),d.type===null){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of m){let g=h.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of g){let S=y.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let C of y.querySelectorAll("button")){let b=C.innerText?.trim();if(b==="Not now"||b==="Done"||b==="Dismiss"||b==="Got it")return C.click(),b}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await w(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(s===0){let m=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],y=[];for(let S of h){for(let b of S.querySelectorAll("button")){let v=b.innerText?.trim();v&&v.length<60&&g.push(v)}let C=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');C&&y.push(C.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(m.buttons)}`),m.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(m.modalText)}`)}}if(d.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(c===null&&d.type===i?s++:s=0,i=d.type,s>=5){let p=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),h=[],g=[];for(let y of m){for(let S of y.querySelectorAll(".artdeco-inline-feedback__message"))h.push(S.textContent?.trim()?.slice(0,60));for(let S of y.querySelectorAll(".fb-dash-form-element")){let C=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),b=S.querySelector("input, select, textarea"),v=!!S.querySelector(".artdeco-inline-feedback__message");C&&(v||b&&!b.value)&&g.push({label:C.slice(0,40),hasError:v,value:b?.value?.slice(0,20)||""})}}return{errors:h,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${d.type}" for ${s} iterations \u2014 form not progressing.`),p.errors.length&&console.error(` Visible errors: ${JSON.stringify(p.errors)}`),p.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(p.emptyRequired)}`),console.error(" Skipping job."),{filledFields:o,formPages:n,skip:!0,duplicateField:{labelText:`stuck_on_${d.type}`}}}await w(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function Hr(e){try{await e.evaluate(()=>{let t=document.getElementById("follow-company-checkbox");t?(t.checked=!1,t.dispatchEvent(new Event("change",{bubbles:!0}))):console.warn("Unfollow checkbox not found.")})}catch(t){console.error("Error in unfollowJobCheckbox:",t)}}async function Il(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let o=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=o?.asElement?.()||null,t||await o.dispose().catch(()=>{})}t&&await t.click()}async function Dl(e){try{let t=await e.evaluate(()=>{let o=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of o){for(let i of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(i.innerText?.trim()==="Done")return i.click(),"Done";let n=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let i of n){let s=i.innerText||"";if(s.includes("application was sent")||s.includes("Application sent")||s.includes("resume into a profile")||s.includes("Next best action"))for(let a of i.querySelectorAll("button")){let l=a.innerText?.trim();if(l==="Not now"||l==="Dismiss")return a.click(),l}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await w(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function Kt(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await w(1e3)):console.log("Popup \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.")}catch{console.log("closeJobApplicationPopup failed to execute: \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D \u0438\u043B\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F.")}}async function Wo(e){try{await e.waitForSelector('button[data-control-name="discard_application_confirm_btn"]',{timeout:3e3});let t=await e.$('button[data-control-name="discard_application_confirm_btn"]');t&&(await t.click(),console.log("Discard confirmed"),await w(500))}catch{console.log("No discard confirmation needed")}}async function Kr(e,t){let o=[],r=t._fromQueue;try{k.attempted++,console.log(`
|
|
297
|
+
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&Co(n)?.status==="applied")return k.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let i=null;if(!r){let d=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name")?.innerText?.trim()?.replace(/\s+/g," ")?.toLowerCase()||""),p=(t.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),m=d.split(" ")[0],h=p.split(" ")[0];if(m&&h&&!d.includes(h)&&!p.includes(m))return k.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${d}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let y=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!y)return!1;let S=y.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(S)||S.includes("Application submitted")}))return k.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&Fe(n,"applied",{source:"detected"}),{keepGoing:!0};try{i=await ir(e)}catch{}}let s=await Ur(e);if(s.dailyLimitReached){console.log(`
|
|
298
298
|
========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
|
|
299
|
-
`);let
|
|
299
|
+
`);let d=He("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${d.total}`),console.log(` - This session: ${Xt}`),console.log(` - Unprocessed: ${d.unprocessed}`),k.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:d}}if(!s.clicked)return k.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await Hr(e);let a=await ul();console.log(`Applying for job: ${t.id}`);let l=`### Job Information
|
|
300
300
|
- **Counter:** ${a}
|
|
301
301
|
- **Job Title:** ${t.jobTitle}
|
|
302
302
|
- **Company:** ${t.companyName}
|
|
303
303
|
- **Location:** ${t.location}
|
|
304
304
|
- **Salary:** ${t.salary}
|
|
305
|
-
- **Job URL:** ${t.href}`,
|
|
306
|
-
Closing browser...`);try{await o.close()}catch{}process.exit(0)};process.on("SIGINT",
|
|
305
|
+
- **Job URL:** ${t.href}`,u=process.env.NODE_EASY_APPLY_MAIN;await Ie.addMessage(u,l,{lifebot:Fr.off});let c=await Je("Should I apply for this job? Answer only 'yes' or 'no'!!");if(Or(),console.log(`Should I apply for ${t.jobTitle} ?? `+c),c.toLowerCase()==="no"){k.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await Kt(e),await Wo(e),await Mr(e,t.id);let d=t.id?.match(/\d+/)?.[0];return ze({jobId:d,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),Fe(d,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let f=await Jr(e,Br);if(f.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await Ur(e)).clicked?f=await Jr(e,Br):(console.log(" pressApplyButton failed on retry"),f={filledFields:[],formPages:0,skip:!0,duplicateField:{labelText:"stale_popup_retry_failed"}})),console.log(`processNavigation: pages=${f.formPages}, fields=${f.filledFields?.length||0}, skip=${f.skip}${f.dailyLimitReached?", DAILY LIMIT":""}`),f.dailyLimitReached)return console.log(" Daily limit reached \u2014 stopping"),await Kt(e),{keepGoing:!1,dailyLimitReached:!0};if(f.skip){if(await Kt(e),await Wo(e),f.duplicateField){await Mr(e,t.id);let d=process.env.NODE_EASY_APPLY_ERRORS;await Ie.addMessage(d,`${t.href} failed at label ${f.duplicateField?.labelText}`,{lifebot:Fr.off})}k.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${f.duplicateField?.labelText||"form error"}`),ze({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"failed",formPages:f.formPages,failedField:f.duplicateField?.labelText||null,questions:f.filledFields||[]})}else{o=f.filledFields,o.length,await Hr(e),await Il(e),await w(2e3),await Dl(e),k.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${f.formPages} pages, ${o.length} fields)`);let d=t.id?.match(/\d+/)?.[0];if(d&&(Rt(d,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),vo(d,{title:t.jobTitle,company:i?.companyName||t.companyName,companyUrl:i?.companyUrl,location:t.location,salary:t.salary,url:t.href,isEasyApply:!0,applyType:"easy-apply",applied:!0,appliedAt:new Date().toISOString().slice(0,10),description:i?.description,techStack:i?.techStack,jobTags:i?.jobTags,seniority:i?.seniority,employmentType:i?.employmentType,industries:i?.industries,jobFunction:i?.jobFunction,postedTime:i?.postedTime,applicantCount:i?.applicantCount,companySize:i?.companySize,workplaceType:i?.workplaceType,contractType:i?.contractType,aboutCompany:i?.aboutCompany}),Fe(d,"applied",{source:"easy-apply"}),i?.companyUrl&&Ut(i.companyUrl,{name:i.companyName||t.companyName,about:i.aboutCompany,size:i.companySize,industries:i.industries,jobId:d})),await wl(e,t),ze({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:f.formPages,questions:o}),!pl())return{keepGoing:!1}}}catch(n){if(nt(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;let i=Wr(n);if(!i)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),console.log(n),{keepGoing:!1};if(i.severity==="fatal")return console.log(`\u274C [${i.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),i.instructions&&console.log(` \u2192 ${i.instructions}`),i.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":i.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin"),{keepGoing:!1};let s=fl(i.label);if(console.log(`\u26A0 [${i.label}] on "${t.jobTitle}" (${s}/${i.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),i.cleanup==="popup"){try{await Kt(e)}catch{}try{await Wo(e)}catch{}}return s>=i.maxConsecutive?(console.log(`\u274C [${i.label}] ${i.maxConsecutive} consecutive \u2014 stopping.`),i.instructions&&console.log(` \u2192 ${i.instructions}`),{keepGoing:!1}):(i.cooldownMs&&await w(i.cooldownMs),{keepGoing:!0})}return Or(),{keepGoing:!0}}async function jl(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],i=0;for(;;){await Yo(e,r)&&(await oe(e),await w(2e3));try{await e.waitForSelector("li.scaffold-layout__list-item",{timeout:3e4})}catch{}await o(e);let a=await hl(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(i++,i>3){console.log(" Too many recovery attempts \u2014 LinkedIn keeps redirecting. Stopping.");break}console.log(` No jobs found but not on /jobs/ page \u2014 recovery attempt ${i}/3...`),await Yo(e,r);continue}let u=await e.evaluate(()=>({totalCards:document.querySelectorAll("li.scaffold-layout__list-item").length,hasListContainer:!!document.querySelector(".jobs-search-results-list, .scaffold-layout__list-container")}));u.totalCards===0?console.log(` \u26A0 No job cards on page (container present: ${u.hasListContainer}). Either the search returned nothing, the page never finished loading, or LinkedIn changed its markup.`):console.log(` ${u.totalCards} job card(s) on page but none are Easy Apply \u2014 nothing to apply to with this search filter.`);break}if(i=0,n.length===0){n=a;let{keepGoing:l}=await qr(e,a,t);if(!l)return{keepGoing:!1,jobsDone:n}}else{let l=a.filter(c=>!n.some(f=>f.id===c.id));if(console.log(` New jobs on page: ${l.length} (page: ${a.length}, total seen: ${n.length})`),l.length===0)break;let{keepGoing:u}=await qr(e,l,t);if(n=[...n,...l],!u)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var k={attempted:0,submitted:0,skippedByLifebot:0,failed:0,mismatch:0,alreadyApplied:0,expired:0,noApplyButton:0,dailyLimitHit:!1,cdpRecoveries:0,browserRestarts:0,fatalAuthExpired:null};(async()=>{let e=process.argv.find(l=>l.startsWith("--job-urls=")),t=Sr("apply",e?"queue":"search"),o=null,r=null,n=[],i=async()=>(await Jo(Pr,{devtools:!1})).browser,s=async l=>{await l.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>Wt();try{let l=await Jo(Pr,{devtools:!1});o=l.browser;let u=async()=>{console.log(`
|
|
306
|
+
Closing browser...`);try{await o.close()}catch{}process.exit(0)};process.on("SIGINT",u),process.on("SIGTERM",u);let c=await o.newPage();await s(c),await Rr(c,l);let f=process.argv.find(_=>_.startsWith("--job-urls=")),d=f?f.split("=").slice(1).join("=").replace(/^@/,""):null,p=process.env.LINKEDIN_SEARCH_URL,m=d?"https://www.linkedin.com/feed/":p;try{await c.goto(m,{waitUntil:"domcontentloaded",timeout:6e4})}catch(_){console.error("\u274C Navigation error:",_.message),console.log("Trying to continue anyway..."),await w(5e3)}let h=c.url();if(/\/login|\/checkpoint|\/authwall|\/uas\/login/.test(h))throw new Error("Not logged in (or session expired). Run: ilml linkedin login");console.log("\u2713 Logged in to LinkedIn.");let g=He("recruiters-from-jobs");g.total>0&&console.log(`
|
|
307
307
|
\u{1F4C2} Existing recruiters for today: ${g.total} (${g.unprocessed} unprocessed)
|
|
308
|
-
`),await w(2e3);let y={page:c,browser:o,recoveryCtx:{searchUrl:p,launchFn:
|
|
309
|
-
\u{1F4CB} Queue mode: ${_.length} jobs from ${
|
|
310
|
-
`);for(let
|
|
311
|
-
[${
|
|
312
|
-
Queue complete. ${S?"Daily limit hit.":"Continuing to search..."}`)}catch(_){console.error(`Failed to read job URLs file: ${_.message}`)}if(!S){if(
|
|
313
|
-
Queue done. Continuing with standard search...`);try{await c.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3)}catch(_){console.error(" Navigation to search failed:",_.message)}}y.page=c,y.browser=o;try{await
|
|
314
|
-
\u274C Apply phase ended: CDP channel could not be recovered after ${
|
|
308
|
+
`),await w(2e3);let y={page:c,browser:o,recoveryCtx:{searchUrl:p,launchFn:i,setupPage:s,cookiesProvider:a}},S=!1;if(d)try{let _=JSON.parse(Vr.readFileSync(d,"utf-8"));console.log(`
|
|
309
|
+
\u{1F4CB} Queue mode: ${_.length} jobs from ${d}
|
|
310
|
+
`);for(let J=0;J<_.length;J++){let T=typeof _[J]=="string"?{url:_[J]}:_[J],O=T.url,x=T.title||"Unknown",M=T.company||"";console.log(`
|
|
311
|
+
[${J+1}/${_.length}] ${x} @ ${M}`),console.log(` ${O}`),c=y.page,o=y.browser;try{let q=O.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await c.goto(O,{waitUntil:"domcontentloaded",timeout:6e4}),await w(8e3);let R=await c.evaluate(()=>{let de=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:de.includes("Application submitted"),noLongerAccepting:de.includes("No longer accepting applications")}});if(R.alreadyApplied){console.log(" Already applied \u2014 skipping"),k.alreadyApplied++,Fe(q,"applied",{applyMethod:"detected"});continue}if(R.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),k.expired++,Fe(q,"expired",{reason:"no_longer_accepting"});continue}if(!R.hasApply){console.log(" No Easy Apply button \u2014 skipping"),k.noApplyButton++;continue}let W={id:`/jobs/view/${q}/`,href:O,jobTitle:x,companyName:M,location:T.location||"",salary:T.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let ue=await Kr(c,W);if(console.log(` Result: keepGoing=${ue.keepGoing}, reason=${ue.dailyLimitReached?"daily_limit":"ok"}`),!ue.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),S=!0;break}}catch(q){if(nt(q))try{await zt(y,`queue job ${J+1}: ${q.message?.slice(0,80)}`),c=y.page,o=y.browser}catch(R){console.error(`\u274C Queue mode: CDP recovery failed: ${R.message}`),console.error(" Aborting queue, falling back to standard search if possible.");break}else{let R=Wr(q);if(R?.severity==="fatal"){console.error(`\u274C [${R.label}] Fatal \u2014 stopping queue: ${(q.message||"").slice(0,120)}`),R.instructions&&console.error(` \u2192 ${R.instructions}`),R.label==="ilml-auth-expired"?k.fatalAuthExpired="ilml":R.label==="linkedin-session-expired"&&(k.fatalAuthExpired="linkedin");break}console.error(` Error: ${q.message?.slice(0,80)}`)}}}console.log(`
|
|
312
|
+
Queue complete. ${S?"Daily limit hit.":"Continuing to search..."}`)}catch(_){console.error(`Failed to read job URLs file: ${_.message}`)}if(!S){if(d){console.log(`
|
|
313
|
+
Queue done. Continuing with standard search...`);try{await c.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3)}catch(_){console.error(" Navigation to search failed:",_.message)}}y.page=c,y.browser=o;try{await bl(y)}catch(_){nt(_)||/CDP unrecoverable/.test(_.message||"")?(console.error(`
|
|
314
|
+
\u274C Apply phase ended: CDP channel could not be recovered after ${k.cdpRecoveries} page recoveries and ${k.browserRestarts} browser restarts.`),console.error(` Last error: ${_.message}`)):/Session expired/i.test(_.message||"")?(console.error(`
|
|
315
315
|
\u274C Apply phase ended: ${_.message}`),r=_):console.error(`
|
|
316
|
-
\u26A0 Apply phase crashed: ${_.message}`)}c=y.page,o=y.browser}let
|
|
317
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let _ of n)console.log(` ${_}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let
|
|
318
|
-
\u26A0 Skipping recruiter funnel \u2014 ${
|
|
319
|
-
--- Funnel: today's recruiters (${
|
|
320
|
-
--- Funnel: backfill from previous days (${T.length} unprocessed) ---`),console.log(` Quota remaining: ${
|
|
321
|
-
\u2705 Funnel done. Connection quota left: ${
|
|
322
|
-
\u274C Apply session ended with error: ${l.message}`),l.stack&&console.error(l.stack)}
|
|
316
|
+
\u26A0 Apply phase crashed: ${_.message}`)}c=y.page,o=y.browser}let C=k.submitted+k.skippedByLifebot+k.failed+k.mismatch+k.alreadyApplied+k.expired+k.noApplyButton,b=k.attempted-C,v=He("recruiters-from-jobs");n.push(`Jobs attempted: ${k.attempted}`),n.push(`Successfully applied: ${k.submitted}`),n.push(`Skipped by Lifebot: ${k.skippedByLifebot}`),n.push(`Failed (form errors): ${k.failed}`),k.mismatch>0&&n.push(`Mismatch (wrong panel): ${k.mismatch}`),k.alreadyApplied>0&&n.push(`Already applied: ${k.alreadyApplied}`),k.expired>0&&n.push(`Expired (closed): ${k.expired}`),k.noApplyButton>0&&n.push(`No Apply button: ${k.noApplyButton}`),b>0&&n.push(`Unaccounted: ${b}`),n.push(`Daily limit reached: ${k.dailyLimitHit?"Yes":"No"}`),k.cdpRecoveries>0&&n.push(`Page recoveries (CDP): ${k.cdpRecoveries}`),k.browserRestarts>0&&n.push(`Browser restarts: ${k.browserRestarts}`),n.push(`Recruiters found: ${Xt}`),n.push(`Recruiters total: ${v.total} (${v.unprocessed} unprocessed)`),console.log(`
|
|
317
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let _ of n)console.log(` ${_}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let L=!!o&&o.isConnected?.()!==!1,I=sl?L?k.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":k.fatalAuthExpired==="ilml"?"iLiveMyLife token expired (run: ilml login)":null:"browser is not in a usable state":"recruiter auto-connect is disabled (FUNNEL_CONNECT_RECRUITERS=false)",N=!I;N||(console.log(`
|
|
318
|
+
\u26A0 Skipping recruiter funnel \u2014 ${I}.`),console.log(` ${v.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${I})`));let{markProfileProcessed:E}=await Promise.resolve().then(()=>(ro(),an)),{canSendConnection:D,getQuotaStatus:K}=await Qe().then(()=>$n),B=()=>({message:cl,useCustomMessage:ll,maxConnections:al,excludeLocations:Ho,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(_,J,T)=>{E("recruiters-from-jobs",_.profileUrl,{status:T.reason,connectionSent:T.connectionSent,withCustomMessage:T.withCustomMessage,message:T.messageSent,method:T.method,reason:T.reason,error:T.error,profileInfo:T.profileInfo},_._fromDate||null)}});if(N&&v.unprocessed>0){console.log(`
|
|
319
|
+
--- Funnel: today's recruiters (${v.unprocessed}) ---`),Ho.length>0&&console.log(` Excluding locations: ${Ho.join(", ")}`);let _=At("recruiters-from-jobs");await Ro(c,_,B())}let Y=D();if(N&&Y.allowed){let _=Et("recruiters-from-jobs"),J=new Date().toISOString().split("T")[0],T=_.filter(O=>O._fromDate!==J);if(T.length>0){let O=K();console.log(`
|
|
320
|
+
--- Funnel: backfill from previous days (${T.length} unprocessed) ---`),console.log(` Quota remaining: ${O.daily.remaining} today, ${O.weekly.remaining} this week`),await Ro(c,T,{...B(),maxConnections:O.daily.remaining})}}let G=K();console.log(`
|
|
321
|
+
\u2705 Funnel done. Connection quota left: ${G.daily.remaining} of ${G.daily.max} today, ${G.weekly.remaining} of ${G.weekly.max} this week`),n.push(`Connection quota left: ${G.daily.remaining} of ${G.daily.max} today, ${G.weekly.remaining} of ${G.weekly.max} week`)}catch(l){r=l,console.error(`
|
|
322
|
+
\u274C Apply session ended with error: ${l.message}`),l.stack&&console.error(l.stack)}kr(t,r?"error":"success",{summaryLines:n,dailyLimitHit:k.dailyLimitHit,attempted:k.attempted,submitted:k.submitted,failed:k.failed,skippedByLifebot:k.skippedByLifebot},r?r.message:null);try{await o?.close()}catch{}r&&process.exit(1)})();
|