ilml-plugin-linkedin 1.4.0 → 1.5.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/dist/run.mjs CHANGED
@@ -1,52 +1,52 @@
1
- var en=Object.defineProperty;var pt=(e,t)=>()=>(e&&(t=e(e=0)),t);var ft=(e,t)=>{for(var n in t)en(e,n,{get:t[n],enumerable:!0})};var Kt={};ft(Kt,{default:()=>cn,getAllUnprocessedProfiles:()=>Ge,getSummary:()=>de,getUnprocessedProfiles:()=>Je,listFiles:()=>zt,loadProfiles:()=>Be,markProfileProcessed:()=>Qt,saveProfile:()=>Ce,saveProfiles:()=>Yt});import"dotenv/config";import*as T from"fs";import*as J from"path";import{fileURLToPath as rn}from"url";function xe(){T.existsSync(Q)||T.mkdirSync(Q,{recursive:!0})}function an(e,t){try{let n=`${e}-${yt()}.json`,r=T.readdirSync(Q).filter(i=>i.startsWith(e)&&i.endsWith(".json")&&i!==n),o=0;for(let i of r)JSON.parse(T.readFileSync(J.join(Q,i),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&o++;return o}catch{return 0}}function yt(){return new Date().toISOString().split("T")[0]}function ht(e,t=null){let n=t||yt();return J.join(Q,`${e}-${n}.json`)}function Be(e,t=null){xe();let n=ht(e,t);try{if(T.existsSync(n)){let r=T.readFileSync(n,"utf-8"),o=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${o.profiles.length} profiles from ${n}`),o.profiles}}catch(r){console.error(`Error loading profiles from ${n}:`,r.message)}return[]}function Ce(e,t){xe();let n=ht(e),r={source:e,date:yt(),lastUpdated:new Date().toISOString(),profiles:[]};try{T.existsSync(n)&&(r=JSON.parse(T.readFileSync(n,"utf-8")))}catch(l){console.error(`Error reading ${n}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===t.profileUrl))return!1;let i=an(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:i}),r.lastUpdated=new Date().toISOString();try{T.writeFileSync(n,JSON.stringify(r,null,2));let l=i>0?` (seen ${i} day${i>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${n}:`,l.message),!1}}function Yt(e,t){let n=0;for(let r of t)Ce(e,r)&&n++;return n}function Je(e,t=null){return Be(e,t).filter(r=>!r.processed)}function Qt(e,t,n,r=null){xe();let o=ht(e,r);try{if(!T.existsSync(o))return;let i=JSON.parse(T.readFileSync(o,"utf-8")),l=i.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let a=n.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),T.writeFileSync(o,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function de(e){let t=Be(e),n=t.filter(o=>o.processed),r=t.filter(o=>!o.processed);return{total:t.length,processed:n.length,unprocessed:r.length,statuses:n.reduce((o,i)=>(o[i.status]=(o[i.status]||0)+1,o),{})}}function zt(){xe();try{return T.readdirSync(Q).filter(t=>t.endsWith(".json")).map(t=>{let[n,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let o=JSON.parse(T.readFileSync(J.join(Q,t),"utf-8"));return{file:t,source:n,date:r,count:o.profiles?.length||0,unprocessed:o.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}function Ge(e){xe();let t=[];try{let o=T.readdirSync(Q).filter(i=>i.startsWith(e+"-")&&i.endsWith(".json")).sort().reverse();for(let i of o)try{let l=JSON.parse(T.readFileSync(J.join(Q,i),"utf-8"));l.profiles&&t.push({file:i,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let n=new Set,r=[];for(let{date:o,profiles:i}of t)for(let l of i)!l.processed&&l.profileUrl&&!n.has(l.profileUrl)&&(n.add(l.profileUrl),r.push({...l,_fromDate:o}));return r}var sn,ln,Q,cn,bt=pt(()=>{sn=rn(import.meta.url),ln=J.dirname(J.dirname(sn)),Q=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"collected-profiles"):J.join(ln,"collected-profiles");cn={loadProfiles:Be,saveProfile:Ce,saveProfiles:Yt,getUnprocessedProfiles:Je,getAllUnprocessedProfiles:Ge,markProfileProcessed:Qt,getSummary:de,listFiles:zt}});var $t={};ft($t,{addEncounter:()=>he,canSendConnection:()=>tt,commitDataSnapshot:()=>ao,default:()=>bn,getAllApplications:()=>io,getPersonStatus:()=>ze,getQuestionStats:()=>lo,getQuotaStatus:()=>Te,getRecentConnections:()=>et,linkPersonToJob:()=>Qe,loadApplicationQuestions:()=>Ct,loadConversations:()=>eo,loadJobs:()=>Ve,loadPeople:()=>K,loadQuota:()=>Xe,loadSyncState:()=>no,logApplicationQuestions:()=>be,migrateFromDailyFiles:()=>oo,recordConnectionSent:()=>Ze,resetCaches:()=>fn,saveConversations:()=>to,saveJobs:()=>We,savePeople:()=>se,saveQuota:()=>xt,saveSyncState:()=>ro,updateConnectionStatus:()=>Ke,upsertJob:()=>Ye,upsertPerson:()=>Ae});import"dotenv/config";import*as E from"fs";import*as j from"path";import{fileURLToPath as un}from"url";import{execSync as gt}from"child_process";function fn(){pe=null,fe=null,z=null,ne=null,me=null,oe=null}function M(){E.existsSync(F)||E.mkdirSync(F,{recursive:!0})}function re(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";E.writeFileSync(r,n);for(let o=0;o<3;o++)try{E.renameSync(r,e);return}catch(i){if(o<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Ee(e,t){if(!E.existsSync(e))return null;try{let n=JSON.parse(E.readFileSync(e,"utf-8"));try{E.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${j.resolve(e)}`);let r=e+".backup";if(E.existsSync(r))try{let o=JSON.parse(E.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{E.copyFileSync(r,e)}catch{}return o}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{E.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}function K(){return pe||(M(),pe=Ee(wt,"people.json")||{},pe)}function se(e){M(),pe=e;try{re(wt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${j.resolve(wt)}`)}}function Ve(){return fe||(M(),fe=Ee(St,"jobs.json")||{},fe)}function We(e){M(),fe=e;try{re(St,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${j.resolve(St)}`)}}function eo(){return ne||(M(),ne=Ee(He,"conversations.json")||{},mn(ne),ne)}function mn(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let o=(n.messages||[]).find(i=>i.status==="draft");o&&n.draftStatus&&n.draftStatus!=="pending"&&(o.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{re(He,e)}catch{}}}function to(e){M(),ne=e;try{re(He,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${j.resolve(He)}`)}}function Ae(e,t={}){if(!e)return null;let n=K(),r=ye(),o=new Date().toISOString(),i=n[e];if(i){i.seenCount=(i.seenCount||1)+1,i.lastSeen=r,i.lastUpdated=o,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of kt)t[l]!=null&&(i[l]=t[l])}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:o};return se(n),n[e]}function Ye(e,t={}){if(!e)return null;let n=Ve(),r=ye(),o=n[e];if(o){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 l of i)t[l]!=null&&(o[l]=t[l])}else n[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 We(n),n[e]}function Qe(e,t){if(!e||!t)return;let n=K(),r=n[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),se(n)))}function he(e,t){if(!e||!t)return;let n=K(),r=n[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(),se(n))}function ze(e){return e&&K()[e]?.connectionStatus||null}function Ke(e,t,n={}){if(!e)return;let r=K(),o=r[e];if(o||(Ae(e,n.profileInfo||{}),o=r[e]),!!o){if(o.connectionStatus=t,o.connectionDate=ye(),o.connectionMethod=n.method||o.connectionMethod,o.messageSent=n.messageSent||o.messageSent,o.lastUpdated=new Date().toISOString(),n.profileInfo)for(let i of kt)n.profileInfo[i]!=null&&(o[i]=n.profileInfo[i]);se(r)}}function Xe(){return z||(M(),z=Ee(Xt,"quota.json"),(!z||!z.connections)&&(z={connections:[]}),z)}function xt(e){M(),z=e;try{re(Xt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Ze(e,t="unknown"){let n=Xe(),r=new Date;n.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),xt(n)}function et(){let e=Xe(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=n)}function tt(){let e=et(),t=ye(),n=e.filter(s=>s.date===t).length,r=e.length,o=n>=$e,i=r>=_e,l=!o&&!i,a={allowed:l,daily:{sent:n,max:$e},weekly:{sent:r,max:_e}};return l||(a.reason=o?`Daily limit reached (${n}/${$e})`:`Weekly limit reached (${r}/${_e})`),a}function Te(){let e=et(),t=ye(),n=e.filter(o=>o.date===t).length,r=e.length;return{daily:{sent:n,max:$e,remaining:$e-n},weekly:{sent:r,max:_e,remaining:_e-r}}}function yn(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function oo(){M();let e=E.readdirSync(F).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(`
1
+ var en=Object.defineProperty;var pt=(e,t)=>()=>(e&&(t=e(e=0)),t);var mt=(e,t)=>{for(var o in t)en(e,o,{get:t[o],enumerable:!0})};var Xt={};mt(Xt,{default:()=>cn,getAllUnprocessedProfiles:()=>He,getSummary:()=>de,getUnprocessedProfiles:()=>Ge,listFiles:()=>Kt,loadProfiles:()=>Je,markProfileProcessed:()=>zt,saveProfile:()=>$e,saveProfiles:()=>Qt});import"dotenv/config";import*as T from"fs";import*as J from"path";import{fileURLToPath as rn}from"url";function Ce(){T.existsSync(Q)||T.mkdirSync(Q,{recursive:!0})}function an(e,t){try{let o=`${e}-${bt()}.json`,r=T.readdirSync(Q).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==o),n=0;for(let s of r)JSON.parse(T.readFileSync(J.join(Q,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function bt(){return new Date().toISOString().split("T")[0]}function ht(e,t=null){let o=t||bt();return J.join(Q,`${e}-${o}.json`)}function Je(e,t=null){Ce();let o=ht(e,t);try{if(T.existsSync(o)){let r=T.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 $e(e,t){Ce();let o=ht(e),r={source:e,date:bt(),lastUpdated:new Date().toISOString(),profiles:[]};try{T.existsSync(o)&&(r=JSON.parse(T.readFileSync(o,"utf-8")))}catch(l){console.error(`Error reading ${o}:`,l.message)}if(r.profiles.some(l=>l.profileUrl===t.profileUrl))return!1;let s=an(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{T.writeFileSync(o,JSON.stringify(r,null,2));let l=s>0?` (seen ${s} day${s>1?"s":""} before)`:"";return console.log(`\u{1F4BE} Saved: ${t.name||t.profileUrl}${l} (total: ${r.profiles.length})`),!0}catch(l){return console.error(`Error saving to ${o}:`,l.message),!1}}function Qt(e,t){let o=0;for(let r of t)$e(e,r)&&o++;return o}function Ge(e,t=null){return Je(e,t).filter(r=>!r.processed)}function zt(e,t,o,r=null){Ce();let n=ht(e,r);try{if(!T.existsSync(n))return;let s=JSON.parse(T.readFileSync(n,"utf-8")),l=s.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let a=o.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}s.lastUpdated=new Date().toISOString(),T.writeFileSync(n,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function de(e){let t=Je(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 Kt(){Ce();try{return T.readdirSync(Q).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(T.readFileSync(J.join(Q,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 He(e){Ce();let t=[];try{let n=T.readdirSync(Q).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of n)try{let l=JSON.parse(T.readFileSync(J.join(Q,s),"utf-8"));l.profiles&&t.push({file:s,date:l.date,profiles:l.profiles})}catch{}}catch{return[]}let o=new Set,r=[];for(let{date:n,profiles:s}of t)for(let l of s)!l.processed&&l.profileUrl&&!o.has(l.profileUrl)&&(o.add(l.profileUrl),r.push({...l,_fromDate:n}));return r}var sn,ln,Q,cn,gt=pt(()=>{sn=rn(import.meta.url),ln=J.dirname(J.dirname(sn)),Q=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"collected-profiles"):J.join(ln,"collected-profiles");cn={loadProfiles:Je,saveProfile:$e,saveProfiles:Qt,getUnprocessedProfiles:Ge,getAllUnprocessedProfiles:He,markProfileProcessed:zt,getSummary:de,listFiles:Kt}});var _t={};mt(_t,{addEncounter:()=>be,canSendConnection:()=>ot,commitDataSnapshot:()=>co,default:()=>hn,getAllApplications:()=>lo,getPersonStatus:()=>Ke,getQuestionStats:()=>ao,getQuotaStatus:()=>qe,getRecentConnections:()=>tt,linkPersonToJob:()=>ze,loadApplicationQuestions:()=>$t,loadConversations:()=>to,loadJobs:()=>We,loadPeople:()=>K,loadQuota:()=>Ze,loadSyncState:()=>ro,logApplicationQuestions:()=>he,migrateFromDailyFiles:()=>no,recordConnectionSent:()=>et,resetCaches:()=>pn,saveConversations:()=>oo,saveJobs:()=>Ye,savePeople:()=>se,saveQuota:()=>Ct,saveSyncState:()=>so,updateConnectionStatus:()=>Xe,upsertJob:()=>Qe,upsertPerson:()=>Te});import"dotenv/config";import*as E from"fs";import*as q from"path";import{fileURLToPath as un}from"url";import{execSync as wt}from"child_process";function pn(){fe=null,pe=null,z=null,ne=null,me=null,oe=null}function M(){E.existsSync(F)||E.mkdirSync(F,{recursive:!0})}function re(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";E.writeFileSync(r,o);for(let n=0;n<3;n++)try{E.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Ae(e,t){if(!E.existsSync(e))return null;try{let o=JSON.parse(E.readFileSync(e,"utf-8"));try{E.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${q.resolve(e)}`);let r=e+".backup";if(E.existsSync(r))try{let n=JSON.parse(E.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{E.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{E.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}function K(){return fe||(M(),fe=Ae(St,"people.json")||{},fe)}function se(e){M(),fe=e;try{re(St,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${q.resolve(St)}`)}}function We(){return pe||(M(),pe=Ae(vt,"jobs.json")||{},pe)}function Ye(e){M(),pe=e;try{re(vt,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${q.resolve(vt)}`)}}function to(){return ne||(M(),ne=Ae(Ve,"conversations.json")||{},mn(ne),ne)}function mn(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{re(Ve,e)}catch{}}}function oo(e){M(),ne=e;try{re(Ve,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${q.resolve(Ve)}`)}}function Te(e,t={}){if(!e)return null;let o=K(),r=ye(),n=new Date().toISOString(),s=o[e];if(s){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 xt)t[l]!=null&&(s[l]=t[l])}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n};return se(o),o[e]}function Qe(e,t={}){if(!e)return null;let o=We(),r=ye(),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 l of s)t[l]!=null&&(n[l]=t[l])}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 Ye(o),o[e]}function ze(e,t){if(!e||!t)return;let o=K(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),se(o)))}function be(e,t){if(!e||!t)return;let o=K(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:ye(),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 Ke(e){return e&&K()[e]?.connectionStatus||null}function Xe(e,t,o={}){if(!e)return;let r=K(),n=r[e];if(n||(Te(e,o.profileInfo||{}),n=r[e]),!!n){if(n.connectionStatus=t,n.connectionDate=ye(),n.connectionMethod=o.method||n.connectionMethod,n.messageSent=o.messageSent||n.messageSent,n.lastUpdated=new Date().toISOString(),o.profileInfo)for(let s of xt)o.profileInfo[s]!=null&&(n[s]=o.profileInfo[s]);se(r)}}function Ze(){return z||(M(),z=Ae(Zt,"quota.json"),(!z||!z.connections)&&(z={connections:[]}),z)}function Ct(e){M(),z=e;try{re(Zt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function et(e,t="unknown"){let o=Ze(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Ct(o)}function tt(){let e=Ze(),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=tt(),t=ye(),o=e.filter(i=>i.date===t).length,r=e.length,n=o>=_e,s=r>=Ee,l=!n&&!s,a={allowed:l,daily:{sent:o,max:_e},weekly:{sent:r,max:Ee}};return l||(a.reason=n?`Daily limit reached (${o}/${_e})`:`Weekly limit reached (${r}/${Ee})`),a}function qe(){let e=tt(),t=ye(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:_e,remaining:_e-o},weekly:{sent:r,max:Ee,remaining:Ee-r}}}function yn(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function no(){M();let e=E.readdirSync(F).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(`
2
2
  Migrating from ${e.length} daily files...
3
- `);let t=K(),n=Ve(),r=0,o=0;e.sort();for(let i of e){let l=j.join(F,i),a;try{a=JSON.parse(E.readFileSync(l,"utf-8"))}catch(p){console.log(` Skipping ${i}: ${p.message}`);continue}let s=a.date||i.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,c=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 p of a.profiles){let f=p.profileUrl;if(!f)continue;let u=t[f];if(u){u.seenCount=(u.seenCount||1)+1,s&&(!u.lastSeen||s>u.lastSeen)&&(u.lastSeen=s),s&&(!u.firstSeen||s<u.firstSeen)&&(u.firstSeen=s),c&&!u.sources?.includes(c)&&(u.sources=u.sources||[],u.sources.push(c));for(let d of kt)p[d]!=null&&(u[d]=p[d]);p.status&&p.processed&&(u.connectionStatus=p.status,u.connectionDate=s,p.funnelResult&&(u.connectionMethod=p.funnelResult.method||u.connectionMethod,u.messageSent=p.funnelResult.message||u.messageSent)),u.lastUpdated=new Date().toISOString()}else t[f]={name:p.name||null,title:p.title||null,location:p.location||null,company:p.company||null,connectionDegree:p.connectionDegree||null,connectionsCount:p.connectionsCount||null,mutualConnections:p.mutualConnections||null,photoUrl:p.photoUrl||null,hasVerifiedBadge:p.hasVerifiedBadge||!1,firstSeen:s,lastSeen:s,seenCount:1,sources:c?[c]:[],connectionStatus:p.processed&&p.status||null,connectionDate:p.processed?s:null,connectionMethod:p.funnelResult?.method||null,messageSent:p.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(p.fromJob?.url){let d=yn(p.fromJob.url);d&&(t[f].jobIds||(t[f].jobIds=[]),t[f].jobIds.includes(d)||t[f].jobIds.push(d),n[d]?n[d].recruiterUrl||(n[d].recruiterUrl=f):(n[d]={title:p.fromJob.title||null,company:p.fromJob.company||null,location:null,salary:null,url:p.fromJob.url,applied:!0,appliedDate:s,recruiterUrl:f,firstSeen:s},o++))}}}return se(t),We(n),console.log(`
4
- Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(n).length} total (${o} new)`),{people:Object.keys(t).length,jobs:Object.keys(n).length}}function no(){return me||(M(),me=Ee(Zt,"sync-state.json")||{},me)}function ro(e){M(),me=e;try{re(Zt,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Ct(){if(oe)return oe;M();try{E.existsSync(vt)&&(oe=JSON.parse(E.readFileSync(vt,"utf-8")))}catch{}return oe||(oe={}),oe}function so(e){return Array.isArray(e.applications)}function io(){let e=Ct();if(so(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function be(e){if(!e||!e.questions||e.questions.length===0)return;let t=Ct(),n=e.jobId||"unknown",o={applicationId:`${n}_${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 l={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=hn?l.options=i.options:l.optionsOmitted=!0),i.page&&(l.page=i.page),i.wasPreFilled&&(l.wasPreFilled=!0),i.wasRetry&&(l.wasRetry=!0),l})};so(t)?(o.jobId=n,o.jobTitle=e.jobTitle||null,o.jobCompany=e.jobCompany||null,o.jobUrl=e.jobUrl||null,t.applications.push(o)):(t[n]||(t[n]={applications:[]}),t[n].applications.push(o));try{re(vt,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function lo(){let e=io(),t=new Map;for(let i of e)for(let l of i.questions||[]){let a=l.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:l.question,count:0,answers:new Map});let s=t.get(a);s.count++;let c=(l.answer||"").trim();s.answers.set(c,(s.answers.get(c)||0)+1)}let n=[...t.values()].sort((i,l)=>l.count-i.count),r=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),o=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:o}}function ao(e){if(E.existsSync(j.join(F,".git")))try{let t={cwd:F,stdio:"pipe",timeout:1e4};gt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{gt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');gt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var dn,pn,F,wt,St,Xt,He,Zt,vt,$e,_e,pe,fe,z,ne,me,oe,kt,hn,bn,je=pt(()=>{dn=un(import.meta.url),pn=j.dirname(j.dirname(dn)),F=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"collected-profiles"):j.join(pn,"collected-profiles"),wt=j.join(F,"people.json"),St=j.join(F,"jobs.json"),Xt=j.join(F,"quota.json"),He=j.join(F,"conversations.json"),Zt=j.join(F,"sync-state.json"),vt=j.join(F,"application-questions.json"),$e=20,_e=100,pe=null,fe=null,z=null,ne=null,me=null,oe=null;kt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];hn=50;bn={loadPeople:K,savePeople:se,loadJobs:Ve,saveJobs:We,loadConversations:eo,saveConversations:to,upsertPerson:Ae,upsertJob:Ye,linkPersonToJob:Qe,addEncounter:he,getPersonStatus:ze,updateConnectionStatus:Ke,migrateFromDailyFiles:oo,loadQuota:Xe,saveQuota:xt,recordConnectionSent:Ze,canSendConnection:tt,getRecentConnections:et,getQuotaStatus:Te,loadSyncState:no,saveSyncState:ro,commitDataSnapshot:ao,logApplicationQuestions:be,getQuestionStats:lo}});var xo={};ft(xo,{getJobDecision:()=>Dt,getLastVisit:()=>Tn,getScoutStats:()=>jn,loadCompanies:()=>ko,loadDiscoveredPeople:()=>qt,loadJobDecisions:()=>It,loadScoutedJobs:()=>Tt,loadVisitLog:()=>nt,recordVisit:()=>An,resetCaches:()=>_n,saveCompany:()=>ot,saveDiscoveredPerson:()=>En,saveScoutedJob:()=>jt,setJobDecision:()=>ae});import"dotenv/config";import*as G from"fs";import*as N from"path";import{fileURLToPath as xn}from"url";function Pe(){G.existsSync(le)||G.mkdirSync(le,{recursive:!0})}function Fe(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";G.writeFileSync(r,n);for(let o=0;o<3;o++)try{G.renameSync(r,e);return}catch(i){if(o<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Me(e){try{if(G.existsSync(e))return JSON.parse(G.readFileSync(e,"utf-8"))}catch{}return null}function _n(){De=null,qe=null,Le=null,Re=null,ie=null}function Tt(){return De||(De=Me(bo)||{},De)}function jt(e,t){if(!e)return;Pe();let n=Tt(),r=new Date().toISOString().slice(0,10);if(n[e]){for(let[o,i]of Object.entries(t))i!=null&&(n[e][o]=i);n[e].lastSeen=r}else n[e]={...t,scoutedAt:r,lastSeen:r};try{Fe(bo,n)}catch(o){console.error(`[!] Failed to save scouted-jobs.json: ${o.message}`)}}function It(){return qe||(qe=Me(vo)||{},qe)}function ae(e,t,n={}){if(!e||!t)return;Pe();let r=It(),o=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=o,n.reason&&(r[e].reason=n.reason),n.score!=null&&(r[e].score=n.score),n.source&&(r[e].source=n.source)):r[e]={status:t,decidedAt:o,updatedAt:o,reason:n.reason||null,score:n.score??null,source:n.source||null};try{Fe(vo,r)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Dt(e){return It()[e]||null}function qt(){return Le||(Le=Me(go)||{},Le)}function En(e,t){if(!e)return;Pe();let n=qt(),r=new Date().toISOString().slice(0,10);if(n[e]){let o=n[e];t.name&&(o.name=t.name),t.title&&(o.title=t.title),t.company&&(o.company=t.company),t.location&&(o.location=t.location),t.role&&(o.role=t.role),t.isConnected!=null&&(o.isConnected=t.isConnected),t.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(t.jobId)||o.jobIds.push(t.jobId)),o.lastSeen=r,o.seenCount=(o.seenCount||1)+1}else n[e]={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{Fe(go,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function ko(){return Re||(Re=Me(So)||{},Re)}function ot(e,t){if(!e)return;Pe();let n=ko(),r=new Date().toISOString().slice(0,10);if(n[e]){let o=n[e];t.name&&(o.name=t.name),t.about&&(o.about=t.about),t.size&&(o.size=t.size),t.industries&&(o.industries=t.industries),t.jobId&&(o.jobIds||(o.jobIds=[]),o.jobIds.includes(t.jobId)||o.jobIds.push(t.jobId)),t.recruiterUrl&&(o.recruiterUrls||(o.recruiterUrls=[]),o.recruiterUrls.includes(t.recruiterUrl)||o.recruiterUrls.push(t.recruiterUrl)),o.lastSeen=r,o.jobCount=o.jobIds?.length||0}else n[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{Fe(So,n)}catch(o){console.error(`[!] Failed to save companies.json: ${o.message}`)}}function nt(){return ie||(ie=Me(wo)||{visits:[]},Array.isArray(ie.visits)||(ie.visits=[]),ie)}function An(e,t={}){if(!e)return;Pe();let n=nt();n.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;n.visits=n.visits.filter(o=>new Date(o.date).getTime()>r);try{Fe(wo,n)}catch(o){console.error(`[!] Failed to save visit-log.json: ${o.message}`)}}function Tn(e){let t=nt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function jn(){let e=Tt(),t=qt(),n=Object.values(e),r=Object.values(t),o={};for(let u of n)u.company&&(o[u.company]=(o[u.company]||0)+1);let i=Object.entries(o).sort((u,d)=>d[1]-u[1]).slice(0,5).map(([u,d])=>`${u} (${d})`),l={};for(let u of n)for(let d of u.techStack||[])l[d]=(l[d]||0)+1;let a=Object.entries(l).sort((u,d)=>d[1]-u[1]).slice(0,8).map(([u,d])=>`${u} (${d})`),s=nt(),c=new Date().toISOString().slice(0,10),p=s.visits.filter(u=>u.date.startsWith(c)).length,f=new Set(s.visits.map(u=>u.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:r.length,topCompanies:i,topTech:a,totalVisited:f,todayVisited:p,lastScoutDate:n.length>0?n.sort((u,d)=>(d.scoutedAt||"").localeCompare(u.scoutedAt||""))[0]?.scoutedAt:null}}var Cn,$n,le,bo,go,wo,So,vo,De,qe,Le,Re,ie,Lt=pt(()=>{Cn=xn(import.meta.url),$n=N.dirname(N.dirname(Cn)),le=process.env.DATA_DIR?N.resolve(process.env.DATA_DIR,"market-research"):N.join($n,"market-research"),bo=N.join(le,"scouted-jobs.json"),go=N.join(le,"discovered-people.json"),wo=N.join(le,"visit-log.json"),So=N.join(le,"companies.json"),vo=N.join(le,"job-decisions.json");De=null;qe=null;Le=null;Re=null;ie=null});import Hn from"puppeteer";import*as Qo from"fs";async function b(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(r=>setTimeout(r,n))}function Ht(e){return parseInt(e,10)||0}async function B(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let o=r.innerText||"",i=o.includes("Premium")||o.includes("premium")||o.includes("Upgrade")||o.includes("upgrade"),l=o.includes("Try for")||o.includes("free trial")||o.includes("/month")||o.includes("per month")||o.includes("Start my")||o.includes("Subscribe"),a=o.includes("Get hired faster")||o.includes("Get hired 2x");if(i||l||a){let s=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:o.substring(0,80)};let c=r.querySelectorAll("button");for(let p of c){let f=p.innerText?.trim().toLowerCase()||"",u=p.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||u.includes("dismiss"))return p.click(),{dismissed:!0,matched:o.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let r=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import{createGraphClient as tn,resolveToken as on}from"@ilivemylife/graph-sdk";import{config as nn}from"dotenv";nn();var Vt=on()||process.env.TOKEN;Vt||(console.error(`
3
+ `);let t=K(),o=We(),r=0,n=0;e.sort();for(let s of e){let l=q.join(F,s),a;try{a=JSON.parse(E.readFileSync(l,"utf-8"))}catch(f){console.log(` Skipping ${s}: ${f.message}`);continue}let i=a.date||s.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,c=a.source||s.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!a.profiles||!Array.isArray(a.profiles)){console.log(` Skipping ${s}: no profiles array`);continue}console.log(` ${s}: ${a.profiles.length} profiles`);for(let f of a.profiles){let d=f.profileUrl;if(!d)continue;let u=t[d];if(u){u.seenCount=(u.seenCount||1)+1,i&&(!u.lastSeen||i>u.lastSeen)&&(u.lastSeen=i),i&&(!u.firstSeen||i<u.firstSeen)&&(u.firstSeen=i),c&&!u.sources?.includes(c)&&(u.sources=u.sources||[],u.sources.push(c));for(let p of xt)f[p]!=null&&(u[p]=f[p]);f.status&&f.processed&&(u.connectionStatus=f.status,u.connectionDate=i,f.funnelResult&&(u.connectionMethod=f.funnelResult.method||u.connectionMethod,u.messageSent=f.funnelResult.message||u.messageSent)),u.lastUpdated=new Date().toISOString()}else t[d]={name:f.name||null,title:f.title||null,location:f.location||null,company:f.company||null,connectionDegree:f.connectionDegree||null,connectionsCount:f.connectionsCount||null,mutualConnections:f.mutualConnections||null,photoUrl:f.photoUrl||null,hasVerifiedBadge:f.hasVerifiedBadge||!1,firstSeen:i,lastSeen:i,seenCount:1,sources:c?[c]:[],connectionStatus:f.processed&&f.status||null,connectionDate:f.processed?i:null,connectionMethod:f.funnelResult?.method||null,messageSent:f.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(f.fromJob?.url){let p=yn(f.fromJob.url);p&&(t[d].jobIds||(t[d].jobIds=[]),t[d].jobIds.includes(p)||t[d].jobIds.push(p),o[p]?o[p].recruiterUrl||(o[p].recruiterUrl=d):(o[p]={title:f.fromJob.title||null,company:f.fromJob.company||null,location:null,salary:null,url:f.fromJob.url,applied:!0,appliedDate:i,recruiterUrl:d,firstSeen:i},n++))}}}return se(t),Ye(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 ro(){return me||(M(),me=Ae(eo,"sync-state.json")||{},me)}function so(e){M(),me=e;try{re(eo,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function $t(){if(oe)return oe;M();try{E.existsSync(kt)&&(oe=JSON.parse(E.readFileSync(kt,"utf-8")))}catch{}return oe||(oe={}),oe}function io(e){return Array.isArray(e.applications)}function lo(){let e=$t();if(io(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function he(e){if(!e||!e.questions||e.questions.length===0)return;let t=$t(),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(s=>{let l={type:s.type||"input",question:s.labelText||s.question||"",answer:s.answer||""};return s.options&&(s.options.length<=bn?l.options=s.options:l.optionsOmitted=!0),s.page&&(l.page=s.page),s.wasPreFilled&&(l.wasPreFilled=!0),s.wasRetry&&(l.wasRetry=!0),typeof s.isRequired=="boolean"&&(l.isRequired=s.isRequired),s.wasOptional&&(l.wasOptional=!0),l})};io(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{re(kt,t)}catch(s){console.error(`[!] Failed to save application-questions.json: ${s.message}`)}}function ao(){let e=lo(),t=new Map;for(let s of e)for(let l of s.questions||[]){let a=l.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:l.question,count:0,answers:new Map});let i=t.get(a);i.count++;let c=(l.answer||"").trim();i.answers.set(c,(i.answers.get(c)||0)+1)}let o=[...t.values()].sort((s,l)=>l.count-s.count),r=o.slice(0,15).map(s=>({question:s.question,count:s.count,topAnswer:[...s.answers.entries()].sort((l,a)=>a[1]-l[1])[0]?.[0]||""})),n=o.filter(s=>s.answers.size>1&&s.count>=3).map(s=>({question:s.question,count:s.count,answers:[...s.answers.entries()].sort((l,a)=>a[1]-l[1]).map(([l,a])=>`${l} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:n}}function co(e){if(E.existsSync(q.join(F,".git")))try{let t={cwd:F,stdio:"pipe",timeout:1e4};wt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{wt("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');wt(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var dn,fn,F,St,vt,Zt,Ve,eo,kt,_e,Ee,fe,pe,z,ne,me,oe,xt,bn,hn,je=pt(()=>{dn=un(import.meta.url),fn=q.dirname(q.dirname(dn)),F=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"collected-profiles"):q.join(fn,"collected-profiles"),St=q.join(F,"people.json"),vt=q.join(F,"jobs.json"),Zt=q.join(F,"quota.json"),Ve=q.join(F,"conversations.json"),eo=q.join(F,"sync-state.json"),kt=q.join(F,"application-questions.json"),_e=20,Ee=100,fe=null,pe=null,z=null,ne=null,me=null,oe=null;xt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];bn=50;hn={loadPeople:K,savePeople:se,loadJobs:We,saveJobs:Ye,loadConversations:to,saveConversations:oo,upsertPerson:Te,upsertJob:Qe,linkPersonToJob:ze,addEncounter:be,getPersonStatus:Ke,updateConnectionStatus:Xe,migrateFromDailyFiles:no,loadQuota:Ze,saveQuota:Ct,recordConnectionSent:et,canSendConnection:ot,getRecentConnections:tt,getQuotaStatus:qe,loadSyncState:ro,saveSyncState:so,commitDataSnapshot:co,logApplicationQuestions:he,getQuestionStats:ao}});var Co={};mt(Co,{getJobDecision:()=>Lt,getLastVisit:()=>Tn,getScoutStats:()=>qn,loadCompanies:()=>xo,loadDiscoveredPeople:()=>Dt,loadJobDecisions:()=>It,loadScoutedJobs:()=>qt,loadVisitLog:()=>rt,recordVisit:()=>An,resetCaches:()=>_n,saveCompany:()=>nt,saveDiscoveredPerson:()=>En,saveScoutedJob:()=>jt,setJobDecision:()=>ae});import"dotenv/config";import*as G from"fs";import*as N from"path";import{fileURLToPath as xn}from"url";function Fe(){G.existsSync(le)||G.mkdirSync(le,{recursive:!0})}function Me(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";G.writeFileSync(r,o);for(let n=0;n<3;n++)try{G.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Ne(e){try{if(G.existsSync(e))return JSON.parse(G.readFileSync(e,"utf-8"))}catch{}return null}function _n(){Le=null,De=null,Re=null,Pe=null,ie=null}function qt(){return Le||(Le=Ne(go)||{},Le)}function jt(e,t){if(!e)return;Fe();let o=qt(),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{Me(go,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}function It(){return De||(De=Ne(ko)||{},De)}function ae(e,t,o={}){if(!e||!t)return;Fe();let r=It(),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{Me(ko,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function Lt(e){return It()[e]||null}function Dt(){return Re||(Re=Ne(wo)||{},Re)}function En(e,t){if(!e)return;Fe();let o=Dt(),r=new Date().toISOString().slice(0,10);if(o[e]){let n=o[e];t.name&&(n.name=t.name),t.title&&(n.title=t.title),t.company&&(n.company=t.company),t.location&&(n.location=t.location),t.role&&(n.role=t.role),t.isConnected!=null&&(n.isConnected=t.isConnected),t.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(t.jobId)||n.jobIds.push(t.jobId)),n.lastSeen=r,n.seenCount=(n.seenCount||1)+1}else o[e]={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{Me(wo,o)}catch(n){console.error(`[!] Failed to save discovered-people.json: ${n.message}`)}}function xo(){return Pe||(Pe=Ne(vo)||{},Pe)}function nt(e,t){if(!e)return;Fe();let o=xo(),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{Me(vo,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}function rt(){return ie||(ie=Ne(So)||{visits:[]},Array.isArray(ie.visits)||(ie.visits=[]),ie)}function An(e,t={}){if(!e)return;Fe();let o=rt();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{Me(So,o)}catch(n){console.error(`[!] Failed to save visit-log.json: ${n.message}`)}}function Tn(e){let t=rt();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function qn(){let e=qt(),t=Dt(),o=Object.values(e),r=Object.values(t),n={};for(let u of o)u.company&&(n[u.company]=(n[u.company]||0)+1);let s=Object.entries(n).sort((u,p)=>p[1]-u[1]).slice(0,5).map(([u,p])=>`${u} (${p})`),l={};for(let u of o)for(let p of u.techStack||[])l[p]=(l[p]||0)+1;let a=Object.entries(l).sort((u,p)=>p[1]-u[1]).slice(0,8).map(([u,p])=>`${u} (${p})`),i=rt(),c=new Date().toISOString().slice(0,10),f=i.visits.filter(u=>u.date.startsWith(c)).length,d=new Set(i.visits.map(u=>u.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:s,topTech:a,totalVisited:d,todayVisited:f,lastScoutDate:o.length>0?o.sort((u,p)=>(p.scoutedAt||"").localeCompare(u.scoutedAt||""))[0]?.scoutedAt:null}}var Cn,$n,le,go,wo,So,vo,ko,Le,De,Re,Pe,ie,Rt=pt(()=>{Cn=xn(import.meta.url),$n=N.dirname(N.dirname(Cn)),le=process.env.DATA_DIR?N.resolve(process.env.DATA_DIR,"market-research"):N.join($n,"market-research"),go=N.join(le,"scouted-jobs.json"),wo=N.join(le,"discovered-people.json"),So=N.join(le,"visit-log.json"),vo=N.join(le,"companies.json"),ko=N.join(le,"job-decisions.json");Le=null;De=null;Re=null;Pe=null;ie=null});import Hn from"puppeteer";import*as Qo from"fs";async function h(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function Wt(e){return parseInt(e,10)||0}async function B(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"),l=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||l||a){let i=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:n.substring(0,80)};let c=r.querySelectorAll("button");for(let f of c){let d=f.innerText?.trim().toLowerCase()||"",u=f.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||u.includes("dismiss"))return f.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})}import{createGraphClient as tn,resolveToken as on}from"@ilivemylife/graph-sdk";import{config as nn}from"dotenv";nn();var Yt=on()||process.env.TOKEN;Yt||(console.error(`
5
5
  [FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
6
6
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
7
7
  `),console.error(` Or add ILML_TOKEN=... to .env
8
- `),process.exit(1));var te=tn({token:Vt});var ce=12e4;async function ue(e,{retries:t=2}={}){let n=process.env.NODE_EASY_APPLY_MAIN;if(!n||n.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 o=await te.askLifebot(n,e,{timeout:ce});return ce=Math.max(12e4,ce*.9),o.content}catch(o){if(o.constructor.name==="LifebotTimeoutError"&&r<t){ce=Math.min(ce*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(ce/1e3)}s...`);continue}throw o}}async function Wt(e,t){(e=="City"||e=="Location (city)")&&(e="Tell my home city (not the city where position is).");let n=`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"),n+=`Additional info: ${t}`),await ue(n)}async function mt(e,t){let n=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ue(n)}async function Ue(e,t){let n=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ue(n)}bt();import{LIFEBOT_MESSAGE_TYPES as Oo}from"@ilivemylife/graph-sdk";je();async function co(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function gn(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(r=>n.includes(r.toLowerCase()))}async function wn(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(2e3+Math.random()*2e3),await B(e)&&(console.log(" Dismissed Premium overlay"),await b(1500),await co(e,t));let r=await e.evaluate(()=>{let o=document.querySelector("h1")?.textContent?.trim()||null,i=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,a=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,c=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,f=document.querySelector(".dist-value")?.textContent?.trim()||null,d=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,g=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),h=g?parseInt(g[1],10):null,k=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,w=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:o,title:i,location:l,about:a,company:c,connectionDegree:f,connectionsCount:d,mutualConnections:h,photoUrl:k,hasVerifiedBadge:w}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(n){console.error(`Error viewing profile ${t}:`,n.message);try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{}return null}}async function Ie(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(n).map(s=>s.getAttribute("aria-label")),o=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:n.length,pendingLabels:r,hasMessageBtn:!!o,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:l}:o&&!i?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function _t(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(s=c.textContent?.trim(),s&&!s.includes("notification")))return s;let p=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(p)return p.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let p=document.querySelectorAll('a[href*="custom-invite"]');return{count:p.length,labels:Array.from(p).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(p=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),u=p.toLowerCase().split(" ")[0],d=null,m=null;for(let y of f){let g=y.getBoundingClientRect();if(g.width===0||g.height===0)continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(u)){d=y;break}m||(m=y)}return d||m||null},n);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(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let c=await e.evaluate(f=>{let u=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),d=document.querySelectorAll("button[aria-label]");return Array.from(d).filter(y=>{let g=y.getAttribute("aria-label")||"";return(g.toLowerCase().includes("invite")||g.toLowerCase().includes("connect"))&&u.test(g)}).map(y=>y.getAttribute("aria-label")?.slice(0,50))},s);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(f=>{let u=document.querySelectorAll("button[aria-label]"),d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let m of u){let y=m.getAttribute("aria-label")||"";if((y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&d.test(y))return m}return null},s);let p=t?.asElement?.()||null;if(p||await t?.dispose?.().catch(()=>{}),p)return console.log(" Found: button matching profile name"),{button:p,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let s=await e.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),t),c=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(c)&&(console.log(` Skipping primary button: wrong person (${s})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let o=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of r){let c=await e.evaluate((p,f)=>{let u=p.className.includes("muted"),d=p.className.includes("sticky-header")||p.className.includes("sticky"),m=p.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,y=(p.getAttribute("aria-label")||"").toLowerCase(),g=y.includes("invite"),h=f?y.includes(f):!0;return{isMuted:u,isStickyHeader:d,inRecommendations:m,hasInvite:g,matchesName:h,ariaLabel:y}},s,o);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}i=s;break}}for(let s of r)s!==i&&await s.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let s of a){let c=await e.evaluate(p=>{let f=p.getBoundingClientRect(),u=f.width>0&&f.height>0,d=p.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:u,isInStickyHeader:d,top:f.top}},s);if(c.isVisible&&!c.isInStickyHeader){l=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of a)s!==l&&await s.dispose().catch(()=>{});if(!l&&a.length>0&&(l=a[a.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let s=await e.evaluateHandle(()=>{let p=Array.from(document.querySelectorAll("button, a")).find(u=>{let d=u.innerText?.trim(),m=u.getAttribute("aria-label")||"",y=u.getBoundingClientRect();return y.top<100||y.top>600||y.width===0?!1:d==="Follow"||d==="Message"||d==="Connect"||m.includes("Follow")||m.includes("Message")||m.includes("Invite")});if(!p)return null;let f=p.parentElement;for(let u=0;u<8&&f;u++){for(let d of f.querySelectorAll("button"))if(d.innerText?.trim()==="More"&&d!==p)return d;f=f.parentElement}return null});l=s?.asElement?.()||null,l||await s?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),l),await b(500),await e.evaluate(p=>p.click(),l),await b(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"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let p=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let u of f){let d=u.querySelector('a[href*="custom-invite"]');if(d)return d;for(let m of u.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(m.innerText?.trim()==="Connect")return m}return null});c=p?.asElement?.()||null,c||await p?.dispose?.().catch(()=>{})}if(!c){let p=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),u=[];for(let d of f)for(let m of d.querySelectorAll('[role="menuitem"], a, div')){let y=m.innerText?.trim();y&&y.length<40&&u.push(y)}return[...new Set(u)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(p)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(p=>(p.getAttribute("aria-label")||"").toLowerCase(),t),c=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(c)&&(console.log(` Skipping generic button: wrong person (${s})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Sn(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await b(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),o=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV";if(o){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(p=>p.click(),t)]),await b(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 b(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await b(3e3)):(await e.evaluate(c=>c.click(),t),await b(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),s=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${s}`:` \u26A0 No modal after connect click \u2014 ${s}`),"success"}async function vn(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 b(1500);let n=await _t(e);if(n){await e.evaluate(o=>o.click(),n),await b(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(o=>o.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function kn(e,t,n={}){let{message:r=null,useCustomMessage:o=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
9
- --- Connecting: ${c} ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(5e3),await B(e)&&(console.log(" Dismissed Premium overlay"),await b(2e3),await co(e,t),await b(2e3)),s.profileInfo=await e.evaluate(()=>{let h=document.querySelector("h1")?.textContent?.trim()||null,v=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,k=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,x=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,L=document.querySelector(".dist-value")?.textContent?.trim()||null,we=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,Z=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),Oe=Z?parseInt(Z[1],10):null,C=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,D=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:h,title:v,location:k,company:x,connectionDegree:L,connectionsCount:we,mutualConnections:Oe,photoUrl:C,hasVerifiedBadge:D}}),a.length>0&&gn(s.profileInfo?.location,a))return console.log(` \u26A0 Excluded location: ${s.profileInfo.location}`),s.reason="excluded_location",s;let f=await Ie(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await B(e);let u=await _t(e);if(!u&&(await B(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await b(2e3),u=await _t(e)),!u))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;if(s.method=u.method,await Sn(e,u.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(4e3);let h=await Ie(e);if(h==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${h} \u2014 trying More dropdown...`),await B(e),await b(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),v),await b(500),await v.click().catch(()=>e.evaluate(w=>w.click(),v)),await b(2e3);let k=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(k){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(I=>I.click(),k),await b(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),s.reason="premium_required",s;if(await Ie(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await b(500),s.reason="premium_required",s}catch(k){return console.log(" More dropdown failed:",k.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let h=await e.$('button[aria-label="Dismiss"]');return h&&await h.click(),await b(500),s.reason="email_required",s}let y=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!y&&!g){let h=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let k=v.querySelector('button[aria-label="Add a note"]'),w=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!w}});if(h.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=v?.asElement?.()||null,y||await v.dispose().catch(()=>{})}if(h.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=v?.asElement?.()||null,g||await v.dispose().catch(()=>{})}}if(o){if(y&&r){if(console.log(" Adding personalized note..."),await y.click(),await b(1500),await e.$("div.modal-upsell")){let k=await vn(e);return s.success=k,s.connectionSent=k,s.reason=k?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",k);await v.type(w,{delay:20}),await b(500);let x=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(x){try{await x.evaluate(I=>I.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=w,s}}}else if(g){console.log(" Sending without note...");try{await g.evaluate(h=>h.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(y&&!r){console.log(" No message provided, sending without note...");let h=await e.$('button[aria-label="Send without a note"]');if(h){try{await h.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let h=g;if(h){try{await h.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}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 b(4e3)),await B(e),await b(500);let v=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let w of v){let x=await e.evaluate(I=>{let L=I.getBoundingClientRect();return{visible:L.width>0&&L.height>0,inSticky:!!I.closest('.sticky-header, [class*="sticky"]')}},w);if(x.visible&&!x.inSticky){k=w;break}}!k&&v.length>0&&(k=v[v.length-1]);for(let w of v)w!==k&&await w.dispose().catch(()=>{});if(k)try{await e.evaluate(x=>x.scrollIntoView({behavior:"smooth",block:"center"}),k),await b(500),await k.click().catch(()=>e.evaluate(x=>x.click(),k)),await b(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(w){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(V=>V.click(),w),await b(3e3);let x=e.url();if(x.includes("/premium/")||x.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await Ie(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await Ie(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let L=await e.$('button[aria-label="Send without a note"]');if(L){console.log(" Modal appeared via More dropdown, sending without note...");try{await L.evaluate(V=>V.click())}catch{}return await b(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(c){console.error(` \u2717 Error: ${c.message}`),s.reason="error",s.error=c.message;let p=c.message.toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("browser has disconnected")||p.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{s.fatal=!0}return s}}async function Et(e,t,n={}){let{message:r=null,useCustomMessage:o=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:s=null,excludeLocations:c=[],source:p="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
10
- === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${o?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!l){let d=Te();console.log(`Quota: today ${d.daily.sent}/${d.daily.max} | week ${d.weekly.sent}/${d.weekly.max}`)}console.log("");let u=0;for(let d=0;d<t.length;d++){let m=t[d];try{if(e.isClosed()){console.log(`
8
+ `),process.exit(1));var te=tn({token:Yt});var ce=12e4;async function ue(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 te.askLifebot(o,e,{timeout:ce});return ce=Math.max(12e4,ce*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){ce=Math.min(ce*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(ce/1e3)}s...`);continue}throw n}}async function yt(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 ue(o)}async function Be(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ue(o)}async function xe(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await ue(o)}gt();import{LIFEBOT_MESSAGE_TYPES as Uo}from"@ilivemylife/graph-sdk";je();async function uo(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function gn(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function wn(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await h(2e3+Math.random()*2e3),await B(e)&&(console.log(" Dismissed Premium overlay"),await h(1500),await uo(e,t));let r=await e.evaluate(()=>{let n=document.querySelector("h1")?.textContent?.trim()||null,s=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,a=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,c=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,d=document.querySelector(".dist-value")?.textContent?.trim()||null,p=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,g=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),b=g?parseInt(g[1],10):null,k=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,w=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:n,title:s,location:l,about:a,company:c,connectionDegree:d,connectionsCount:p,mutualConnections:b,photoUrl:k,hasVerifiedBadge:w}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await h(1e3)}catch{}return null}}async function Ie(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(o).map(i=>i.getAttribute("aria-label")),n=document.querySelector('button[aria-label*="Message"]'),s=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:r,hasMessageBtn:!!n,hasConnectBtn:!!s};return o.length>0?{status:"pending",debug:l}:n&&!s?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Et(e){let t=null,o=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(i=c.textContent?.trim(),i&&!i.includes("notification")))return i;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 i=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))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),u=f.toLowerCase().split(" ")[0],p=null,y=null;for(let m of d){let g=m.getBoundingClientRect();if(g.width===0||g.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(u)){p=m;break}y||(y=m)}return p||y||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 i=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let c=await e.evaluate(d=>{let u=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let g=m.getAttribute("aria-label")||"";return(g.toLowerCase().includes("invite")||g.toLowerCase().includes("connect"))&&u.test(g)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},i);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(d=>{let u=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let y of u){let m=y.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return y}return null},i);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 i=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(c)&&(console.log(` Skipping primary button: wrong person (${i})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let 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 i of r){let c=await e.evaluate((f,d)=>{let u=f.className.includes("muted"),p=f.className.includes("sticky-header")||f.className.includes("sticky"),y=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(f.getAttribute("aria-label")||"").toLowerCase(),g=m.includes("invite"),b=d?m.includes(d):!0;return{isMuted:u,isStickyHeader:p,inRecommendations:y,hasInvite:g,matchesName:b,ariaLabel:m}},i,n);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}s=i;break}}for(let i of r)i!==s&&await i.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let i of a){let c=await e.evaluate(f=>{let d=f.getBoundingClientRect(),u=d.width>0&&d.height>0,p=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:u,isInStickyHeader:p,top:d.top}},i);if(c.isVisible&&!c.isInStickyHeader){l=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of a)i!==l&&await i.dispose().catch(()=>{});if(!l&&a.length>0&&(l=a[a.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let i=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(u=>{let p=u.innerText?.trim(),y=u.getAttribute("aria-label")||"",m=u.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let u=0;u<8&&d;u++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==f)return p;d=d.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(f=>f.scrollIntoView({behavior:"smooth",block:"center"}),l),await h(500),await e.evaluate(f=>f.click(),l),await h(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"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let f=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let u of d){let p=u.querySelector('a[href*="custom-invite"]');if(p)return p;for(let y of u.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(y.innerText?.trim()==="Connect")return y}return null});c=f?.asElement?.()||null,c||await f?.dispose?.().catch(()=>{})}if(!c){let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),u=[];for(let p of d)for(let y of p.querySelectorAll('[role="menuitem"], a, div')){let m=y.innerText?.trim();m&&m.length<40&&u.push(m)}return[...new Set(u)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(f)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let i=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(c)&&(console.log(` Skipping generic button: wrong person (${i})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Sn(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await h(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";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 h(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 h(2e3),"premium_redirect"}else s?(await e.evaluate(c=>c.click(),t),await h(3e3)):(await e.evaluate(c=>c.click(),t),await h(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),i=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${i}`:` \u26A0 No modal after connect click \u2014 ${i}`),"success"}async function vn(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 h(1500);let o=await Et(e);if(o){await e.evaluate(n=>n.click(),o),await h(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(n=>n.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function kn(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,skipIfPending:s=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=o,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
9
+ --- Connecting: ${c} ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await h(5e3),await B(e)&&(console.log(" Dismissed Premium overlay"),await h(2e3),await uo(e,t),await h(2e3)),i.profileInfo=await e.evaluate(()=>{let b=document.querySelector("h1")?.textContent?.trim()||null,v=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,k=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,x=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,D=document.querySelector(".dist-value")?.textContent?.trim()||null,we=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,Z=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),Ue=Z?parseInt(Z[1],10):null,C=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,I=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:b,title:v,location:k,company:x,connectionDegree:D,connectionsCount:we,mutualConnections:Ue,photoUrl:C,hasVerifiedBadge:I}}),a.length>0&&gn(i.profileInfo?.location,a))return console.log(` \u26A0 Excluded location: ${i.profileInfo.location}`),i.reason="excluded_location",i;let d=await Ie(e);if(d==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await B(e);let u=await Et(e);if(!u&&(await B(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await h(2e3),u=await Et(e)),!u))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=u.method,await Sn(e,u.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await h(4e3);let b=await Ie(e);if(b==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${b} \u2014 trying More dropdown...`),await B(e),await h(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),v),await h(500),await v.click().catch(()=>e.evaluate(w=>w.click(),v)),await h(2e3);let k=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(k){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(j=>j.click(),k),await h(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3),i.reason="premium_required",i;if(await Ie(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await h(500),i.reason="premium_required",i}catch(k){return console.log(" More dropdown failed:",k.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let b=await e.$('button[aria-label="Dismiss"]');return b&&await b.click(),await h(500),i.reason="email_required",i}let m=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!m&&!g){let b=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let k=v.querySelector('button[aria-label="Add a note"]'),w=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!w}});if(b.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=v?.asElement?.()||null,m||await v.dispose().catch(()=>{})}if(b.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=v?.asElement?.()||null,g||await v.dispose().catch(()=>{})}}if(n){if(m&&r){if(console.log(" Adding personalized note..."),await m.click(),await h(1500),await e.$("div.modal-upsell")){let k=await vn(e);return i.success=k,i.connectionSent=k,i.reason=k?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",k);await v.type(w,{delay:20}),await h(500);let x=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(x){try{await x.evaluate(j=>j.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=w,i}}}else if(g){console.log(" Sending without note...");try{await g.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(m&&!r){console.log(" No message provided, sending without note...");let b=await e.$('button[aria-label="Send without a note"]');if(b){try{await b.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let b=g;if(b){try{await b.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await h(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}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 h(4e3)),await B(e),await h(500);let v=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let w of v){let x=await e.evaluate(j=>{let D=j.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!j.closest('.sticky-header, [class*="sticky"]')}},w);if(x.visible&&!x.inSticky){k=w;break}}!k&&v.length>0&&(k=v[v.length-1]);for(let w of v)w!==k&&await w.dispose().catch(()=>{});if(k)try{await e.evaluate(x=>x.scrollIntoView({behavior:"smooth",block:"center"}),k),await h(500),await k.click().catch(()=>e.evaluate(x=>x.click(),k)),await h(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(w){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(V=>V.click(),w),await h(3e3);let x=e.url();if(x.includes("/premium/")||x.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3),await Ie(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await Ie(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let D=await e.$('button[aria-label="Send without a note"]');if(D){console.log(" Modal appeared via More dropdown, sending without note...");try{await D.evaluate(V=>V.click())}catch{}return await h(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(c){console.error(` \u2717 Error: ${c.message}`),i.reason="error",i.error=c.message;let f=c.message.toLowerCase();if(f.includes("detached")||f.includes("session closed")||f.includes("target closed")||f.includes("browser has disconnected")||f.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await h(1e3)}catch{i.fatal=!0}return i}}async function At(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:c=[],source:f="unknown"}=o,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
10
+ === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${s})`}`),l||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!l){let p=qe();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let u=0;for(let p=0;p<t.length;p++){let y=t[p];try{if(e.isClosed()){console.log(`
11
11
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
12
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!m.profileUrl){console.log(`[${d+1}/${t.length}] Skipping - no URL`);continue}let y=ze(m.profileUrl);if(y==="pending"||y==="connected"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"){console.log(`[${d+1}/${t.length}] ${m.name||m.profileUrl} \u2014 skipped (db: ${y})`),y==="pending"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,s&&await s(m,f,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${d+1}/${t.length}] ${m.name||m.profileUrl}`);let g=null;if(l){let h=await wn(e,m.profileUrl);h?(f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:h}):(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 h=tt();if(!h.allowed){console.log(` \u26A0 Global quota exhausted: ${h.reason}`);break}if(g=await kn(e,m.profileUrl,{message:r,useCustomMessage:o,excludeLocations:c}),g.success)f.connectionsSent++,g.connectionSent&&Ze(m.profileUrl,p);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(`
13
- \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(u++,u>=3){console.log(`
14
- \u26A0 ${u} consecutive errors \u2014 aborting funnel`);break}}else u=0;if(g&&g.reason&&(Ke(m.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),he(m.profileUrl,{source:p||"funnel",jobId:m.jobId||m.fromJob?.jobId||null,jobTitle:m.fromJob?.title||null,jobCompany:m.fromJob?.company||null,action:g.reason})),s&&await s(m,f,g),d<t.length-1){let h=a+Math.random()*2e3;await b(h)}}if(console.log(`
15
- === Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!l){let d=Te();console.log(` Quota remaining: today ${d.daily.remaining}/${d.daily.max} | week ${d.weekly.remaining}/${d.weekly.max}`)}return f}je();async function uo(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 o=null,i=null;for(let f of r)if(o=document.querySelector(f),o){i=f;break}if(!o){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let u=f.parentElement;for(;u&&u!==document.body;){if(u.scrollHeight>u.clientHeight){o=u,i="parent of li.scaffold-layout__list-item";break}u=u.parentElement}}}if(!o)return{found:!1,triedSelectors:r};let l=o.scrollTop,a=300,s=300,c=50,p=0;for(;p<c&&(o.scrollBy(0,a),await new Promise(f=>setTimeout(f,s)),!(o.scrollTop+o.clientHeight>=o.scrollHeight));)p++;return{found:!0,usedSelector:i,initialScroll:l,finalScroll:o.scrollTop,scrollHeight:o.scrollHeight,attempts:p}},t)}async function po(e,{easyApplyOnly:t=!0}={}){let n=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(o=>{let l=(o.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=o.querySelector("a.job-card-container__link");if(a){let s=a.getAttribute("href").split("?")[0],c=o.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),p=o.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=o.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),u=o.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:s,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${s}`,jobTitle:c,companyName:p,location:f,salary:u||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return t?n.filter(r=>r.isEasyApply&&r.href):n.filter(r=>r.href)}async function fo(e){let t=await e.evaluate(()=>{let n=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(n&&!n.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return n.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 b(2e3),t.success}async function At(e,t){let n=e.url();if(n.includes("/jobs/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let o=e.url();if(!o.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${o.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function mo(e,t,n,r){for(let o of t){await At(e,r)&&(await B(e),await b(2e3));let l=await e.$(`a[data-control-id="${o.dataId}"]`),a="dataId";if(!l){let s=o.id?.match(/\d+/)?.[0];s&&(l=await e.$(`a[href*="/jobs/view/${s}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${o.jobTitle}`);let s=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"}),l),await b(300),await l.click(),await b(1500);let c=!1;for(let u=0;u<8;u++){let d=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(d&&d!==s){c=!0;break}await b(500)}if(!c){await e.evaluate(u=>u.click(),l),await b(1500);for(let u=0;u<6;u++){let d=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(d&&d!==s){c=!0;break}await b(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${o.jobTitle}`)}let p=await e.evaluate(()=>{let u=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let d of u)for(let m of d.querySelectorAll("button")){let y=m.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return m.click(),y}return null});p&&console.log(` Dismissed popup before processing (${p})`);let{keepGoing:f}=await n(e,o);if(!f)return{keepGoing:!1}}else{let s=o.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${o.jobTitle||o.id} (dataId=${o.dataId}, jobId=${s})`)}}return{keepGoing:!0}}async function yo(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,n=t.querySelector(".hirer-card__hirer-information");if(n){let l=n.querySelector('a[href*="/in/"]'),a=n.querySelector(".jobs-poster__name")||n.querySelector("strong")||n.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"poster_name"}}let o=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(o){let l=o.querySelector('a[href*="/in/"]');if(l)return{name:(o.querySelector(".jobs-poster__name")||o.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let l of i){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function ho(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()||"",o={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let Y of i){let ee=Y.querySelector(".job-criteria__subheader")?.textContent?.trim(),ke=Y.querySelector(".job-criteria__text")?.textContent?.trim();ee&&ke&&(o[ee.toLowerCase()]=ke)}let l=["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 Y of l)new RegExp("\\b"+Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(Y.replace(/\\\+/g,"+"));let c=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,u=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),d=u?.innerText?.trim()||null,y=(u?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,h=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",k=h.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=h.match(/(\d[\d,]*)\s+applicant/i),x=w?parseInt(w[1].replace(/,/g,"")):null,I=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),L=Array.from(I).map(Y=>Y.innerText?.trim()?.replace(/\s+/g," ")),we=L.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,U=L.join(" ")+" "+h,Se=/\bremote\b/i.test(U)?"remote":/\bhybrid\b/i.test(U)?"hybrid":/\bon-?site\b/i.test(U)?"onsite":null,Z=/\bcontract\b/i.test(U)?"contract":/\bfull-?time\b/i.test(U)?"full-time":/\bpart-?time\b/i.test(U)?"part-time":/\bfreelance\b/i.test(U)?"freelance":/\btemporary\b/i.test(U)?"temporary":null,P=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",D=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",_=(P+" "+r+" "+D).toLowerCase(),A=P.toLowerCase(),$=[];/\bremote\b/.test(_)&&$.push("remote"),/\bhybrid\b/.test(_)&&$.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(_)&&$.push("onsite"),($.length===0||!$.includes("remote")&&!$.includes("hybrid")&&!$.includes("onsite"))&&/remote/i.test(D)&&$.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(A)&&$.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(A)&&$.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(A)&&!$.includes("managerial")&&$.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(A)?$.push("junior"):/\b(senior|sr\.?)\b/i.test(A)?$.push("senior"):/\b(staff|principal|distinguished)\b/i.test(A)?$.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(A)?$.push("executive"):/\b(lead|team lead)\b/i.test(A)&&$.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(_)&&$.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(_)&&$.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(_)&&$.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(_)&&$.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(_)&&$.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(_)&&$.push("mobile"),/\b(architect)\b/i.test(A)&&$.push("architect"),/\b(consultant|consulting)\b/i.test(A)&&$.push("consultant");let ve=(o["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(ve)||/\bcontract\b/i.test(_))&&$.push("contract"),/full.?time|permanent/i.test(ve)&&$.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(D)&&$.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(D)&&$.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&$.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:d,companyUrl:y?y.startsWith("/")?"https://www.linkedin.com"+y:y:null,aboutCompany:c,seniority:o["seniority level"]||null,employmentType:o["employment type"]||null,industries:o.industries||null,jobFunction:o["job function"]||null,postedTime:k,applicantCount:x,companySize:we,workplaceType:Se,contractType:Z,techStack:[...new Set(a)],jobTags:[...new Set($)]}})}Lt();import"dotenv/config";import*as O from"fs";import*as q from"path";import{fileURLToPath as In}from"url";var Dn=In(import.meta.url),qn=q.dirname(Dn),_o=q.dirname(q.dirname(qn)),rt=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"collected-profiles"):q.join(_o,"collected-profiles"),st=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"market-research"):q.join(_o,"market-research"),Rt=1,Ln=[{version:1,file:"./v001-normalize-jobs-and-questions.mjs"}];function Eo(e){return q.join(e,".schema-version")}function Pt(e){let t=Eo(e);if(!O.existsSync(t))return{version:0,migrations:[]};try{return JSON.parse(O.readFileSync(t,"utf-8"))}catch{return{version:0,migrations:[]}}}function Rn(e,t){O.writeFileSync(Eo(e),JSON.stringify(t,null,2))}function Co(e,t){if(!O.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,r=O.readdirSync(e).filter(o=>o.endsWith(".json")&&!o.includes(".backup"));for(let o of r){let i=q.join(e,o),l=q.join(e,o+n);try{O.copyFileSync(i,l)}catch(a){console.error(` [!] Failed to backup ${o}: ${a.message}`)}}r.length>0&&console.log(` Backed up ${r.length} files in ${q.basename(e)}/ (${n})`)}var $o=!1;async function Ao(){if($o)return;$o=!0;let e=Pt(rt),t=Pt(st),n=Math.min(e.version,t.version);if(n>=Rt)return;console.log(`
16
- \u{1F4E6} Schema migration: v${n} \u2192 v${Rt}`);let r=Ln.filter(o=>o.version>n);for(let o of r){console.log(`
17
- Running migration v${String(o.version).padStart(3,"0")}...`),Co(rt,o.version),Co(st,o.version);let i=await import(o.file);try{await i.up(rt,st)}catch(s){console.error(`
18
- [FATAL] Migration v${o.version} failed: ${s.message}`),console.error(` Backups are in collected-profiles/ and market-research/ (.pre-v${String(o.version).padStart(3,"0")}.backup)`),console.error(` Fix the issue and restart.
19
- `),process.exit(1)}let l=new Date().toISOString(),a={version:o.version,name:i.NAME||`v${String(o.version).padStart(3,"0")}`,appliedAt:l};for(let s of[rt,st]){if(!O.existsSync(s))continue;let c=Pt(s);c.version=o.version,c.migratedAt=l,c.migrations.push(a),Rn(s,c)}console.log(` \u2713 Migration v${String(o.version).padStart(3,"0")} complete`)}try{let{resetCaches:o}=await Promise.resolve().then(()=>(je(),$t));o()}catch{}try{let{resetCaches:o}=await Promise.resolve().then(()=>(Lt(),xo));o()}catch{}console.log(`
20
- \u2713 Schema is now at v${Rt}
21
- `)}import"dotenv/config";import*as H from"fs";import*as X from"path";import{fileURLToPath as Mn}from"url";import"dotenv/config";function Pn(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r?`${n}m ${r}s`:`${n}m`}function Fn({scriptName:e,mode:t,status:n,error:r,duration:o}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),a=o?` ${Pn(o)}`:"",s=n==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${c} \u2014 ${s} \u2014 ${l}${a}`}async function To({scriptName:e,mode:t,status:n,summaryLines:r,error:o,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let s=`**${Fn({scriptName:e,mode:t,status:n,error:o,duration:i})}**
12
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=Ke(y.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${y.name||y.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,i&&await i(y,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${y.name||y.profileUrl}`);let g=null;if(l){let b=await wn(e,y.profileUrl);b?(d.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:b}):(d.errors++,g={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let b=ot();if(!b.allowed){console.log(` \u26A0 Global quota exhausted: ${b.reason}`);break}if(g=await kn(e,y.profileUrl,{message:r,useCustomMessage:n,excludeLocations:c}),g.success)d.connectionsSent++,g.connectionSent&&et(y.profileUrl,f);else switch(g.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(g?.fatal){console.log(`
13
+ \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(g?.reason==="error"){if(u++,u>=3){console.log(`
14
+ \u26A0 ${u} consecutive errors \u2014 aborting funnel`);break}}else u=0;if(g&&g.reason&&(Xe(y.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),be(y.profileUrl,{source:f||"funnel",jobId:y.jobId||y.fromJob?.jobId||null,jobTitle:y.fromJob?.title||null,jobCompany:y.fromJob?.company||null,action:g.reason})),i&&await i(y,d,g),p<t.length-1){let b=a+Math.random()*2e3;await h(b)}}if(console.log(`
15
+ === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let p=qe();console.log(` Quota remaining: today ${p.daily.remaining}/${p.daily.max} | week ${p.weekly.remaining}/${p.weekly.max}`)}return d}je();async function fo(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 l=n.scrollTop,a=300,i=300,c=50,f=0;for(;f<c&&(n.scrollBy(0,a),await new Promise(d=>setTimeout(d,i)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)f++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:f}},t)}async function po(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 l=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),a=n.querySelector("a.job-card-container__link");if(a){let i=a.getAttribute("href").split("?")[0],c=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),f=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:i,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${i}`,jobTitle:c,companyName:f,location:d,salary:u||null,jobLink:l?a.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function mo(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 h(2e3),t.success}async function Tt(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: npm run 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 h(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 yo(e,t,o,r){for(let n of t){await Tt(e,r)&&(await B(e),await h(2e3));let l=await e.$(`a[data-control-id="${n.dataId}"]`),a="dataId";if(!l){let i=n.id?.match(/\d+/)?.[0];i&&(l=await e.$(`a[href*="/jobs/view/${i}/"]`),l&&(a="href"))}if(l){a==="href"&&console.log(` \u{1F4CC} Found by href fallback: ${n.jobTitle}`);let i=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"}),l),await h(300),await l.click(),await h(1500);let c=!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!==i){c=!0;break}await h(500)}if(!c){await e.evaluate(u=>u.click(),l),await h(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!==i){c=!0;break}await h(500)}c||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let f=await e.evaluate(()=>{let u=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of u)for(let y of p.querySelectorAll("button")){let m=y.innerText?.trim();if(m==="Continue applying"||m==="Got it"||m==="Dismiss")return y.click(),m}return null});f&&console.log(` Dismissed popup before processing (${f})`);let{keepGoing:d}=await o(e,n);if(!d)return{keepGoing:!1}}else{let i=n.id?.match(/\d+/)?.[0]||"?";console.log(` No element for job: ${n.jobTitle||n.id} (dataId=${n.dataId}, jobId=${i})`)}}return{keepGoing:!0}}async function bo(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 l=o.querySelector('a[href*="/in/"]'),a=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(l)return{name:a?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let l=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(l)return{name:r.textContent?.trim(),profileUrl:l.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 l=n.querySelector('a[href*="/in/"]');if(l)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||l.textContent?.trim(),profileUrl:l.href?.split("?")[0],source:"people_section"}}let s=t.querySelectorAll('a[href*="/in/"]');for(let l of s){let a=l.textContent?.trim();if(a&&a.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(a))return{name:a,profileUrl:l.href?.split("?")[0],source:"details_link"}}return null})}async function ho(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 Y of s){let ee=Y.querySelector(".job-criteria__subheader")?.textContent?.trim(),ke=Y.querySelector(".job-criteria__text")?.textContent?.trim();ee&&ke&&(n[ee.toLowerCase()]=ke)}let l=["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 Y of l)new RegExp("\\b"+Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(Y.replace(/\\\+/g,"+"));let c=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,m=(u?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,b=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",k=b.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=b.match(/(\d[\d,]*)\s+applicant/i),x=w?parseInt(w[1].replace(/,/g,"")):null,j=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),D=Array.from(j).map(Y=>Y.innerText?.trim()?.replace(/\s+/g," ")),we=D.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,U=D.join(" ")+" "+b,Se=/\bremote\b/i.test(U)?"remote":/\bhybrid\b/i.test(U)?"hybrid":/\bon-?site\b/i.test(U)?"onsite":null,Z=/\bcontract\b/i.test(U)?"contract":/\bfull-?time\b/i.test(U)?"full-time":/\bpart-?time\b/i.test(U)?"part-time":/\bfreelance\b/i.test(U)?"freelance":/\btemporary\b/i.test(U)?"temporary":null,P=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",I=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",_=(P+" "+r+" "+I).toLowerCase(),A=P.toLowerCase(),$=[];/\bremote\b/.test(_)&&$.push("remote"),/\bhybrid\b/.test(_)&&$.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(_)&&$.push("onsite"),($.length===0||!$.includes("remote")&&!$.includes("hybrid")&&!$.includes("onsite"))&&/remote/i.test(I)&&$.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(A)&&$.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(A)&&$.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(A)&&!$.includes("managerial")&&$.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(A)?$.push("junior"):/\b(senior|sr\.?)\b/i.test(A)?$.push("senior"):/\b(staff|principal|distinguished)\b/i.test(A)?$.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(A)?$.push("executive"):/\b(lead|team lead)\b/i.test(A)&&$.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(_)&&$.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(_)&&$.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(_)&&$.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(_)&&$.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(_)&&$.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(_)&&$.push("mobile"),/\b(architect)\b/i.test(A)&&$.push("architect"),/\b(consultant|consulting)\b/i.test(A)&&$.push("consultant");let ve=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(ve)||/\bcontract\b/i.test(_))&&$.push("contract"),/full.?time|permanent/i.test(ve)&&$.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(I)&&$.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(I)&&$.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&$.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:d,companyName:p,companyUrl:m?m.startsWith("/")?"https://www.linkedin.com"+m:m:null,aboutCompany:c,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:k,applicantCount:x,companySize:we,workplaceType:Se,contractType:Z,techStack:[...new Set(a)],jobTags:[...new Set($)]}})}Rt();import"dotenv/config";import*as O from"fs";import*as L from"path";import{fileURLToPath as jn}from"url";var In=jn(import.meta.url),Ln=L.dirname(In),Eo=L.dirname(L.dirname(Ln)),st=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"collected-profiles"):L.join(Eo,"collected-profiles"),it=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"market-research"):L.join(Eo,"market-research"),Pt=1,Dn=[{version:1,file:"./v001-normalize-jobs-and-questions.mjs"}];function Ao(e){return L.join(e,".schema-version")}function Ft(e){let t=Ao(e);if(!O.existsSync(t))return{version:0,migrations:[]};try{return JSON.parse(O.readFileSync(t,"utf-8"))}catch{return{version:0,migrations:[]}}}function Rn(e,t){O.writeFileSync(Ao(e),JSON.stringify(t,null,2))}function $o(e,t){if(!O.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=O.readdirSync(e).filter(n=>n.endsWith(".json")&&!n.includes(".backup"));for(let n of r){let s=L.join(e,n),l=L.join(e,n+o);try{O.copyFileSync(s,l)}catch(a){console.error(` [!] Failed to backup ${n}: ${a.message}`)}}r.length>0&&console.log(` Backed up ${r.length} files in ${L.basename(e)}/ (${o})`)}var _o=!1;async function To(){if(_o)return;_o=!0;let e=Ft(st),t=Ft(it),o=Math.min(e.version,t.version);if(o>=Pt)return;console.log(`
16
+ \u{1F4E6} Schema migration: v${o} \u2192 v${Pt}`);let r=Dn.filter(n=>n.version>o);for(let n of r){console.log(`
17
+ Running migration v${String(n.version).padStart(3,"0")}...`),$o(st,n.version),$o(it,n.version);let s=await import(n.file);try{await s.up(st,it)}catch(i){console.error(`
18
+ [FATAL] Migration v${n.version} failed: ${i.message}`),console.error(` Backups are in collected-profiles/ and market-research/ (.pre-v${String(n.version).padStart(3,"0")}.backup)`),console.error(` Fix the issue and restart.
19
+ `),process.exit(1)}let l=new Date().toISOString(),a={version:n.version,name:s.NAME||`v${String(n.version).padStart(3,"0")}`,appliedAt:l};for(let i of[st,it]){if(!O.existsSync(i))continue;let c=Ft(i);c.version=n.version,c.migratedAt=l,c.migrations.push(a),Rn(i,c)}console.log(` \u2713 Migration v${String(n.version).padStart(3,"0")} complete`)}try{let{resetCaches:n}=await Promise.resolve().then(()=>(je(),_t));n()}catch{}try{let{resetCaches:n}=await Promise.resolve().then(()=>(Rt(),Co));n()}catch{}console.log(`
20
+ \u2713 Schema is now at v${Pt}
21
+ `)}import"dotenv/config";import*as H from"fs";import*as X from"path";import{fileURLToPath as Mn}from"url";import"dotenv/config";function Pn(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 Fn({scriptName:e,mode:t,status:o,error:r,duration:n}){let s=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),a=n?` ${Pn(n)}`:"",i=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${c} \u2014 ${i} \u2014 ${l}${a}`}async function qo({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:s}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let i=`**${Fn({scriptName:e,mode:t,status:o,error:n,duration:s})}**
22
22
 
23
23
  ${r.join(`
24
- `)}`;try{await te.addMessage(l,s)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Nn=Mn(import.meta.url),On=X.dirname(X.dirname(Nn)),Ft=process.env.DATA_DIR?X.resolve(process.env.DATA_DIR,"collected-profiles"):X.join(On,"collected-profiles"),Mt=X.join(Ft,"run-log.json");function Un(e,t){let n=JSON.stringify(t,null,2),r=e+".tmp";H.writeFileSync(r,n);for(let o=0;o<3;o++)try{H.renameSync(r,e);return}catch(i){if(o<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function jo(){try{if(!H.existsSync(Mt))return{runs:[]};let e=JSON.parse(H.readFileSync(Mt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Io(e){H.existsSync(Ft)||H.mkdirSync(Ft,{recursive:!0});try{Un(Mt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Do(e,t="default"){let n=jo();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let r=new Date,o={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(o);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>i),Io(n),{script:e,mode:t,startTime:r.getTime(),runIndex:n.runs.length-1}}function qo(e,t,n=null,r=null){if(!e)return;let o=null;try{let l=jo(),a=l.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=n,a.error=r,o=a.duration;else{let s=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=r,o=s.duration)}Io(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";To({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:r,duration:o??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import Lo from"fs";import Bn from"path";var Jn="cookies.json";function Gn(){let e=process.env.ILML_SCOPE_DIR;return e?Bn.join(e,"plugins-state","linkedin","cookies.json"):Jn}function Nt(){let e=Gn();if(!Lo.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Lo.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}async function it(e,t,n="op"){let r,o=new Promise((i,l)=>{r=setTimeout(()=>l(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,o])}finally{clearTimeout(r)}}function ge(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let n=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(n)||/Target closed/i.test(n)||/Session closed/i.test(n)||/Connection closed/i.test(n)||/Most likely the page has been closed/i.test(n)||/Navigating frame was detached/i.test(n)||/Protocol error.*timed out/i.test(n)}async function Ro(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await it(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function Po(e,{timeoutMs:t=3e3,retryDelayMs:n=5e3}={}){return await Ro(e,t)?!0:(await b(n),await Ro(e,t))}async function Fo(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await it(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function Mo(e,t,{returnUrl:n,gotoTimeoutMs:r=6e4,cookiesProvider:o=null,setupPage:i=null}={}){try{await it(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let l=await e.newPage();if(i)try{await i(l)}catch{}if(o)try{let a=o();Array.isArray(a)&&a.length>0&&await l.setCookie(...a)}catch{}if(n){await l.goto(n,{waitUntil:"domcontentloaded",timeout:r});let a=l.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 l}async function No(e,{launchFn:t,returnUrl:n,gotoTimeoutMs:r=6e4,cookiesProvider:o=null,setupPage:i=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");try{await it(e.close(),5e3,"oldBrowser.close")}catch{}let l=await t(),a=await l.newPage();if(i)try{await i(a)}catch{}if(o)try{let s=o();Array.isArray(s)&&s.length>0&&await a.setCookie(...s)}catch{}if(n){await a.goto(n,{waitUntil:"domcontentloaded",timeout:r});let s=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(s))throw new Error(`Session expired after browser restart \u2014 landed on ${s}. Run: ilml linkedin login`)}return{browser:l,page:a}}await Ao();var dt=0,Vn=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Wn=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Yn=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Ot=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],lt=-1;async function Qn(){if(lt===-1){let e=await ue("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}"`);lt=Ht(e)+1,console.log(`lastIndex initialized as: ${lt}`)}return lt++}var zo=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${zo}`);var zn=[{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=>{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:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Ne={};function Ko(e){return zn.find(t=>t.match(e))||null}function Kn(e){return Ne[e]=(Ne[e]||0)+1,Ne[e]}function Uo(){for(let e of Object.keys(Ne))Ne[e]=0}var Ut=0;function Xn(){return Ut++,Ut>=zo?(console.log(`Max run counter reached with ${Ut}`),!1):!0}async function Zn(e){let t=await uo(e)}async function er(e){return po(e,{easyApplyOnly:!0})}async function tr(e){return fo(e)}async function Gt(e,t){return At(e,t)}var Bt=3,or=2;async function ct(e,t){let{searchUrl:n,launchFn:r,setupPage:o,cookiesProvider:i}=e.recoveryCtx,l=await Fo(e.browser);if(!l||e._pageRecoveryStreak>=Bt){if(S.browserRestarts>=or)throw new Error(`CDP unrecoverable: ${S.browserRestarts} browser restart${S.browserRestarts===1?"":"s"} and ${S.cdpRecoveries} page recover${S.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let s=l?`${Bt} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${s}). Reason: ${t}`);let c=await No(e.browser,{launchFn:r,setupPage:o,cookiesProvider:i,returnUrl:n});e.browser=c.browser,e.page=c.page,e._pageRecoveryStreak=0,S.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${S.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${Bt}). Reason: ${t}`),e.page=await Mo(e.browser,e.page,{returnUrl:n,cookiesProvider:i,setupPage:o}),e._pageRecoveryStreak+=1,S.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${S.cdpRecoveries}).`)}async function nr(e){let{searchUrl:t}=e.recoveryCtx,n=3;e._pageRecoveryStreak=e._pageRecoveryStreak||0;for(let r=1;r<=n;r++){if(r>1){console.log(`
25
- --- Pass ${r}/${n}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(a){if(ge(a))await ct(e,`pass-${r} navigation: ${a.message?.slice(0,80)}`);else throw a}await b(3e3)}let o=S.submitted,i=!0,l=!0;for(;i&&l;){if(!await Po(e.page)){await ct(e,"liveness probe failed twice");continue}try{await Gt(e.page,t);let s=await mr(e.page,Zo,Zn);l=s.keepGoing;let c=s.jobsDone;if(console.log("keepGoing",l),console.log("pageDone"),console.log(c.length),!l)break;i=await tr(e.page),e._pageRecoveryStreak=0}catch(s){if(!ge(s))throw s;await ct(e,`mid-iteration: ${s.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!l)break;if(S.submitted===o){console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${S.submitted-o} new jobs in pass ${r}.`)}}async function Bo(e,t,n){let r=process.env.LINKEDIN_SEARCH_URL;return mo(e,t,n,r)}async function Jo(e,t){let n=t?.match(/\d+/)?.[0]||t,r=await e.$(`div[data-job-id="${n}"] button[aria-label^="Dismiss"]`);r?(await r.click(),console.log(` Dismissed job ${n} from list`)):console.log(` Dismiss button not found for ${n}`)}async function rr(e,t){try{let n=await yo(e);if(n&&n.profileUrl){n.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},Ce("recruiters-from-jobs",n)?(dt++,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: ${n.name?.substring(0,30).padEnd(30)} \u2502`),console.log(`\u2502 Source: ${n.source.padEnd(28)} \u2502`),console.log(`\u2502 Company: ${t.companyName?.substring(0,27).padEnd(27)} \u2502`),console.log(`\u2502 Total today: ${String(dt).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: ${n.name}`),Ae(n.profileUrl,{name:n.name,source:"recruiters-from-jobs"});let o=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(o){Qe(n.profileUrl,o),he(n.profileUrl,{source:"job-apply",jobId:o,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let i=n.fromJob?.companyUrl;i&&ot(i,{recruiterUrl:n.profileUrl,jobId:o})}return n}else console.log(" \u26AA No recruiter found on this job page");return null}catch(n){return console.error("Error extracting recruiter:",n.message),null}}async function ut(e){return await e.evaluate(()=>{let t=document.body.innerText||"",n=document.querySelector("#interop-outlet")?.shadowRoot?.textContent||"",r=t+" "+n;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 Xo(e){try{let t=await e.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let o of n){let i=o.querySelectorAll("button");for(let l of i){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.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 Go(e){await e.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let s of a.querySelectorAll("button")){let c=s.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){s.click();return}}});let t=Date.now(),n=3e3,r=null;for(;!r&&Date.now()-t<n;){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 l=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let s of a){let c=s.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return s}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let o=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${o>400?` (waited ${o}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await ut(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await b(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 b(2e3)}}else await r.click(),await b(1500);return await ut(e)?(await Xo(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await ut(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function sr(e){return await e.evaluate(async()=>{function t(){let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length>0)return s;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(s=c.querySelectorAll(".artdeco-inline-feedback__message")),s}let n=3e3,r=t();if(r?.length===0&&(await new Promise(s=>setTimeout(s,n)),r=t()),r?.length===0)return null;let o=r[0];console.log("errorMsg"),console.log(o);let i=o?.textContent.trim(),l=o.parentElement.parentElement.querySelector("label")?.textContent.trim(),a=o.closest(".fb-dash-form-element");if(console.log("parentElement"),console.log(a),console.log("isUpload"),console.log(l),a||l){console.log("parentElement"),console.log(a);let s=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"),c=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")),p=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),u=o.parentElement.parentElement.querySelector('input[type="file"]'),d=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(u),s&&c)return{type:"input",labelText:s.textContent.trim(),errorMsgText:i};if(s&&p.length){let m=s?s.querySelector("span:nth-of-type(1)")?.textContent.trim():null,y=Array.from(p).map(h=>{let k=(document.querySelector(`label[for="${h.id}"]`)||h.nextElementSibling)?.textContent?.trim();return{value:h.value,label:k||h.value}}),g=y.map(h=>h.label);return{type:"radio",labelText:m,errorMsgText:i,options:g,optionsData:y}}else if(f){let m=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),y=m?m.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(f.options).map(h=>h.value).filter(h=>h!=="Select an option");return{type:"select",labelText:y,errorMsgText:i,options:g}}else if(u){let m=o.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:i,labelText:m}}else{if(d)return{type:"datePicker",errorMsgText:i};{let m=s?s.querySelector("span:nth-of-type(2)")?.textContent.trim():null,y=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(y.length>0){let g=Array.from(y).map(h=>h.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:m,errorMsgText:i,options:g}}else return null}}}return null})}async function ir(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let s=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"));s.value=o;let c=new Event("input",{bubbles:!0});if(s.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(s)}}return null},t,n)}async function lr(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let s=a.querySelectorAll('input[type="radio"]'),c=o;if(r.optionsData){let p=r.optionsData.find(f=>f.label.toLowerCase()===o.toLowerCase());p&&(c=p.value,console.log(`Radio: matched label "${o}" to value "${c}"`))}for(let p of s){let u=(document.querySelector(`label[for="${p.id}"]`)||p.nextElementSibling)?.textContent?.trim()||"";if(p.value.toLowerCase()===c.toLowerCase()||u.toLowerCase()===o.toLowerCase()){p.checked=!0;let d=new Event("change",{bubbles:!0});p.dispatchEvent(d),console.log(`Radio selected: value="${p.value}", label="${u}"`);break}}}return null},t,n)}async function ar(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let s=a.querySelector("select[data-test-text-entity-list-form-select]");if(!s)return null;let c=Array.from(s.options),p=c.find(u=>u.text.toLowerCase()===o.toLowerCase())||c.find(u=>u.text.toLowerCase().includes(o.toLowerCase()));p?s.value=p.value:s.value=o;let f=new Event("change",{bubbles:!0});s.dispatchEvent(f)}return null},t,n)}async function cr(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length===0){let s=document.querySelector("#interop-outlet")?.shadowRoot;s&&(i=s.querySelectorAll(".artdeco-inline-feedback__message"))}if(i?.length===0)return null;let a=i[0].closest(".fb-dash-form-element");if(a){let s=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');s.length>0&&s.forEach(c=>{if(c.nextElementSibling.textContent.trim()===o.trim()){c.checked=!0;let p=new Event("change",{bubbles:!0});c.dispatchEvent(p)}})}return null},t,n)}async function ur(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i?.length===0)return null;let l=i[0],a=l.closest(".fb-dash-form-element"),s=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&s){async function c(p,f,u){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let m=new Blob([new Uint8Array(f)]),y=new File([m],u,{type:"application/pdf"}),g=new DataTransfer;g.items.add(y),p.files=g.files;let h=new Event("change",{bubbles:!0});p.dispatchEvent(h)}await c(s,o,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,n)}async function Ho(e){let t=await sr(e);if(t===null)return null;if(t?.type==="input"){let o=await Wt(t.labelText,t.errorMsgText);o=o?.trim()||o,t.answer=o,await ir(e,t,o)}else if(t?.type==="radio"){let o=await mt(t.labelText,t.options);o=o?.trim()||o;let i=t.options||[];!i.find(a=>a.toLowerCase()===o?.toLowerCase())&&i.length>0&&(console.log(` \u26A0 Lifebot gave invalid radio answer "${o}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),o=await mt(t.labelText,t.options),o=o?.trim()||o,i.find(s=>s.toLowerCase()===o?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${i[0]}"`),o=i[0])),t.answer=o,await lr(e,t,o)}else if(t?.type==="select"){let o=await Ue(t.labelText,t.options);o=o?.trim()||o;let i=t.options||[],l=i.find(a=>a.toLowerCase()===o?.toLowerCase());if(l)o=l;else if(i.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${o}" for "${t.labelText}". Options: ${i.join(", ")}. Retrying...`),o=await Ue(t.labelText,t.options),o=o?.trim()||o;let a=i.find(s=>s.toLowerCase()===o?.toLowerCase());a?o=a:(console.log(` \u26A0 Retry also invalid: "${o}". Using first option: "${i[0]}"`),o=i[0])}t.answer=o,await ar(e,t,o)}else if(t?.type==="checkbox"){let o=await Ue(t.labelText,t.options);t.answer=o,await cr(e,t,o)}else if(t?.type==="file"){let o=process.env.RESUME_PDF_URL;t.answer=o;let i=await fetch(o);if(!i.ok)throw new Error("Network response was not ok");let l=await i.arrayBuffer();await ur(e,t,l)}else t?.type==="datePicker"?t.answer="(not implemented)":t.answer="(unknown field type)";let n=t.labelText?.slice(0,55)||"?",r=t.answer!=null?`"${String(t.answer).slice(0,50)}"`:"(no answer)";return console.log(` ? [${t.type}] "${n}" \u2192 ${r}`),t}async function dr(e){return await e.evaluate(async()=>{let t=[],n=document.querySelectorAll(".fb-dash-form-element");if(!n||n.length===0){let r=document.querySelector("#interop-outlet")?.shadowRoot;r&&(n=r.querySelectorAll(".fb-dash-form-element"))}if(!n||n.length===0)return[];for(let r of n){let o=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"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),s=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),p=r.querySelector('input[type="file"]');if(o&&l&&a.length===0){let f=o.textContent.trim();t.push({type:"input",labelText:f,answer:l.value,isRequired:i,wasPreFilled:!!l.value})}else if(o&&a.length){let f=o?o.querySelector("span:nth-of-type(1)")?.textContent.trim():null,u=Array.from(a).map(m=>m.value),d=(Array.from(a).find(m=>m.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:u,answer:d,isRequired:i,wasPreFilled:!!d})}else if(s){let f=r.querySelector('label[for="'+s.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),u=f?f.querySelector("span:nth-of-type(2)")?.textContent.trim():null,d=Array.from(s.options).map(y=>y.value).filter(y=>y!=="Select an option"),m=s.value!=="Select an option"?s.value:"";t.push({type:"select",labelText:u,options:d,answer:m,isRequired:i,wasPreFilled:!!m})}else if(c.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),u=Array.from(c).map(d=>({label:d.nextElementSibling?.textContent?.trim()||d.value,checked:d.checked}));t.push({type:"checkbox",labelText:f,options:u.map(d=>d.label),answer:u.filter(d=>d.checked).map(d=>d.label).join(", "),isRequired:i})}else if(p){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:p.value?"uploaded":"",isRequired:i})}}return t})}async function Vo(e,t,n){return await e.evaluate(async(r,o)=>{let i=document.querySelectorAll(".fb-dash-form-element");if(!i||i.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(i=l.querySelectorAll(".fb-dash-form-element"))}if(!i||i.length===0)return!1;for(let l of i){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),s=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&s&&r===a.textContent.trim()){s.value=o;let c=new Event("input",{bubbles:!0});if(s.dispatchEvent(c),r==="City"||r==="Location (city)"){let p=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});d.dispatchEvent(m)},f=d=>{let m=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});d.dispatchEvent(m)};await(async d=>{await new Promise(m=>setTimeout(m,500)),f(d),await new Promise(m=>setTimeout(m,100)),p(d)})(s)}return!0}}return!1},t,n)}async function Wo(e,t){let n=[],r=!0,o=0,i=null,l=0;for(;r;){if(o++,await ut(e))return console.log(" Daily limit reached during form navigation"),await Xo(e),{filledFields:n,formPages:o,skip:!0,dailyLimitReached:!0};let c=(await dr(e)).filter(d=>!n.some(m=>m.labelText===d.labelText));n.push(...c);try{let d=n.find(y=>y.labelText==="City"||y.labelText==="Location (city)"),m=n.filter(y=>y.labelText!=null).find(y=>y.labelText!==null&&y.labelText.trim()!==null&&(y.labelText.trim().toLowerCase()==="cv"||y.labelText.trim().toLowerCase()==="curriculum vitae"||y.labelText.trim().toLowerCase()==="cover letter"||y.labelText.trim().toLowerCase()==="cover"));if(d&&!d.answer){let y=process.env.City;await Vo(e,d.labelText,y),d.answer=y}else if(m){let y=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!m.answer||m.answer!==y)&&(await b(1e4),await Vo(e,m.labelText,y),m.answer=y,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}let p=null;try{p=await t(e)}catch(d){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${d.message?.slice(0,100)}`),{filledFields:n,formPages:o,skip:!0}}if(p!==null){if(p.type==="datePicker")return{filledFields:n,formPages:o,skip:!0,duplicateField:p};let d=p&&n.find(y=>y.errorMsgText&&y.labelText===p.labelText);if(d)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(p,null,2)),console.log("Previous attempt:",JSON.stringify(d,null,2)),{filledFields:n,formPages:o,skip:!0,duplicateField:p};let m=n.findIndex(y=>y.labelText===p.labelText&&!y.answer);m!==-1&&n.splice(m,1),n.push(p)}let f=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of d){let y=m.querySelectorAll("button");for(let g of y){let h=g.innerText?.trim();if(h==="Continue applying"||h==="Got it"||h==="Dismiss")return g.click(),h}}return null});f&&console.log(` Dismissed safety popup (${f})`);let u=await e.evaluate(async()=>{function d(w){let x=document.querySelector(w);if(x)return x;let I=document.querySelector("#interop-outlet")?.shadowRoot;return I?I.querySelector(w):null}function m(w){let x=document.querySelectorAll(w),I=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...x||[],...I||[]]}let y=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),g=m('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||m("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),h=d('button[aria-label="Submit application"]'),v=async()=>{let w=d("button[data-easy-apply-next-button]")||d('button[aria-label="Continue to next step"]')||m("footer button, button.artdeco-button--primary").find(x=>x.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},k=()=>{let w=m("button").find(x=>x.innerText?.trim()==="Review");w&&w.click()};return y?(await v(),{type:"next"}):g?(await k(),{type:"review"}):h?{type:"submit"}:{type:null}});if(u==null)return{filledFields:n,formPages:o,skip:!0};if(u.type&&console.log(` \u2192 ${u.type}`),u.type===null){let d=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let y of m){let g=y.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let h of g){let v=h.innerText||"";if(v.includes("application was sent")||v.includes("resume into a profile")||v.includes("Application submitted")||v.includes("Next best action"))for(let k of h.querySelectorAll("button")){let w=k.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return k.click(),w}}}return null});if(d)return console.log(` Dismissed stale popup (${d}) \u2014 need to re-open Easy Apply`),await b(1500),{filledFields:n,formPages:o,skip:!1,stalePopupDismissed:!0};if(l===0){let m=await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],h=[];for(let v of y){for(let w of v.querySelectorAll("button")){let x=w.innerText?.trim();x&&x.length<60&&g.push(x)}let k=v.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');k&&h.push(k.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:h.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:n,formPages:o,skip:!1};if(p===null&&u.type===i?l++:l=0,i=u.type,l>=5){let d=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),y=[],g=[];for(let h of m){for(let v of h.querySelectorAll(".artdeco-inline-feedback__message"))y.push(v.textContent?.trim()?.slice(0,60));for(let v of h.querySelectorAll(".fb-dash-form-element")){let k=v.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=v.querySelector("input, select, textarea"),x=!!v.querySelector(".artdeco-inline-feedback__message");k&&(x||w&&!w.value)&&g.push({label:k.slice(0,40),hasError:x,value:w?.value?.slice(0,20)||""})}}return{errors:y,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${u.type}" for ${l} iterations \u2014 form not progressing.`),d.errors.length&&console.error(` Visible errors: ${JSON.stringify(d.errors)}`),d.emptyRequired.length&&console.error(` Empty/error fields: ${JSON.stringify(d.emptyRequired)}`),console.error(" Skipping job."),{filledFields:n,formPages:o,skip:!0,duplicateField:{labelText:`stuck_on_${u.type}`}}}await b(1500),r=!0}return{filledFields:n,formPages:o,skip:!1}}async function Yo(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 pr(e){let t=await e.$('button[aria-label="Submit application"]');if(!t){let n=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Submit application"]')||null);t=n?.asElement?.()||null,t||await n.dispose().catch(()=>{})}t&&await t.click()}async function fr(e){try{let t=await e.evaluate(()=>{let n=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let r of n){for(let i of r.querySelectorAll('div.artdeco-modal button, [role="dialog"] button'))if(i.innerText?.trim()==="Done")return i.click(),"Done";let o=r.querySelectorAll('div.artdeco-modal, [role="dialog"]');for(let i of o){let l=i.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of i.querySelectorAll("button")){let s=a.innerText?.trim();if(s==="Not now"||s==="Dismiss")return a.click(),s}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await b(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function at(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 b(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 Jt(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 b(500))}catch{console.log("No discard confirmation needed")}}async function Zo(e,t){let n=[],r=t._fromQueue;try{S.attempted++,console.log(`
26
- --- Processing: ${t.jobTitle} at ${t.companyName} ---`);let o=t.id?.match(/\d+/)?.[0];if(o&&Dt(o)?.status==="applied")return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let i=null;if(!r){let u=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()||""),d=(t.companyName||"").replace(/\s+/g," ").toLowerCase().trim(),m=u.split(" ")[0],y=d.split(" ")[0];if(m&&y&&!u.includes(y)&&!d.includes(m))return S.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${u}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let h=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!h)return!1;let v=h.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(v)||v.includes("Application submitted")}))return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),o&&ae(o,"applied",{source:"detected"}),{keepGoing:!0};try{i=await ho(e)}catch{}}let l=await Go(e);if(l.dailyLimitReached){console.log(`
24
+ `)}`;try{await te.addMessage(l,i)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Nn=Mn(import.meta.url),On=X.dirname(X.dirname(Nn)),Mt=process.env.DATA_DIR?X.resolve(process.env.DATA_DIR,"collected-profiles"):X.join(On,"collected-profiles"),Nt=X.join(Mt,"run-log.json");function Un(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";H.writeFileSync(r,o);for(let n=0;n<3;n++)try{H.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function jo(){try{if(!H.existsSync(Nt))return{runs:[]};let e=JSON.parse(H.readFileSync(Nt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Io(e){H.existsSync(Mt)||H.mkdirSync(Mt,{recursive:!0});try{Un(Nt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Lo(e,t="default"){let o=jo();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let 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(l=>new Date(l.timestamp).getTime()>s),Io(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Do(e,t,o=null,r=null){if(!e)return;let n=null;try{let l=jo(),a=l.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 i=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());i&&(i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=o,i.error=r,n=i.duration)}Io(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";qo({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:r,duration:n??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import Ro from"fs";import Bn from"path";var Jn="cookies.json";function Gn(){let e=process.env.ILML_SCOPE_DIR;return e?Bn.join(e,"plugins-state","linkedin","cookies.json"):Jn}function Ot(){let e=Gn();if(!Ro.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Ro.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}async function lt(e,t,o="op"){let r,n=new Promise((s,l)=>{r=setTimeout(()=>l(new Error(`${o} timeout after ${t}ms`)),t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}function ge(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 Po(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await lt(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function Fo(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await Po(e,t)?!0:(await h(o),await Po(e,t))}async function Mo(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await lt(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function No(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){try{await lt(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let l=await e.newPage();if(s)try{await s(l)}catch{}if(n)try{let a=n();Array.isArray(a)&&a.length>0&&await l.setCookie(...a)}catch{}if(o){await l.goto(o,{waitUntil:"domcontentloaded",timeout:r});let a=l.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 l}async function Oo(e,{launchFn:t,returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){if(!t)throw new Error("relaunchBrowser: launchFn is required");try{await lt(e.close(),5e3,"oldBrowser.close")}catch{}let l=await t(),a=await l.newPage();if(s)try{await s(a)}catch{}if(n)try{let i=n();Array.isArray(i)&&i.length>0&&await a.setCookie(...i)}catch{}if(o){await a.goto(o,{waitUntil:"domcontentloaded",timeout:r});let i=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(i))throw new Error(`Session expired after browser restart \u2014 landed on ${i}. Run: ilml linkedin login`)}return{browser:l,page:a}}await To();var ft=0,Vn=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",Wn=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),Yn=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",Ut=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],at=-1;async function Qn(){if(at===-1){let e=await ue("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}"`);at=Wt(e)+1,console.log(`lastIndex initialized as: ${at}`)}return at++}var zo=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${zo}`);var zn=[{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=>{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:"stale-context",match:e=>/Execution context was destroyed|Cannot find context/.test(e.message),severity:"transient",maxConsecutive:5,cooldownMs:3e3}],Oe={};function Ko(e){return zn.find(t=>t.match(e))||null}function Kn(e){return Oe[e]=(Oe[e]||0)+1,Oe[e]}function Bo(){for(let e of Object.keys(Oe))Oe[e]=0}var Bt=0;function Xn(){return Bt++,Bt>=zo?(console.log(`Max run counter reached with ${Bt}`),!1):!0}async function Zn(e){let t=await fo(e)}async function er(e){return po(e,{easyApplyOnly:!0})}async function tr(e){return mo(e)}async function Ht(e,t){return Tt(e,t)}var Jt=3,or=2;async function ut(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:s}=e.recoveryCtx,l=await Mo(e.browser);if(!l||e._pageRecoveryStreak>=Jt){if(S.browserRestarts>=or)throw new Error(`CDP unrecoverable: ${S.browserRestarts} browser restart${S.browserRestarts===1?"":"s"} and ${S.cdpRecoveries} page recover${S.cdpRecoveries===1?"y":"ies"} all failed. Last reason: ${t}`);let i=l?`${Jt} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${i}). Reason: ${t}`);let c=await Oo(e.browser,{launchFn:r,setupPage:n,cookiesProvider:s,returnUrl:o});e.browser=c.browser,e.page=c.page,e._pageRecoveryStreak=0,S.browserRestarts+=1,console.log(`\u2713 Browser restarted (total restarts this run: ${S.browserRestarts}).`);return}console.log(`\u{1F504} CDP dead \u2014 recovering page (attempt ${e._pageRecoveryStreak+1}/${Jt}). Reason: ${t}`),e.page=await No(e.browser,e.page,{returnUrl:o,cookiesProvider:s,setupPage:n}),e._pageRecoveryStreak+=1,S.cdpRecoveries+=1,console.log(`\u2713 Page recovered (total page recoveries this run: ${S.cdpRecoveries}).`)}async function nr(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(`
25
+ --- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(a){if(ge(a))await ut(e,`pass-${r} navigation: ${a.message?.slice(0,80)}`);else throw a}await h(3e3)}let n=S.submitted,s=!0,l=!0;for(;s&&l;){if(!await Fo(e.page)){await ut(e,"liveness probe failed twice");continue}try{await Ht(e.page,t);let i=await gr(e.page,Zo,Zn);l=i.keepGoing;let c=i.jobsDone;if(console.log("keepGoing",l),console.log("pageDone"),console.log(c.length),!l)break;s=await tr(e.page),e._pageRecoveryStreak=0}catch(i){if(!ge(i))throw i;await ut(e,`mid-iteration: ${i.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!l)break;if(S.submitted===n){console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${S.submitted-n} new jobs in pass ${r}.`)}}async function Jo(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return yo(e,t,o,r)}async function Go(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 rr(e,t){try{let o=await bo(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},$e("recruiters-from-jobs",o)?(ft++,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(ft).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}`),Te(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){ze(o.profileUrl,n),be(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=o.fromJob?.companyUrl;s&&nt(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 dt(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 Xo(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 l of s){let a=l.innerText?.trim();if(a==="Got it"||a==="OK"||a==="Done")return l.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 Ho(e){await e.evaluate(()=>{let l=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let a of l)for(let i of a.querySelectorAll("button")){let c=i.innerText?.trim();if(c==="Continue applying"||c==="Got it"||c==="Dismiss"){i.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 l=await e.evaluateHandle(()=>{let a=document.querySelectorAll("button, a");for(let i of a){let c=i.innerText?.trim();if(c==="Easy Apply"||c==="Apply")return i}return null});r=l?.asElement?.()||null,r||await l.dispose().catch(()=>{})}r||await new Promise(l=>setTimeout(l,300))}let n=Date.now()-t;if(console.log(` pressApplyButton: found=${!!r}${n>400?` (waited ${n}ms)`:""}`),r){if(await e.evaluate(c=>c.disabled,r))return await dt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(c=>c.tagName==="A",r)){await e.evaluate(c=>c.click(),r),await h(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 h(2e3)}}else await r.click(),await h(1500);return await dt(e)?(await Xo(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await dt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function sr(e){return await e.evaluate(async()=>{function t(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let c=document.querySelector("#interop-outlet")?.shadowRoot;return c&&(i=c.querySelectorAll(".artdeco-inline-feedback__message")),i}let o=3e3,r=t();if(r?.length===0&&(await new Promise(i=>setTimeout(i,o)),r=t()),r?.length===0)return null;let n=r[0];console.log("errorMsg"),console.log(n);let s=n?.textContent.trim(),l=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(l),a||l){console.log("parentElement"),console.log(a);let i=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"),c=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")),f=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),i&&c)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&f.length){let y=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,m=Array.from(f).map(b=>{let k=(document.querySelector(`label[for="${b.id}"]`)||b.nextElementSibling)?.textContent?.trim();return{value:b.value,label:k||b.value}}),g=m.map(b=>b.label);return{type:"radio",labelText:y,errorMsgText:s,options:g,optionsData:m}}else if(d){let y=a.querySelector('label[for="'+d.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),m=y?y.querySelector("span:nth-of-type(2)")?.textContent.trim():null,g=Array.from(d.options).map(b=>b.value).filter(b=>b!=="Select an option");return{type:"select",labelText:m,errorMsgText:s,options:g}}else if(u){let y=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:y}}else{if(p)return{type:"datePicker",errorMsgText:s};{let y=i?i.querySelector("span:nth-of-type(2)")?.textContent.trim():null,m=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(m.length>0){let g=Array.from(m).map(b=>b.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:y,errorMsgText:s,options:g}}else return null}}}return null})}async function ir(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=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"));i.value=n;let c=new Event("input",{bubbles:!0});if(i.dispatchEvent(c),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let f=p=>{let y=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(y)},d=p=>{let y=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(y)};await(async p=>{await new Promise(y=>setTimeout(y,500)),d(p),await new Promise(y=>setTimeout(y,100)),f(p)})(i)}}return null},t,o)}async function lr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('input[type="radio"]'),c=n;if(r.optionsData){let f=r.optionsData.find(d=>d.label.toLowerCase()===n.toLowerCase());f&&(c=f.value,console.log(`Radio: matched label "${n}" to value "${c}"`))}for(let f of i){let u=(document.querySelector(`label[for="${f.id}"]`)||f.nextElementSibling)?.textContent?.trim()||"";if(f.value.toLowerCase()===c.toLowerCase()||u.toLowerCase()===n.toLowerCase()){f.checked=!0;let p=new Event("change",{bubbles:!0});f.dispatchEvent(p),console.log(`Radio selected: value="${f.value}", label="${u}"`);break}}}return null},t,o)}async function ar(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelector("select[data-test-text-entity-list-form-select]");if(!i)return null;let c=Array.from(i.options),f=c.find(u=>u.text.toLowerCase()===n.toLowerCase())||c.find(u=>u.text.toLowerCase().includes(n.toLowerCase()));f?i.value=f.value:i.value=n;let d=new Event("change",{bubbles:!0});i.dispatchEvent(d)}return null},t,o)}async function cr(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".artdeco-inline-feedback__message");if(s.length===0){let i=document.querySelector("#interop-outlet")?.shadowRoot;i&&(s=i.querySelectorAll(".artdeco-inline-feedback__message"))}if(s?.length===0)return null;let a=s[0].closest(".fb-dash-form-element");if(a){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');i.length>0&&i.forEach(c=>{if(c.nextElementSibling.textContent.trim()===n.trim()){c.checked=!0;let f=new Event("change",{bubbles:!0});c.dispatchEvent(f)}})}return null},t,o)}async function ur(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 l=s[0],a=l.closest(".fb-dash-form-element"),i=l.parentElement.parentElement.querySelector('input[type="file"]');if(a&&i){async function c(f,d,u){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let y=new Blob([new Uint8Array(d)]),m=new File([y],u,{type:"application/pdf"}),g=new DataTransfer;g.items.add(m),f.files=g.files;let b=new Event("change",{bubbles:!0});f.dispatchEvent(b)}await c(i,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function Vo(e){let t=await sr(e);if(t===null)return null;if(t?.type==="input"){let n=await yt(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await ir(e,t,n)}else if(t?.type==="radio"){let n=await Be(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 Be(t.labelText,t.options),n=n?.trim()||n,s.find(i=>i.toLowerCase()===n?.toLowerCase())||(console.log(` \u26A0 Retry also invalid: "${n}". Using first option: "${s[0]}"`),n=s[0])),t.answer=n,await lr(e,t,n)}else if(t?.type==="select"){let n=await xe(t.labelText,t.options);n=n?.trim()||n;let s=t.options||[],l=s.find(a=>a.toLowerCase()===n?.toLowerCase());if(l)n=l;else if(s.length>0){console.log(` \u26A0 Lifebot gave invalid select answer "${n}" for "${t.labelText}". Options: ${s.join(", ")}. Retrying...`),n=await xe(t.labelText,t.options),n=n?.trim()||n;let a=s.find(i=>i.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 ar(e,t,n)}else if(t?.type==="checkbox"){let n=await xe(t.labelText,t.options);t.answer=n,await cr(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 l=await s.arrayBuffer();await ur(e,t,l)}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 dr(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"),l=r.querySelector(".artdeco-text-input--input")||r.querySelector("input"),a=r.querySelectorAll('input[type="radio"]'),i=r.querySelector("select[data-test-text-entity-list-form-select]"),c=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),f=r.querySelector('input[type="file"]');if(n&&l&&a.length===0){let d=n.textContent.trim();t.push({type:"input",labelText:d,answer:l.value,isRequired:s,wasPreFilled:!!l.value})}else if(n&&a.length){let d=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,u=Array.from(a).map(y=>y.value),p=(Array.from(a).find(y=>y.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:d,options:u,answer:p,isRequired:s,wasPreFilled:!!p})}else if(i){let d=r.querySelector('label[for="'+i.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(i.options).map(m=>m.value).filter(m=>m!=="Select an option"),y=i.value!=="Select an option"?i.value:"";t.push({type:"select",labelText:u,options:p,answer:y,isRequired:s,wasPreFilled:!!y})}else if(c.length>0){let d=r.querySelector("legend span")?.textContent?.trim(),u=Array.from(c).map(m=>({label:m.nextElementSibling?.textContent?.trim()||m.value,checked:m.checked})),p=u.some(m=>m.checked),y=u.filter(m=>m.checked).map(m=>m.label).join(", ");t.push({type:"checkbox",labelText:d,options:u.map(m=>m.label),answer:y,isRequired:s,wasPreFilled:p})}else if(f){let d=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:d,answer:f.value?"uploaded":"",isRequired:s,wasPreFilled:!!f.value})}}return t})}async function Vt(e,t,o){return await e.evaluate(async(r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector(".artdeco-text-input--label")||l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('[class*="fb-dash-form-element__label"] span[aria-hidden="true"]')||l.parentElement.parentElement?.querySelector(".jobs-easy-apply-form-section__group-subtitle"),i=l.querySelector(".artdeco-text-input--input")||l.querySelector("input");if(a&&i&&r===a.textContent.trim()){i.value=n;let c=new Event("input",{bubbles:!0});if(i.dispatchEvent(c),r==="City"||r==="Location (city)"){let f=p=>{let y=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(y)},d=p=>{let y=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(y)};await(async p=>{await new Promise(y=>setTimeout(y,500)),d(p),await new Promise(y=>setTimeout(y,100)),f(p)})(i)}return!0}}return!1},t,o)}async function fr(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelectorAll('input[type="radio"]');if(a.length===0)continue;let i=l.querySelector("legend .fb-dash-form-element__label-title--is-required")||l.querySelector('legend [class*="fb-dash-form-element__label"]')||l.querySelector("legend span");if((i?.querySelector("span:nth-of-type(1)")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let f=(n||"").toLowerCase();for(let d of a){let u=d.getRootNode(),y=(d.id&&u.querySelector(`label[for="${d.id}"]`)||d.nextElementSibling)?.textContent?.trim()||"";if(d.value.toLowerCase()===f||y.toLowerCase()===f)return d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function pr(e,t,o){return await e.evaluate((r,n)=>{let s=document.querySelectorAll(".fb-dash-form-element");if(!s||s.length===0){let l=document.querySelector("#interop-outlet")?.shadowRoot;l&&(s=l.querySelectorAll(".fb-dash-form-element"))}if(!s||s.length===0)return!1;for(let l of s){let a=l.querySelector("select[data-test-text-entity-list-form-select]");if(!a)continue;let i=l.querySelector(`label[for="${a.id}"]`)||l.querySelector(".fb-dash-form-element__label-title--is-required");if((i?.querySelector("span:nth-of-type(2)")?.textContent.trim()||i?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||i?.querySelector("span")?.textContent.trim()||i?.textContent?.trim())!==r)continue;let f=Array.from(a.options),d=(n||"").toLowerCase(),u=f.find(p=>p.text.toLowerCase()===d)||f.find(p=>p.value.toLowerCase()===d)||f.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 mr(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 l=(n||"").split(",").map(a=>a.trim().toLowerCase()).filter(Boolean);if(l.length===0)return!1;for(let a of s){let i=a.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]');if(i.length===0||a.querySelector("legend span")?.textContent?.trim()!==r)continue;let f=!1;for(let d of i){let u=(d.nextElementSibling?.textContent||d.value||"").trim().toLowerCase();l.includes(u)&&!d.checked&&(d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),f=!0)}return f}return!1},t,o)}async function yr(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 yt(o.labelText,"");else if(o.type==="radio")r=await Be(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await xe(o.labelText,o.options||[]);else continue}catch(l){console.log(` \u26A0 Lifebot failed for optional "${o.labelText}": ${l.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 Vt(e,o.labelText,r):o.type==="radio"?n=await fr(e,o.labelText,r):o.type==="select"?n=await pr(e,o.labelText,r):o.type==="checkbox"&&(n=await mr(e,o.labelText,r))}catch(l){console.log(` \u26A0 setter failed for "${o.labelText}": ${l.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 Wo(e,t){let o=[],r=!0,n=0,s=null,l=0;for(;r;){if(n++,await dt(e))return console.log(" Daily limit reached during form navigation"),await Xo(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let c=(await dr(e)).filter(p=>!o.some(y=>y.labelText===p.labelText));o.push(...c);try{let p=o.find(m=>m.labelText==="City"||m.labelText==="Location (city)"),y=o.filter(m=>m.labelText!=null).find(m=>m.labelText!==null&&m.labelText.trim()!==null&&(m.labelText.trim().toLowerCase()==="cv"||m.labelText.trim().toLowerCase()==="curriculum vitae"||m.labelText.trim().toLowerCase()==="cover letter"||m.labelText.trim().toLowerCase()==="cover"));if(p&&!p.answer){let m=process.env.City;await Vt(e,p.labelText,m),p.answer=m}else if(y){let m=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!y.answer||y.answer!==m)&&(await h(1e4),await Vt(e,y.labelText,m),y.answer=m,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await yr(e,c)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let f=null;try{f=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(f!==null){if(f.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:f};let p=f&&o.find(m=>m.errorMsgText&&m.labelText===f.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(f,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:f};let y=o.findIndex(m=>m.labelText===f.labelText&&!m.answer);y!==-1&&o.splice(y,1),o.push(f)}let d=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let y of p){let m=y.querySelectorAll("button");for(let g of m){let b=g.innerText?.trim();if(b==="Continue applying"||b==="Got it"||b==="Dismiss")return g.click(),b}}return null});d&&console.log(` Dismissed safety popup (${d})`);let u=await e.evaluate(async()=>{function p(w){let x=document.querySelector(w);if(x)return x;let j=document.querySelector("#interop-outlet")?.shadowRoot;return j?j.querySelector(w):null}function y(w){let x=document.querySelectorAll(w),j=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...x||[],...j||[]]}let m=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||y("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),g=y('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||y("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),b=p('button[aria-label="Submit application"]'),v=async()=>{let w=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||y("footer button, button.artdeco-button--primary").find(x=>x.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},k=()=>{let w=y("button").find(x=>x.innerText?.trim()==="Review");w&&w.click()};return m?(await v(),{type:"next"}):g?(await k(),{type:"review"}):b?{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 y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of y){let g=m.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let b of g){let v=b.innerText||"";if(v.includes("application was sent")||v.includes("resume into a profile")||v.includes("Application submitted")||v.includes("Next best action"))for(let k of b.querySelectorAll("button")){let w=k.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return k.click(),w}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await h(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(l===0){let y=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),g=[],b=[];for(let v of m){for(let w of v.querySelectorAll("button")){let x=w.innerText?.trim();x&&x.length<60&&g.push(x)}let k=v.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');k&&b.push(k.innerText?.slice(0,200))}return{buttons:g.slice(0,15),modalText:b.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(y.buttons)}`),y.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(y.modalText)}`)}}if(u.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(f===null&&u.type===s?l++:l=0,s=u.type,l>=5){let p=await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),m=[],g=[];for(let b of y){for(let v of b.querySelectorAll(".artdeco-inline-feedback__message"))m.push(v.textContent?.trim()?.slice(0,60));for(let v of b.querySelectorAll(".fb-dash-form-element")){let k=v.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=v.querySelector("input, select, textarea"),x=!!v.querySelector(".artdeco-inline-feedback__message");k&&(x||w&&!w.value)&&g.push({label:k.slice(0,40),hasError:x,value:w?.value?.slice(0,20)||""})}}return{errors:m,emptyRequired:g.slice(0,5)}});return console.error(` \u26A0 Stuck on "${u.type}" for ${l} 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 h(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function Yo(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 br(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 hr(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 l=s.innerText||"";if(l.includes("application was sent")||l.includes("Application sent")||l.includes("resume into a profile")||l.includes("Next best action"))for(let a of s.querySelectorAll("button")){let i=a.innerText?.trim();if(i==="Not now"||i==="Dismiss")return a.click(),i}}}return null});t?(console.log(` Post-apply popup closed (${t})`),await h(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function ct(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 h(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 Gt(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 h(500))}catch{console.log("No discard confirmation needed")}}async function Zo(e,t){let o=[],r=t._fromQueue;try{S.attempted++,console.log(`
26
+ --- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&Lt(n)?.status==="applied")return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (our DB): ${t.jobTitle} \u2014 skipping`),{keepGoing:!0};let s=null;if(!r){let u=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(),y=u.split(" ")[0],m=p.split(" ")[0];if(y&&m&&!u.includes(m)&&!p.includes(y))return S.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${u}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let b=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!b)return!1;let v=b.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(v)||v.includes("Application submitted")}))return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&ae(n,"applied",{source:"detected"}),{keepGoing:!0};try{s=await ho(e)}catch{}}let l=await Ho(e);if(l.dailyLimitReached){console.log(`
27
27
  ========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
28
- `);let u=de("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${u.total}`),console.log(` - This session: ${dt}`),console.log(` - Unprocessed: ${u.unprocessed}`),S.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:u}}if(!l.clicked)return S.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await Yo(e);let a=await Qn();console.log(`Applying for job: ${t.id}`);let s=`### Job Information
28
+ `);let u=de("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${u.total}`),console.log(` - This session: ${ft}`),console.log(` - Unprocessed: ${u.unprocessed}`),S.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:u}}if(!l.clicked)return S.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await Yo(e);let a=await Qn();console.log(`Applying for job: ${t.id}`);let i=`### Job Information
29
29
  - **Counter:** ${a}
30
30
  - **Job Title:** ${t.jobTitle}
31
31
  - **Company:** ${t.companyName}
32
32
  - **Location:** ${t.location}
33
33
  - **Salary:** ${t.salary}
34
- - **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await te.addMessage(c,s,{lifebot:Oo.off});let p=await ue("Should I apply for this job? Answer only 'yes' or 'no'!!");if(Uo(),console.log(`Should I apply for ${t.jobTitle} ?? `+p),p.toLowerCase()==="no"){S.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await at(e),await Jt(e),await Jo(e,t.id);let u=t.id?.match(/\d+/)?.[0];return be({jobId:u,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),ae(u,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let f=await Wo(e,Ho);if(f.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await Go(e)).clicked?f=await Wo(e,Ho):(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 at(e),{keepGoing:!1,dailyLimitReached:!0};if(f.skip){if(await at(e),await Jt(e),f.duplicateField){await Jo(e,t.id);let u=process.env.NODE_EASY_APPLY_ERRORS;await te.addMessage(u,`${t.href} failed at label ${f.duplicateField?.labelText}`,{lifebot:Oo.off})}S.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${f.duplicateField?.labelText||"form error"}`),be({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{n=f.filledFields,n.length,await Yo(e),await pr(e),await b(2e3),await fr(e),S.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${f.formPages} pages, ${n.length} fields)`);let u=t.id?.match(/\d+/)?.[0];if(u&&(Ye(u,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),jt(u,{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}),ae(u,"applied",{source:"easy-apply"}),i?.companyUrl&&ot(i.companyUrl,{name:i.companyName||t.companyName,about:i.aboutCompany,size:i.companySize,industries:i.industries,jobId:u})),await rr(e,t),be({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:f.formPages,questions:n}),!Xn())return{keepGoing:!1}}}catch(o){if(ge(o))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(o.message||"").slice(0,100)}`),o;console.log(o);let i=Ko(o);if(!i)return console.log(`\u274C Unknown error \u2014 stopping: ${(o.message||"").slice(0,120)}`),{keepGoing:!1};if(i.severity==="fatal")return console.log(`\u274C [${i.label}] Fatal \u2014 stopping: ${(o.message||"").slice(0,120)}`),i.instructions&&console.log(` \u2192 ${i.instructions}`),i.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":i.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin"),{keepGoing:!1};let l=Kn(i.label);if(console.log(`\u26A0 [${i.label}] on "${t.jobTitle}" (${l}/${i.maxConsecutive} consecutive): ${(o.message||"").slice(0,120)}`),i.cleanup==="popup"){try{await at(e)}catch{}try{await Jt(e)}catch{}}return l>=i.maxConsecutive?(console.log(`\u274C [${i.label}] ${i.maxConsecutive} consecutive \u2014 stopping.`),{keepGoing:!1}):(i.cooldownMs&&await b(i.cooldownMs),{keepGoing:!0})}return Uo(),{keepGoing:!0}}async function mr(e,t,n){let r=process.env.LINKEDIN_SEARCH_URL,o=[],i=0;for(;;){await Gt(e,r)&&(await B(e),await b(2e3)),await n(e);let a=await er(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 Gt(e,r);continue}break}if(i=0,o.length===0){o=a;let{keepGoing:s}=await Bo(e,a,t);if(!s)return{keepGoing:!1,jobsDone:o}}else{let s=a.filter(p=>!o.some(f=>f.id===p.id));if(console.log(` New jobs on page: ${s.length} (page: ${a.length}, total seen: ${o.length})`),s.length===0)break;let{keepGoing:c}=await Bo(e,s,t);if(o=[...o,...s],!c)return{keepGoing:!1,jobsDone:o}}}return console.log(` All jobs processed. Total: ${o.length}`),{keepGoing:!0,jobsDone:o}}var S={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(s=>s.startsWith("--job-urls=")),t=Do("apply",e?"queue":"search"),n=null,r=null,o=[],i=async()=>Hn.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),l=async s=>{await s.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>Nt();try{n=await i();let s=async()=>{console.log(`
35
- Closing browser...`);try{await n.close()}catch{}process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);let c=await n.newPage();await l(c);let p=Nt();await c.setCookie(...p);let f=process.argv.find(C=>C.startsWith("--job-urls=")),u=f?f.split("=").slice(1).join("=").replace(/^@/,""):null,d=process.env.LINKEDIN_SEARCH_URL,m=u?"https://www.linkedin.com/feed/":d;try{await c.goto(m,{waitUntil:"domcontentloaded",timeout:6e4})}catch(C){console.error("\u274C Navigation error:",C.message),console.log("Trying to continue anyway..."),await b(5e3)}let y=c.url();if(y.includes("/login")||y.includes("/checkpoint"))throw new Error("Not logged in \u2014 cookies expired, run: npm run login");console.log("\u2713 \u0417\u0430\u043B\u043E\u0433\u0438\u043D\u0435\u043D\u044B \u043D\u0430 LinkedIn!");let g=de("recruiters-from-jobs");g.total>0&&console.log(`
34
+ - **Job URL:** ${t.href}`,c=process.env.NODE_EASY_APPLY_MAIN;await te.addMessage(c,i,{lifebot:Uo.off});let f=await ue("Should I apply for this job? Answer only 'yes' or 'no'!!");if(Bo(),console.log(`Should I apply for ${t.jobTitle} ?? `+f),f.toLowerCase()==="no"){S.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await ct(e),await Gt(e),await Go(e,t.id);let u=t.id?.match(/\d+/)?.[0];return he({jobId:u,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),ae(u,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let d=await Wo(e,Vo);if(d.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await Ho(e)).clicked?d=await Wo(e,Vo):(console.log(" pressApplyButton failed on retry"),d={filledFields:[],formPages:0,skip:!0,duplicateField:{labelText:"stale_popup_retry_failed"}})),console.log(`processNavigation: pages=${d.formPages}, fields=${d.filledFields?.length||0}, skip=${d.skip}${d.dailyLimitReached?", DAILY LIMIT":""}`),d.dailyLimitReached)return console.log(" Daily limit reached \u2014 stopping"),await ct(e),{keepGoing:!1,dailyLimitReached:!0};if(d.skip){if(await ct(e),await Gt(e),d.duplicateField){await Go(e,t.id);let u=process.env.NODE_EASY_APPLY_ERRORS;await te.addMessage(u,`${t.href} failed at label ${d.duplicateField?.labelText}`,{lifebot:Uo.off})}S.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${d.duplicateField?.labelText||"form error"}`),he({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"failed",formPages:d.formPages,failedField:d.duplicateField?.labelText||null,questions:d.filledFields||[]})}else{o=d.filledFields,o.length,await Yo(e),await br(e),await h(2e3),await hr(e),S.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${d.formPages} pages, ${o.length} fields)`);let u=t.id?.match(/\d+/)?.[0];if(u&&(Qe(u,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),jt(u,{title:t.jobTitle,company:s?.companyName||t.companyName,companyUrl:s?.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:s?.description,techStack:s?.techStack,jobTags:s?.jobTags,seniority:s?.seniority,employmentType:s?.employmentType,industries:s?.industries,jobFunction:s?.jobFunction,postedTime:s?.postedTime,applicantCount:s?.applicantCount,companySize:s?.companySize,workplaceType:s?.workplaceType,contractType:s?.contractType,aboutCompany:s?.aboutCompany}),ae(u,"applied",{source:"easy-apply"}),s?.companyUrl&&nt(s.companyUrl,{name:s.companyName||t.companyName,about:s.aboutCompany,size:s.companySize,industries:s.industries,jobId:u})),await rr(e,t),he({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:d.formPages,questions:o}),!Xn())return{keepGoing:!1}}}catch(n){if(ge(n))throw console.log(`\u26A0 CDP dead during "${t.jobTitle}" \u2014 bubbling up for page recovery: ${(n.message||"").slice(0,100)}`),n;console.log(n);let s=Ko(n);if(!s)return console.log(`\u274C Unknown error \u2014 stopping: ${(n.message||"").slice(0,120)}`),{keepGoing:!1};if(s.severity==="fatal")return console.log(`\u274C [${s.label}] Fatal \u2014 stopping: ${(n.message||"").slice(0,120)}`),s.instructions&&console.log(` \u2192 ${s.instructions}`),s.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":s.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin"),{keepGoing:!1};let l=Kn(s.label);if(console.log(`\u26A0 [${s.label}] on "${t.jobTitle}" (${l}/${s.maxConsecutive} consecutive): ${(n.message||"").slice(0,120)}`),s.cleanup==="popup"){try{await ct(e)}catch{}try{await Gt(e)}catch{}}return l>=s.maxConsecutive?(console.log(`\u274C [${s.label}] ${s.maxConsecutive} consecutive \u2014 stopping.`),{keepGoing:!1}):(s.cooldownMs&&await h(s.cooldownMs),{keepGoing:!0})}return Bo(),{keepGoing:!0}}async function gr(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],s=0;for(;;){await Ht(e,r)&&(await B(e),await h(2e3)),await o(e);let a=await er(e);if(a.length===0){if(!e.url().includes("/jobs/")){if(s++,s>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 ${s}/3...`),await Ht(e,r);continue}break}if(s=0,n.length===0){n=a;let{keepGoing:i}=await Jo(e,a,t);if(!i)return{keepGoing:!1,jobsDone:n}}else{let i=a.filter(f=>!n.some(d=>d.id===f.id));if(console.log(` New jobs on page: ${i.length} (page: ${a.length}, total seen: ${n.length})`),i.length===0)break;let{keepGoing:c}=await Jo(e,i,t);if(n=[...n,...i],!c)return{keepGoing:!1,jobsDone:n}}}return console.log(` All jobs processed. Total: ${n.length}`),{keepGoing:!0,jobsDone:n}}var S={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(i=>i.startsWith("--job-urls=")),t=Lo("apply",e?"queue":"search"),o=null,r=null,n=[],s=async()=>Hn.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),l=async i=>{await i.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>Ot();try{o=await s();let i=async()=>{console.log(`
35
+ Closing browser...`);try{await o.close()}catch{}process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i);let c=await o.newPage();await l(c);let f=Ot();await c.setCookie(...f);let d=process.argv.find(C=>C.startsWith("--job-urls=")),u=d?d.split("=").slice(1).join("=").replace(/^@/,""):null,p=process.env.LINKEDIN_SEARCH_URL,y=u?"https://www.linkedin.com/feed/":p;try{await c.goto(y,{waitUntil:"domcontentloaded",timeout:6e4})}catch(C){console.error("\u274C Navigation error:",C.message),console.log("Trying to continue anyway..."),await h(5e3)}let m=c.url();if(m.includes("/login")||m.includes("/checkpoint"))throw new Error("Not logged in \u2014 cookies expired, run: npm run login");console.log("\u2713 \u0417\u0430\u043B\u043E\u0433\u0438\u043D\u0435\u043D\u044B \u043D\u0430 LinkedIn!");let g=de("recruiters-from-jobs");g.total>0&&console.log(`
36
36
  \u{1F4C2} Existing recruiters for today: ${g.total} (${g.unprocessed} unprocessed)
37
- `),await b(2e3);let h={page:c,browser:n,recoveryCtx:{searchUrl:d,launchFn:i,setupPage:l,cookiesProvider:a}},v=!1;if(u)try{let C=JSON.parse(Qo.readFileSync(u,"utf-8"));console.log(`
37
+ `),await h(2e3);let b={page:c,browser:o,recoveryCtx:{searchUrl:p,launchFn:s,setupPage:l,cookiesProvider:a}},v=!1;if(u)try{let C=JSON.parse(Qo.readFileSync(u,"utf-8"));console.log(`
38
38
  \u{1F4CB} Queue mode: ${C.length} jobs from ${u}
39
- `);for(let D=0;D<C.length;D++){let _=typeof C[D]=="string"?{url:C[D]}:C[D],A=_.url,$=_.title||"Unknown",ve=_.company||"";console.log(`
40
- [${D+1}/${C.length}] ${$} @ ${ve}`),console.log(` ${A}`),c=h.page,n=h.browser;try{let W=A.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await c.goto(A,{waitUntil:"domcontentloaded",timeout:6e4}),await b(8e3);let R=await c.evaluate(()=>{let ke=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:ke.includes("Application submitted"),noLongerAccepting:ke.includes("No longer accepting applications")}});if(R.alreadyApplied){console.log(" Already applied \u2014 skipping"),S.alreadyApplied++,ae(W,"applied",{applyMethod:"detected"});continue}if(R.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),S.expired++,ae(W,"expired",{reason:"no_longer_accepting"});continue}if(!R.hasApply){console.log(" No Easy Apply button \u2014 skipping"),S.noApplyButton++;continue}let Y={id:`/jobs/view/${W}/`,href:A,jobTitle:$,companyName:ve,location:_.location||"",salary:_.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let ee=await Zo(c,Y);if(console.log(` Result: keepGoing=${ee.keepGoing}, reason=${ee.dailyLimitReached?"daily_limit":"ok"}`),!ee.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),v=!0;break}}catch(W){if(ge(W))try{await ct(h,`queue job ${D+1}: ${W.message?.slice(0,80)}`),c=h.page,n=h.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=Ko(W);if(R?.severity==="fatal"){console.error(`\u274C [${R.label}] Fatal \u2014 stopping queue: ${(W.message||"").slice(0,120)}`),R.instructions&&console.error(` \u2192 ${R.instructions}`),R.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":R.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin");break}console.error(` Error: ${W.message?.slice(0,80)}`)}}}console.log(`
39
+ `);for(let I=0;I<C.length;I++){let _=typeof C[I]=="string"?{url:C[I]}:C[I],A=_.url,$=_.title||"Unknown",ve=_.company||"";console.log(`
40
+ [${I+1}/${C.length}] ${$} @ ${ve}`),console.log(` ${A}`),c=b.page,o=b.browser;try{let W=A.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await c.goto(A,{waitUntil:"domcontentloaded",timeout:6e4}),await h(8e3);let R=await c.evaluate(()=>{let ke=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:ke.includes("Application submitted"),noLongerAccepting:ke.includes("No longer accepting applications")}});if(R.alreadyApplied){console.log(" Already applied \u2014 skipping"),S.alreadyApplied++,ae(W,"applied",{applyMethod:"detected"});continue}if(R.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),S.expired++,ae(W,"expired",{reason:"no_longer_accepting"});continue}if(!R.hasApply){console.log(" No Easy Apply button \u2014 skipping"),S.noApplyButton++;continue}let Y={id:`/jobs/view/${W}/`,href:A,jobTitle:$,companyName:ve,location:_.location||"",salary:_.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let ee=await Zo(c,Y);if(console.log(` Result: keepGoing=${ee.keepGoing}, reason=${ee.dailyLimitReached?"daily_limit":"ok"}`),!ee.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),v=!0;break}}catch(W){if(ge(W))try{await ut(b,`queue job ${I+1}: ${W.message?.slice(0,80)}`),c=b.page,o=b.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=Ko(W);if(R?.severity==="fatal"){console.error(`\u274C [${R.label}] Fatal \u2014 stopping queue: ${(W.message||"").slice(0,120)}`),R.instructions&&console.error(` \u2192 ${R.instructions}`),R.label==="ilml-auth-expired"?S.fatalAuthExpired="ilml":R.label==="linkedin-session-expired"&&(S.fatalAuthExpired="linkedin");break}console.error(` Error: ${W.message?.slice(0,80)}`)}}}console.log(`
41
41
  Queue complete. ${v?"Daily limit hit.":"Continuing to search..."}`)}catch(C){console.error(`Failed to read job URLs file: ${C.message}`)}if(!v){if(u){console.log(`
42
- Queue done. Continuing with standard search...`);try{await c.goto(d,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3)}catch(C){console.error(" Navigation to search failed:",C.message)}}h.page=c,h.browser=n;try{await nr(h)}catch(C){ge(C)||/CDP unrecoverable/.test(C.message||"")?(console.error(`
42
+ Queue done. Continuing with standard search...`);try{await c.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await h(3e3)}catch(C){console.error(" Navigation to search failed:",C.message)}}b.page=c,b.browser=o;try{await nr(b)}catch(C){ge(C)||/CDP unrecoverable/.test(C.message||"")?(console.error(`
43
43
  \u274C Apply phase ended: CDP channel could not be recovered after ${S.cdpRecoveries} page recoveries and ${S.browserRestarts} browser restarts.`),console.error(` Last error: ${C.message}`)):/Session expired/i.test(C.message||"")?(console.error(`
44
44
  \u274C Apply phase ended: ${C.message}`),r=C):console.error(`
45
- \u26A0 Apply phase crashed: ${C.message}`)}c=h.page,n=h.browser}let k=S.submitted+S.skippedByLifebot+S.failed+S.mismatch+S.alreadyApplied+S.expired+S.noApplyButton,w=S.attempted-k,x=de("recruiters-from-jobs");o.push(`Jobs attempted: ${S.attempted}`),o.push(`Successfully applied: ${S.submitted}`),o.push(`Skipped by Lifebot: ${S.skippedByLifebot}`),o.push(`Failed (form errors): ${S.failed}`),S.mismatch>0&&o.push(`Mismatch (wrong panel): ${S.mismatch}`),S.alreadyApplied>0&&o.push(`Already applied: ${S.alreadyApplied}`),S.expired>0&&o.push(`Expired (closed): ${S.expired}`),S.noApplyButton>0&&o.push(`No Apply button: ${S.noApplyButton}`),w>0&&o.push(`Unaccounted: ${w}`),o.push(`Daily limit reached: ${S.dailyLimitHit?"Yes":"No"}`),S.cdpRecoveries>0&&o.push(`Page recoveries (CDP): ${S.cdpRecoveries}`),S.browserRestarts>0&&o.push(`Browser restarts: ${S.browserRestarts}`),o.push(`Recruiters found: ${dt}`),o.push(`Recruiters total: ${x.total} (${x.unprocessed} unprocessed)`),console.log(`
46
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 C of o)console.log(` ${C}`);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=!!n&&n.isConnected?.()!==!1?S.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":S.fatalAuthExpired==="ilml"?"iLiveMyLife token expired (run: ilml login)":null:"browser is not in a usable state",V=!L;V||(console.log(`
47
- \u26A0 Skipping recruiter funnel \u2014 ${L}.`),console.log(` ${x.unprocessed} recruiters saved for next run.`),o.push(`Funnel: skipped (${L})`));let{markProfileProcessed:we}=await Promise.resolve().then(()=>(bt(),Kt)),{canSendConnection:U,getQuotaStatus:Se}=await Promise.resolve().then(()=>(je(),$t)),Z=()=>({message:Yn,useCustomMessage:Vn,maxConnections:Wn,excludeLocations:Ot,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(C,D,_)=>{we("recruiters-from-jobs",C.profileUrl,{status:_.reason,connectionSent:_.connectionSent,withCustomMessage:_.withCustomMessage,message:_.messageSent,method:_.method,reason:_.reason,error:_.error,profileInfo:_.profileInfo},C._fromDate||null)}});if(V&&x.unprocessed>0){console.log(`
48
- --- Funnel: today's recruiters (${x.unprocessed}) ---`),Ot.length>0&&console.log(` Excluding locations: ${Ot.join(", ")}`);let C=Je("recruiters-from-jobs");await Et(c,C,Z())}let Oe=U();if(V&&Oe.allowed){let C=Ge("recruiters-from-jobs"),D=new Date().toISOString().split("T")[0],_=C.filter(A=>A._fromDate!==D);if(_.length>0){let A=Se();console.log(`
49
- --- Funnel: backfill from previous days (${_.length} unprocessed) ---`),console.log(` Quota remaining: ${A.daily.remaining} today, ${A.weekly.remaining} this week`),await Et(c,_,{...Z(),maxConnections:A.daily.remaining})}}let P=Se();console.log(`
50
- \u2705 Funnel done. Quota: ${P.daily.remaining}/${P.daily.max} today, ${P.weekly.remaining}/${P.weekly.max} this week`),o.push(`Funnel quota: ${P.daily.remaining}/${P.daily.max} today, ${P.weekly.remaining}/${P.weekly.max} week`),!u&&!process.argv.includes("--no-wait")&&(console.log(`
51
- Press Enter to close browser...`),await new Promise(C=>{process.stdin.once("data",()=>C())}))}catch(s){r=s,console.error(`
52
- \u274C Apply session ended with error: ${s.message}`),s.stack&&console.error(s.stack)}qo(t,r?"error":"success",{summaryLines:o,dailyLimitHit:S.dailyLimitHit,attempted:S.attempted,submitted:S.submitted,failed:S.failed,skippedByLifebot:S.skippedByLifebot},r?r.message:null);try{await n?.close()}catch{}r&&process.exit(1)})();
45
+ \u26A0 Apply phase crashed: ${C.message}`)}c=b.page,o=b.browser}let k=S.submitted+S.skippedByLifebot+S.failed+S.mismatch+S.alreadyApplied+S.expired+S.noApplyButton,w=S.attempted-k,x=de("recruiters-from-jobs");n.push(`Jobs attempted: ${S.attempted}`),n.push(`Successfully applied: ${S.submitted}`),n.push(`Skipped by Lifebot: ${S.skippedByLifebot}`),n.push(`Failed (form errors): ${S.failed}`),S.mismatch>0&&n.push(`Mismatch (wrong panel): ${S.mismatch}`),S.alreadyApplied>0&&n.push(`Already applied: ${S.alreadyApplied}`),S.expired>0&&n.push(`Expired (closed): ${S.expired}`),S.noApplyButton>0&&n.push(`No Apply button: ${S.noApplyButton}`),w>0&&n.push(`Unaccounted: ${w}`),n.push(`Daily limit reached: ${S.dailyLimitHit?"Yes":"No"}`),S.cdpRecoveries>0&&n.push(`Page recoveries (CDP): ${S.cdpRecoveries}`),S.browserRestarts>0&&n.push(`Browser restarts: ${S.browserRestarts}`),n.push(`Recruiters found: ${ft}`),n.push(`Recruiters total: ${x.total} (${x.unprocessed} unprocessed)`),console.log(`
46
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 C of n)console.log(` ${C}`);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 D=!!o&&o.isConnected?.()!==!1?S.fatalAuthExpired==="linkedin"?"LinkedIn session expired (run: ilml linkedin login)":S.fatalAuthExpired==="ilml"?"iLiveMyLife token expired (run: ilml login)":null:"browser is not in a usable state",V=!D;V||(console.log(`
47
+ \u26A0 Skipping recruiter funnel \u2014 ${D}.`),console.log(` ${x.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${D})`));let{markProfileProcessed:we}=await Promise.resolve().then(()=>(gt(),Xt)),{canSendConnection:U,getQuotaStatus:Se}=await Promise.resolve().then(()=>(je(),_t)),Z=()=>({message:Yn,useCustomMessage:Vn,maxConnections:Wn,excludeLocations:Ut,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(C,I,_)=>{we("recruiters-from-jobs",C.profileUrl,{status:_.reason,connectionSent:_.connectionSent,withCustomMessage:_.withCustomMessage,message:_.messageSent,method:_.method,reason:_.reason,error:_.error,profileInfo:_.profileInfo},C._fromDate||null)}});if(V&&x.unprocessed>0){console.log(`
48
+ --- Funnel: today's recruiters (${x.unprocessed}) ---`),Ut.length>0&&console.log(` Excluding locations: ${Ut.join(", ")}`);let C=Ge("recruiters-from-jobs");await At(c,C,Z())}let Ue=U();if(V&&Ue.allowed){let C=He("recruiters-from-jobs"),I=new Date().toISOString().split("T")[0],_=C.filter(A=>A._fromDate!==I);if(_.length>0){let A=Se();console.log(`
49
+ --- Funnel: backfill from previous days (${_.length} unprocessed) ---`),console.log(` Quota remaining: ${A.daily.remaining} today, ${A.weekly.remaining} this week`),await At(c,_,{...Z(),maxConnections:A.daily.remaining})}}let P=Se();console.log(`
50
+ \u2705 Funnel done. Quota: ${P.daily.remaining}/${P.daily.max} today, ${P.weekly.remaining}/${P.weekly.max} this week`),n.push(`Funnel quota: ${P.daily.remaining}/${P.daily.max} today, ${P.weekly.remaining}/${P.weekly.max} week`),!u&&!process.argv.includes("--no-wait")&&(console.log(`
51
+ Press Enter to close browser...`),await new Promise(C=>{process.stdin.once("data",()=>C())}))}catch(i){r=i,console.error(`
52
+ \u274C Apply session ended with error: ${i.message}`),i.stack&&console.error(i.stack)}Do(t,r?"error":"success",{summaryLines:n,dailyLimitHit:S.dailyLimitHit,attempted:S.attempted,submitted:S.submitted,failed:S.failed,skippedByLifebot:S.skippedByLifebot},r?r.message:null);try{await o?.close()}catch{}r&&process.exit(1)})();