ilml-plugin-linkedin 1.12.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/dist/applyQueue.mjs +4 -4
- package/dist/enrichProfile.mjs +242 -19
- package/dist/enrichProfiles.mjs +257 -48
- package/dist/funnelRunner.mjs +256 -47
- package/dist/profileHistory.mjs +4 -4
- package/dist/readPost.mjs +70 -0
- package/dist/run.mjs +260 -51
- package/dist/scout.mjs +7 -7
- package/dist/syncAll.mjs +317 -90
- package/dist/verifyAbout.mjs +219 -10
- package/dist/visit.mjs +256 -47
- package/ilml-plugin.json +185 -28
- package/package.json +1 -1
package/dist/run.mjs
CHANGED
|
@@ -1,88 +1,297 @@
|
|
|
1
|
-
var jn=Object.defineProperty;var Be=(e,t)=>()=>(e&&(t=e(e=0)),t);var _e=(e,t)=>{for(var o in t)jn(e,o,{get:t[o],enumerable:!0})};async function g(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function ao(e){return parseInt(e,10)||0}async function te(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",s=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),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 u=r.querySelectorAll("button");for(let c of u){let f=c.innerText?.trim().toLowerCase()||"",d=c.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return c.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Te=Be(()=>{});var mo={};_e(mo,{default:()=>Mn,getAllUnprocessedProfiles:()=>rt,getSummary:()=>je,getUnprocessedProfiles:()=>nt,listFiles:()=>po,loadProfiles:()=>ot,markProfileProcessed:()=>fo,saveProfile:()=>Ge,saveProfiles:()=>uo});import"dotenv/config";import*as B from"fs";import*as oe from"path";import{fileURLToPath as qn}from"url";function He(){B.existsSync(ue)||B.mkdirSync(ue,{recursive:!0})}function Pn(e,t){try{let o=`${e}-${At()}.json`,r=B.readdirSync(ue).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==o),n=0;for(let s of r)JSON.parse(B.readFileSync(oe.join(ue,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function At(){return new Date().toISOString().split("T")[0]}function _t(e,t=null){let o=t||At();return oe.join(ue,`${e}-${o}.json`)}function ot(e,t=null){He();let o=_t(e,t);try{if(B.existsSync(o)){let r=B.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 Ge(e,t){He();let o=_t(e),r={source:e,date:At(),lastUpdated:new Date().toISOString(),profiles:[]};try{B.existsSync(o)&&(r=JSON.parse(B.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=Pn(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{B.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 uo(e,t){let o=0;for(let r of t)Ge(e,r)&&o++;return o}function nt(e,t=null){return ot(e,t).filter(r=>!r.processed)}function fo(e,t,o,r=null){He();let n=_t(e,r);try{if(!B.existsSync(n))return;let s=JSON.parse(B.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(),B.writeFileSync(n,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function je(e){let t=ot(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 po(){He();try{return B.readdirSync(ue).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(B.readFileSync(oe.join(ue,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 rt(e){He();let t=[];try{let n=B.readdirSync(ue).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of n)try{let l=JSON.parse(B.readFileSync(oe.join(ue,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 On,Fn,ue,Mn,Tt=Be(()=>{On=qn(import.meta.url),Fn=oe.dirname(oe.dirname(On)),ue=process.env.DATA_DIR?oe.resolve(process.env.DATA_DIR,"collected-profiles"):oe.join(Fn,"collected-profiles");Mn={loadProfiles:ot,saveProfile:Ge,saveProfiles:uo,getUnprocessedProfiles:nt,getAllUnprocessedProfiles:rt,markProfileProcessed:fo,getSummary:je,listFiles:po}});import{getPluginConfig as Un}from"@ilivemylife/graph-sdk";var Bn,Ms,Se,Us,Bs,ho=Be(async()=>{Bn=await Un();for(let[e,t]of Object.entries(Bn))process.env[e]===void 0&&(process.env[e]=t);Ms=process.env.LINKEDIN_NAME,Se=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Us=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.NEEDS_REVIEW])),Bs=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.REJECTED,Se.NEEDS_REVIEW]))});var jo={};_e(jo,{addEncounter:()=>Fe,canSendConnection:()=>yt,commitDataSnapshot:()=>Ro,default:()=>er,getAllApplications:()=>To,getPersonStatus:()=>dt,getQuestionStats:()=>Io,getQuotaStatus:()=>Ye,getRecentConnections:()=>ht,linkPersonToJob:()=>ut,loadApplicationQuestions:()=>Ot,loadConversations:()=>xo,loadJobs:()=>lt,loadPeople:()=>X,loadProfileHistory:()=>vo,loadQuota:()=>pt,loadSyncState:()=>Co,logApplicationQuestions:()=>Pe,migrateFromDailyFiles:()=>Eo,profileSlug:()=>it,recordConnectionSent:()=>mt,resetCaches:()=>Nt,saveConversations:()=>$o,saveJobs:()=>at,savePeople:()=>xe,saveQuota:()=>qt,saveSyncState:()=>Ao,updateConnectionStatus:()=>ft,upsertJob:()=>ct,upsertPerson:()=>me});import"dotenv/config";import*as F from"fs";import*as J from"path";import{fileURLToPath as Jn}from"url";import{execSync as It}from"child_process";function Nt(){Le=null,De=null,de=null,ve=null,Ne=null,ke=null}function Z(){F.existsSync(Y)||F.mkdirSync(Y,{recursive:!0})}function he(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";F.writeFileSync(r,o);for(let n=0;n<3;n++)try{F.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 qe(e,t){if(!F.existsSync(e))return null;try{let o=JSON.parse(F.readFileSync(e,"utf-8"));try{F.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${J.resolve(e)}`);let r=e+".backup";if(F.existsSync(r))try{let n=JSON.parse(F.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{F.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{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function Oe(){return new Date().toISOString().split("T")[0]}function it(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Wn(){F.existsSync(Dt)||F.mkdirSync(Dt,{recursive:!0})}function ko(e){let t=it(e);return t?J.join(Dt,`${t}.json`):null}function vo(e){let t=ko(e);return t?qe(t,`profile-history/${it(e)}.json`)||[]:[]}function Yn(e,t){let o=ko(e);if(!o)return;Wn();let r=vo(e);r.unshift(t);try{he(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${it(e)}: ${n.message}`)}}function yo(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function go(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Qn(e,t){if(!e)return[];let o=[];for(let r of Vn){let n=e[r],s=t[r];yo(n)||yo(s)||go(n)!==go(s)&&o.push(r)}return o}function zn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function X(){return Le||(Z(),Le=qe(Rt,"people.json")||{},Le)}function xe(e){Z(),Le=e;try{he(Rt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${J.resolve(Rt)}`)}}function lt(){return De||(Z(),De=qe(jt,"jobs.json")||{},De)}function at(e){Z(),De=e;try{he(jt,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${J.resolve(jt)}`)}}function xo(){return ve||(Z(),ve=qe(st,"conversations.json")||{},Kn(ve),ve)}function Kn(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(s=>s.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{he(st,e)}catch{}}}function $o(e){Z(),ve=e;try{he(st,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${J.resolve(st)}`)}}function me(e,t={}){if(!e)return null;let o=X(),r=Oe(),n=new Date().toISOString(),s=o[e];if(s){let l=Qn(s,t);l.length>0&&(Yn(e,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:l,snapshot:zn(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let a of So)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(s[a])&&s[a].length>0)continue;s[a]=t[a]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return xe(o),o[e]}function ct(e,t={}){if(!e)return null;let o=lt(),r=Oe(),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 at(o),o[e]}function ut(e,t){if(!e||!t)return;let o=X(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),xe(o)))}function Fe(e,t){if(!e||!t)return;let o=X(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:Oe(),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(),xe(o))}function dt(e){return e&&X()[e]?.connectionStatus||null}function ft(e,t,o={}){if(!e)return;o.profileInfo?me(e,o.profileInfo):X()[e]||me(e,{});let r=X(),n=r[e];n&&(n.connectionStatus=t,n.connectionDate=Oe(),n.connectionMethod=o.method||n.connectionMethod,n.messageSent=o.messageSent||n.messageSent,n.lastUpdated=new Date().toISOString(),xe(r))}function pt(){return de||(Z(),de=qe(bo,"quota.json"),(!de||!de.connections)&&(de={connections:[]}),de)}function qt(e){Z(),de=e;try{he(bo,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function mt(e,t="unknown"){let o=pt(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),qt(o)}function ht(){let e=pt(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function yt(){let e=ht(),t=Oe(),o=e.filter(i=>i.date===t).length,r=e.length,n=o>=Ve,s=r>=We,l=!n&&!s,a={allowed:l,daily:{sent:o,max:Ve},weekly:{sent:r,max:We}};return l||(a.reason=n?`Daily limit reached (${o}/${Ve})`:`Weekly limit reached (${r}/${We})`),a}function Ye(){let e=ht(),t=Oe(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:Ve,remaining:Ve-o},weekly:{sent:r,max:We,remaining:We-r}}}function Xn(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function Eo(){Z();let e=F.readdirSync(Y).filter(s=>s.endsWith(".json")&&s!=="people.json"&&s!=="jobs.json"&&s!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
1
|
+
var Gn=Object.defineProperty;var Je=(e,t)=>()=>(e&&(t=e(e=0)),t);var _e=(e,t)=>{for(var o in t)Gn(e,o,{get:t[o],enumerable:!0})};async function g(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}function wo(e){return parseInt(e,10)||0}async function te(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let n=r.innerText||"",s=n.includes("Premium")||n.includes("premium")||n.includes("Upgrade")||n.includes("upgrade"),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 u=r.querySelectorAll("button");for(let c of u){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:n.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Te=Je(()=>{});var $o={};_e($o,{default:()=>er,getAllUnprocessedProfiles:()=>at,getSummary:()=>De,getUnprocessedProfiles:()=>lt,listFiles:()=>xo,loadProfiles:()=>it,markProfileProcessed:()=>vo,saveProfile:()=>Ge,saveProfiles:()=>ko});import"dotenv/config";import*as J from"fs";import*as oe from"path";import{fileURLToPath as Qn}from"url";function He(){J.existsSync(ue)||J.mkdirSync(ue,{recursive:!0})}function Zn(e,t){try{let o=`${e}-${Dt()}.json`,r=J.readdirSync(ue).filter(s=>s.startsWith(e)&&s.endsWith(".json")&&s!==o),n=0;for(let s of r)JSON.parse(J.readFileSync(oe.join(ue,s),"utf-8")).profiles?.some(a=>a.profileUrl===t)&&n++;return n}catch{return 0}}function Dt(){return new Date().toISOString().split("T")[0]}function Lt(e,t=null){let o=t||Dt();return oe.join(ue,`${e}-${o}.json`)}function it(e,t=null){He();let o=Lt(e,t);try{if(J.existsSync(o)){let r=J.readFileSync(o,"utf-8"),n=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${n.profiles.length} profiles from ${o}`),n.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function Ge(e,t){He();let o=Lt(e),r={source:e,date:Dt(),lastUpdated:new Date().toISOString(),profiles:[]};try{J.existsSync(o)&&(r=JSON.parse(J.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=Zn(e,t.profileUrl);r.profiles.push({...t,collectedAt:new Date().toISOString(),seenBefore:s}),r.lastUpdated=new Date().toISOString();try{J.writeFileSync(o,JSON.stringify(r,null,2));let 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 ko(e,t){let o=0;for(let r of t)Ge(e,r)&&o++;return o}function lt(e,t=null){return it(e,t).filter(r=>!r.processed)}function vo(e,t,o,r=null){He();let n=Lt(e,r);try{if(!J.existsSync(n))return;let s=JSON.parse(J.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(),J.writeFileSync(n,JSON.stringify(s,null,2))}}catch(s){console.error("Error marking profile processed:",s.message)}}function De(e){let t=it(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 xo(){He();try{return J.readdirSync(ue).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let n=JSON.parse(J.readFileSync(oe.join(ue,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 at(e){He();let t=[];try{let n=J.readdirSync(ue).filter(s=>s.startsWith(e+"-")&&s.endsWith(".json")).sort().reverse();for(let s of n)try{let l=JSON.parse(J.readFileSync(oe.join(ue,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 zn,Xn,ue,er,jt=Je(()=>{zn=Qn(import.meta.url),Xn=oe.dirname(oe.dirname(zn)),ue=process.env.DATA_DIR?oe.resolve(process.env.DATA_DIR,"collected-profiles"):oe.join(Xn,"collected-profiles");er={loadProfiles:it,saveProfile:Ge,saveProfiles:ko,getUnprocessedProfiles:lt,getAllUnprocessedProfiles:at,markProfileProcessed:vo,getSummary:De,listFiles:xo}});import{getPluginConfig as tr}from"@ilivemylife/graph-sdk";var or,si,Se,ii,li,Eo=Je(async()=>{or=await tr();for(let[e,t]of Object.entries(or))process.env[e]===void 0&&(process.env[e]=t);si=process.env.LINKEDIN_NAME,Se=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ii=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.NEEDS_REVIEW])),li=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.REJECTED,Se.NEEDS_REVIEW]))});var Bo={};_e(Bo,{addEncounter:()=>Pe,canSendConnection:()=>St,commitDataSnapshot:()=>Uo,default:()=>mr,getAllApplications:()=>Oo,getPersonStatus:()=>ht,getQuestionStats:()=>Mo,getQuotaStatus:()=>Ke,getRecentConnections:()=>wt,linkPersonToJob:()=>mt,loadApplicationQuestions:()=>Bt,loadConversations:()=>Lo,loadJobs:()=>dt,loadPeople:()=>X,loadProfileHistory:()=>Do,loadQuota:()=>gt,loadSyncState:()=>Fo,logApplicationQuestions:()=>Oe,migrateFromDailyFiles:()=>No,profileSlug:()=>ut,recordConnectionSent:()=>bt,resetCaches:()=>Mt,saveConversations:()=>jo,saveJobs:()=>ft,savePeople:()=>xe,saveQuota:()=>Ut,saveSyncState:()=>qo,updateConnectionStatus:()=>yt,upsertJob:()=>pt,upsertPerson:()=>he});import"dotenv/config";import*as O from"fs";import*as V from"path";import{fileURLToPath as nr}from"url";import{execSync as Nt}from"child_process";function Mt(){Le=null,je=null,de=null,ve=null,Ne=null,ke=null}function Z(){O.existsSync(K)||O.mkdirSync(K,{recursive:!0})}function ye(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";O.writeFileSync(r,o);for(let n=0;n<3;n++)try{O.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 Fe(e,t){if(!O.existsSync(e))return null;try{let o=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${V.resolve(e)}`);let r=e+".backup";if(O.existsSync(r))try{let n=JSON.parse(O.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{O.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{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function qe(){return new Date().toISOString().split("T")[0]}function ut(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function lr(){O.existsSync(Ot)||O.mkdirSync(Ot,{recursive:!0})}function Ro(e){let t=ut(e);return t?V.join(Ot,`${t}.json`):null}function Do(e){let t=Ro(e);return t?Fe(t,`profile-history/${ut(e)}.json`)||[]:[]}function ar(e,t){let o=Ro(e);if(!o)return;lr();let r=Do(e);r.unshift(t);try{ye(o,r)}catch(n){console.error(`[!] Failed to append profile-history for ${ut(e)}: ${n.message}`)}}function Co(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ao(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function cr(e,t){if(!e)return[];let o=[];for(let r of ir){let n=e[r],s=t[r];Co(n)||Co(s)||Ao(n)!==Ao(s)&&o.push(r)}return o}function ur(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[r,n]of Object.entries(e))t.has(r)||(o[r]=n);return o}function X(){return Le||(Z(),Le=Fe(Ft,"people.json")||{},Le)}function xe(e){Z(),Le=e;try{ye(Ft,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${V.resolve(Ft)}`)}}function dt(){return je||(Z(),je=Fe(qt,"jobs.json")||{},je)}function ft(e){Z(),je=e;try{ye(qt,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${V.resolve(qt)}`)}}function Lo(){return ve||(Z(),ve=Fe(ct,"conversations.json")||{},dr(ve),ve)}function dr(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{ye(ct,e)}catch{}}}function jo(e){Z(),ve=e;try{ye(ct,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${V.resolve(ct)}`)}}function he(e,t={}){if(!e)return null;let o=X(),r=qe(),n=new Date().toISOString(),s=o[e];if(s){let l=cr(s,t);l.length>0&&(ar(e,{capturedAt:n,previousLastUpdated:s.lastUpdated||null,changedFields:l,snapshot:ur(s)}),s.lastSnapshotAt=n),s.seenCount=(s.seenCount||1)+1,s.lastSeen=r,s.lastUpdated=n,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let a of Io)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(s[a])&&s[a].length>0)continue;s[a]=t[a]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=n)}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?n:null};return xe(o),o[e]}function pt(e,t={}){if(!e)return null;let o=dt(),r=qe(),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 ft(o),o[e]}function mt(e,t){if(!e||!t)return;let o=X(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),xe(o)))}function Pe(e,t){if(!e||!t)return;let o=X(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let s={date:qe(),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(),xe(o))}function ht(e){return e&&X()[e]?.connectionStatus||null}function yt(e,t,o={}){if(!e)return;o.profileInfo?he(e,o.profileInfo):X()[e]||he(e,{});let r=X(),n=r[e];n&&(n.connectionStatus=t,n.connectionDate=qe(),n.connectionMethod=o.method||n.connectionMethod,n.messageSent=o.messageSent||n.messageSent,n.lastUpdated=new Date().toISOString(),xe(r))}function gt(){return de||(Z(),de=Fe(_o,"quota.json"),(!de||!de.connections)&&(de={connections:[]}),de)}function Ut(e){Z(),de=e;try{ye(_o,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function bt(e,t="unknown"){let o=gt(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Ut(o)}function wt(){let e=gt(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function St(){let e=wt(),t=qe(),o=e.filter(i=>i.date===t).length,r=e.length,n=o>=We,s=r>=Ye,l=!n&&!s,a={allowed:l,daily:{sent:o,max:We},weekly:{sent:r,max:Ye}};return l||(a.reason=n?`Daily limit reached (${o}/${We})`:`Weekly limit reached (${r}/${Ye})`),a}function Ke(){let e=wt(),t=qe(),o=e.filter(n=>n.date===t).length,r=e.length;return{daily:{sent:o,max:We,remaining:We-o},weekly:{sent:r,max:Ye,remaining:Ye-r}}}function fr(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function No(){Z();let e=O.readdirSync(K).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=X(),o=
|
|
4
|
-
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${n} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function
|
|
3
|
+
`);let t=X(),o=dt(),r=0,n=0;e.sort();for(let s of e){let l=V.join(K,s),a;try{a=JSON.parse(O.readFileSync(l,"utf-8"))}catch(c){console.log(` Skipping ${s}: ${c.message}`);continue}let i=a.date||s.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,u=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 c of a.profiles){let d=c.profileUrl;if(!d)continue;let f=t[d];if(f){f.seenCount=(f.seenCount||1)+1,i&&(!f.lastSeen||i>f.lastSeen)&&(f.lastSeen=i),i&&(!f.firstSeen||i<f.firstSeen)&&(f.firstSeen=i),u&&!f.sources?.includes(u)&&(f.sources=f.sources||[],f.sources.push(u));for(let p of Io)c[p]!=null&&(f[p]=c[p]);c.status&&c.processed&&(f.connectionStatus=c.status,f.connectionDate=i,c.funnelResult&&(f.connectionMethod=c.funnelResult.method||f.connectionMethod,f.messageSent=c.funnelResult.message||f.messageSent)),f.lastUpdated=new Date().toISOString()}else t[d]={name:c.name||null,title:c.title||null,location:c.location||null,company:c.company||null,connectionDegree:c.connectionDegree||null,connectionsCount:c.connectionsCount||null,mutualConnections:c.mutualConnections||null,photoUrl:c.photoUrl||null,hasVerifiedBadge:c.hasVerifiedBadge||!1,firstSeen:i,lastSeen:i,seenCount:1,sources:u?[u]:[],connectionStatus:c.processed&&c.status||null,connectionDate:c.processed?i:null,connectionMethod:c.funnelResult?.method||null,messageSent:c.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(c.fromJob?.url){let p=fr(c.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:c.fromJob.title||null,company:c.fromJob.company||null,location:null,salary:null,url:c.fromJob.url,applied:!0,appliedDate:i,recruiterUrl:d,firstSeen:i},n++))}}}return xe(t),ft(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 Fo(){return Ne||(Z(),Ne=Fe(To,"sync-state.json")||{},Ne)}function qo(e){Z(),Ne=e;try{ye(To,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Bt(){if(ke)return ke;Z();try{O.existsSync(Pt)&&(ke=JSON.parse(O.readFileSync(Pt,"utf-8")))}catch{}return ke||(ke={}),ke}function Po(e){return Array.isArray(e.applications)}function Oo(){let e=Bt();if(Po(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function Oe(e){if(!e||!e.questions||e.questions.length===0)return;let t=Bt(),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<=pr?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})};Po(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{ye(Pt,t)}catch(s){console.error(`[!] Failed to save application-questions.json: ${s.message}`)}}function Mo(){let e=Oo(),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 u=(l.answer||"").trim();i.answers.set(u,(i.answers.get(u)||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 Uo(e){if(O.existsSync(V.join(K,".git")))try{let t={cwd:K,stdio:"pipe",timeout:1e4};Nt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{Nt("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Nt(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var rr,sr,K,Ft,qt,_o,ct,To,Pt,Ot,We,Ye,Le,je,de,ve,Ne,ke,Io,ir,pr,mr,Qe=Je(async()=>{await Eo();rr=nr(import.meta.url),sr=V.dirname(V.dirname(rr)),K=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(sr,"collected-profiles"),Ft=V.join(K,"people.json"),qt=V.join(K,"jobs.json"),_o=V.join(K,"quota.json"),ct=V.join(K,"conversations.json"),To=V.join(K,"sync-state.json"),Pt=V.join(K,"application-questions.json"),Ot=V.join(K,"profile-history"),We=20,Ye=100,Le=null,je=null,de=null,ve=null,Ne=null,ke=null;Io=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],ir=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];pr=50;mr={loadPeople:X,savePeople:xe,loadJobs:dt,saveJobs:ft,loadConversations:Lo,saveConversations:jo,upsertPerson:he,upsertJob:pt,linkPersonToJob:mt,addEncounter:Pe,getPersonStatus:ht,updateConnectionStatus:yt,migrateFromDailyFiles:No,loadQuota:gt,saveQuota:Ut,recordConnectionSent:bt,canSendConnection:St,getRecentConnections:wt,getQuotaStatus:Ke,loadSyncState:Fo,saveSyncState:qo,commitDataSnapshot:Uo,logApplicationQuestions:Oe,getQuestionStats:Mo}});var Jo={};_e(Jo,{extractCertificationsFromDetails:()=>wr,extractEducationFromDetails:()=>gr,extractExperienceFromDetails:()=>hr,extractFeaturedFromDetails:()=>yr,extractRecommendationsFromDetails:()=>Sr,extractSkillsFromDetails:()=>br});async function hr(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/experience/`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(900);await g(1e3);let n=0;for(;n<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)n++,await g(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function l(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(f.textContent||"").length<500||d.push({el:f,count:h.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let a=l(s);if(!a)return[];let i=Array.from(a.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function u(c){let d=c[0]||null,f=null,p=null;if(c[1]){let C=c[1].split("\xB7").map(N=>N.trim());f=C[0]||null,C[1]&&(p=C[1])}let h=c.findIndex(C=>/(\d{4}|present)/i.test(C)&&/(-|–|—)/i.test(C)&&C.length<80),m=null,b=null;if(h>=0){let C=c[h].split("\xB7").map(N=>N.trim());m=C[0]||null,C[1]&&(b=C[1])}let y=null,k=-1;if(h>=0&&c[h+1]){let C=c[h+1],N=/^[>*\-•]|^>/.test(C),Y=/https?:\/\//.test(C),U=/\d{4}/.test(C),ae=/,/.test(C)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(C);!N&&!Y&&!U&&C.length<100&&ae&&(y=C,k=h+1)}let v=null,w=-1,E=c[c.length-1];if(E&&/and\s+\+\d+\s+skills?$/i.test(E)){w=c.length-1;let C=E.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);C&&(v={listed:C[1].split(",").map(N=>N.trim()),additional:parseInt(C[2],10)})}let q=new Set([0,1,h,k,w].filter(C=>C>=0)),D=c.filter((C,N)=>!q.has(N)),W=D.length>0?D.join(`
|
|
5
5
|
|
|
6
|
-
`):null;return{title:
|
|
7
|
-
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return u(
|
|
6
|
+
`):null;return{title:d,company:f,employmentType:p,dates:m,duration:b,location:y,description:W,skills:v,_raw:c}}return i.map(c=>{let f=(c.innerText||"").trim().split(`
|
|
7
|
+
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return u(f)}).filter(c=>c.title)})}catch(r){if(/session expired|bounced to|authwall|checkpoint/i.test(r.message||""))throw r;return console.error(`extractExperienceFromDetails failed for ${t}: ${r.message?.slice(0,120)}`),[]}}async function ze(e,t,o){let r=t.replace(/\/+$/,"")+`/details/${o}/`;await e.goto(r,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3);let n=e.url();if(/\/(login|authwall|checkpoint)/i.test(n))throw new Error(`Session expired \u2014 bounced to ${n} when fetching /details/${o}/`);if(!n.toLowerCase().includes(`/details/${o.toLowerCase()}/`))throw new Error(`Section /details/${o}/ not available on profile (landed on ${n})`);for(let l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(700);await g(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)s++,await g(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await g(600)}async function Ze(e,t,o,r){try{return await r()}catch(n){let s=n.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw n;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${o} failed for ${e}: ${s.slice(0,120)}`),[])}}async function yr(e,t){return Ze(t,"featured","extractFeaturedFromDetails",async()=>(await ze(e,t,"featured"),await e.evaluate(`(() => {
|
|
8
|
+
${Xe}
|
|
9
|
+
|
|
10
|
+
const main = document.querySelector('main');
|
|
11
|
+
if (!main) return [];
|
|
12
|
+
const container = findEntryContainer(main);
|
|
13
|
+
if (!container) return [];
|
|
14
|
+
|
|
15
|
+
const entries = Array.from(container.children)
|
|
16
|
+
.filter(c => c.tagName === 'DIV')
|
|
17
|
+
.filter(c => (c.textContent || '').trim().length > 30);
|
|
18
|
+
|
|
19
|
+
return entries.map(entry => {
|
|
20
|
+
const raw = (entry.innerText || '').trim();
|
|
21
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 2000);
|
|
22
|
+
|
|
23
|
+
// External link from any anchor inside the card (filter LinkedIn-internal)
|
|
24
|
+
const anchors = Array.from(entry.querySelectorAll('a[href]'));
|
|
25
|
+
const externalAnchor = anchors.find(a => {
|
|
26
|
+
const h = a.href || '';
|
|
27
|
+
return h.startsWith('http') &&
|
|
28
|
+
!h.includes('linkedin.com/in/') &&
|
|
29
|
+
!h.includes('linkedin.com/posts/') &&
|
|
30
|
+
!h.includes('#');
|
|
31
|
+
});
|
|
32
|
+
const url = externalAnchor?.href || anchors[0]?.href || null;
|
|
33
|
+
|
|
34
|
+
const title = lines[0] || null;
|
|
35
|
+
const caption = lines[1] && lines[1] !== title ? lines[1] : null;
|
|
36
|
+
|
|
37
|
+
return { title, caption, url, _raw: lines };
|
|
38
|
+
}).filter(e => {
|
|
39
|
+
if (!e.title) return false;
|
|
40
|
+
// Reject "People You May Know" sidebar cards: signature is
|
|
41
|
+
// exactly [title, "View"] with no url/caption beyond "View".
|
|
42
|
+
if (e._raw.length === 2 && e._raw[1] === 'View') return false;
|
|
43
|
+
return true;
|
|
44
|
+
});
|
|
45
|
+
})()`)))}async function gr(e,t){return Ze(t,"education","extractEducationFromDetails",async()=>(await ze(e,t,"education"),await e.evaluate(`(() => {
|
|
46
|
+
${Xe}
|
|
47
|
+
|
|
48
|
+
const main = document.querySelector('main');
|
|
49
|
+
if (!main) return [];
|
|
50
|
+
const container = findEntryContainer(main);
|
|
51
|
+
if (!container) return [];
|
|
52
|
+
|
|
53
|
+
const entries = Array.from(container.children)
|
|
54
|
+
.filter(c => c.tagName === 'DIV')
|
|
55
|
+
.filter(c => (c.textContent || '').trim().length > 30);
|
|
56
|
+
|
|
57
|
+
return entries.map(entry => {
|
|
58
|
+
const raw = (entry.innerText || '').trim();
|
|
59
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 5000);
|
|
60
|
+
|
|
61
|
+
const school = lines[0] || null;
|
|
62
|
+
const degree = lines[1] || null;
|
|
63
|
+
const dates = lines.find(l =>
|
|
64
|
+
/(\\d{4})/.test(l) &&
|
|
65
|
+
/(-|\u2013|\u2014)/i.test(l) &&
|
|
66
|
+
l.length < 80
|
|
67
|
+
) || null;
|
|
68
|
+
const used = new Set([0, 1, dates ? lines.indexOf(dates) : -1].filter(i => i >= 0));
|
|
69
|
+
const descLines = lines.filter((_, i) => !used.has(i));
|
|
70
|
+
const description = descLines.length > 0 ? descLines.join(' / ') : null;
|
|
71
|
+
|
|
72
|
+
return { school, degree, dates, description, _raw: lines };
|
|
73
|
+
}).filter(e => {
|
|
74
|
+
if (!e.school) return false;
|
|
75
|
+
// Reject "People You May Know" sidebar cards: [title, "View"].
|
|
76
|
+
if (e._raw.length === 2 && e._raw[1] === 'View') return false;
|
|
77
|
+
return true;
|
|
78
|
+
});
|
|
79
|
+
})()`)))}async function br(e,t){return Ze(t,"skills","extractSkillsFromDetails",async()=>(await ze(e,t,"skills"),await e.evaluate(`(() => {
|
|
80
|
+
${Xe}
|
|
81
|
+
|
|
82
|
+
const main = document.querySelector('main');
|
|
83
|
+
if (!main) return [];
|
|
84
|
+
const container = findEntryContainer(main);
|
|
85
|
+
if (!container) return [];
|
|
86
|
+
|
|
87
|
+
const entries = Array.from(container.children)
|
|
88
|
+
.filter(c => c.tagName === 'DIV')
|
|
89
|
+
.filter(c => (c.textContent || '').trim().length > 1);
|
|
90
|
+
|
|
91
|
+
const seen = new Set();
|
|
92
|
+
const skills = [];
|
|
93
|
+
for (const entry of entries) {
|
|
94
|
+
const raw = (entry.innerText || '').trim();
|
|
95
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(Boolean);
|
|
96
|
+
if (lines.length === 0) continue;
|
|
97
|
+
|
|
98
|
+
const name = lines[0];
|
|
99
|
+
if (!name || name.length > 100 || seen.has(name.toLowerCase())) continue;
|
|
100
|
+
seen.add(name.toLowerCase());
|
|
101
|
+
|
|
102
|
+
let endorsements = null;
|
|
103
|
+
for (const l of lines.slice(1)) {
|
|
104
|
+
const m = l.match(/(\\d+)\\s+endorsement/i);
|
|
105
|
+
if (m) { endorsements = parseInt(m[1], 10); break; }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
skills.push({ name, endorsements, _raw: lines });
|
|
109
|
+
}
|
|
110
|
+
return skills;
|
|
111
|
+
})()`)))}async function wr(e,t){return Ze(t,"certifications","extractCertificationsFromDetails",async()=>(await ze(e,t,"certifications"),await e.evaluate(`(() => {
|
|
112
|
+
${Xe}
|
|
113
|
+
|
|
114
|
+
const main = document.querySelector('main');
|
|
115
|
+
if (!main) return [];
|
|
116
|
+
const container = findEntryContainer(main);
|
|
117
|
+
if (!container) return [];
|
|
118
|
+
|
|
119
|
+
const entries = Array.from(container.children)
|
|
120
|
+
.filter(c => c.tagName === 'DIV')
|
|
121
|
+
.filter(c => (c.textContent || '').trim().length > 20);
|
|
122
|
+
|
|
123
|
+
return entries.map(entry => {
|
|
124
|
+
const raw = (entry.innerText || '').trim();
|
|
125
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 2000);
|
|
126
|
+
|
|
127
|
+
const name = lines[0] || null;
|
|
128
|
+
const issuer = lines[1] || null;
|
|
129
|
+
const issueDate = lines.find(l => /^Issued\\b/i.test(l)) || null;
|
|
130
|
+
const expiryDate = lines.find(l => /Expir(es|ed)\\b/i.test(l)) || null;
|
|
131
|
+
const credentialId = (lines.find(l => /credential id/i.test(l)) || '')
|
|
132
|
+
.replace(/^.*credential id[:\\s]*/i, '').trim() || null;
|
|
133
|
+
|
|
134
|
+
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
135
|
+
}).filter(e => e.name);
|
|
136
|
+
})()`)))}async function Sr(e,t){return Ze(t,"recommendations","extractRecommendationsFromDetails",async()=>(await ze(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
137
|
+
${Xe}
|
|
138
|
+
|
|
139
|
+
const main = document.querySelector('main');
|
|
140
|
+
if (!main) return [];
|
|
141
|
+
const container = findEntryContainer(main);
|
|
142
|
+
if (!container) return [];
|
|
143
|
+
|
|
144
|
+
const entries = Array.from(container.children)
|
|
145
|
+
.filter(c => c.tagName === 'DIV')
|
|
146
|
+
.filter(c => (c.textContent || '').trim().length > 50);
|
|
147
|
+
|
|
148
|
+
return entries.map(entry => {
|
|
149
|
+
const raw = (entry.innerText || '').trim();
|
|
150
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 5000);
|
|
151
|
+
|
|
152
|
+
const recommender = lines[0] || null;
|
|
153
|
+
const recommenderTitle = lines[1] || null;
|
|
154
|
+
const relationship = lines.find(l =>
|
|
155
|
+
/\\b(was |worked |reported |managed |taught |studied )\\b/i.test(l) &&
|
|
156
|
+
l.length < 200
|
|
157
|
+
) || null;
|
|
158
|
+
const date = lines.find(l => /(January|February|March|April|May|June|July|August|September|October|November|December)\\s+\\d{1,2}.*\\d{4}/i.test(l)) || null;
|
|
159
|
+
// Recommendation text is the longest non-meta line
|
|
160
|
+
const text = [...lines].sort((a, b) => b.length - a.length)[0] || '';
|
|
161
|
+
|
|
162
|
+
return { recommender, recommenderTitle, relationship, date, text, _raw: lines };
|
|
163
|
+
}).filter(e => {
|
|
164
|
+
if (!e.recommender || !e.text) return false;
|
|
165
|
+
// Reject "People You May Know" sidebar cards: [title, "View"].
|
|
166
|
+
if (e._raw.length === 2 && e._raw[1] === 'View') return false;
|
|
167
|
+
return true;
|
|
168
|
+
});
|
|
169
|
+
})()`)))}var Xe,Vo=Je(()=>{Te();Xe=`
|
|
170
|
+
function findEntryContainer(root) {
|
|
171
|
+
const candidates = [];
|
|
172
|
+
for (const div of root.querySelectorAll('div')) {
|
|
173
|
+
const directDivs = Array.from(div.children).filter(c => c.tagName === 'DIV');
|
|
174
|
+
if (directDivs.length < 2) continue;
|
|
175
|
+
const substantial = directDivs.filter(c => (c.textContent || '').trim().length > 30);
|
|
176
|
+
if (substantial.length < 2) continue;
|
|
177
|
+
if ((div.textContent || '').length < 200) continue;
|
|
178
|
+
|
|
179
|
+
// Reject "People You May Know" suggestion containers: every substantial
|
|
180
|
+
// child is exactly [title, "View"] (a tiny suggestion card with a single
|
|
181
|
+
// "View" CTA). Real section entries always have richer per-child content
|
|
182
|
+
// (multiple text lines per entry).
|
|
183
|
+
const allLookLikePYMK = substantial.every(c => {
|
|
184
|
+
const lines = (c.innerText || '').trim().split('\\n').map(l => l.trim()).filter(Boolean);
|
|
185
|
+
return lines.length === 2 && lines[1] === 'View';
|
|
186
|
+
});
|
|
187
|
+
if (allLookLikePYMK) continue;
|
|
188
|
+
|
|
189
|
+
// Reject LinkedIn footer/legal blocks: when a /details/<section>/ page
|
|
190
|
+
// renders empty, LinkedIn falls back to "Questions? Visit our Help
|
|
191
|
+
// Center", "Select language" (35+ languages), "Recommendation
|
|
192
|
+
// transparency" and similar nav cards inside <main>. These are unique
|
|
193
|
+
// marker strings that never appear inside real section entries.
|
|
194
|
+
const containerText = div.textContent || '';
|
|
195
|
+
const FOOTER_MARKERS = [
|
|
196
|
+
'Visit our Help Center',
|
|
197
|
+
'Select language',
|
|
198
|
+
'Recommendation transparency',
|
|
199
|
+
'Manage your account and privacy',
|
|
200
|
+
'Go to your Settings',
|
|
201
|
+
'Who your viewers also viewed', // "Private to you" PYMK block on empty pages
|
|
202
|
+
'People also viewed',
|
|
203
|
+
'People you may know',
|
|
204
|
+
];
|
|
205
|
+
if (FOOTER_MARKERS.some(m => containerText.includes(m))) continue;
|
|
206
|
+
|
|
207
|
+
candidates.push({ el: div, count: substantial.length, totalText: (div.textContent || '').length });
|
|
208
|
+
}
|
|
209
|
+
// Sort: most children first, then RICHER children (larger totalText) \u2014 real
|
|
210
|
+
// section entries dominate via content density, not just child count. The
|
|
211
|
+
// previous "smaller totalText wins" tie-break gave PYMK sidebars priority
|
|
212
|
+
// over the real Education / Recommendations lists.
|
|
213
|
+
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
214
|
+
return candidates[0]?.el;
|
|
215
|
+
}
|
|
216
|
+
`});Te();import ks from"puppeteer";import*as Fn from"fs";import{createGraphClient as Wn,resolveToken as Yn}from"@ilivemylife/graph-sdk";import{config as Kn}from"dotenv";Kn();var So=Yn()||process.env.TOKEN;So||(console.error(`
|
|
8
217
|
[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.
|
|
9
218
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
10
219
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
11
|
-
`),process.exit(1));var we=Ln({token:co});var Ie=12e4;async function Re(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 we.askLifebot(o,e,{timeout:Ie});return Ie=Math.max(12e4,Ie*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Ie=Math.min(Ie*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Ie/1e3)}s...`);continue}throw n}}async function Ct(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 Re(o)}async function tt(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Re(o)}async function Je(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Re(o)}Tt();import{LIFEBOT_MESSAGE_TYPES as bn}from"@ilivemylife/graph-sdk";Te();await Qe();async function qo(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 g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function No(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function or(e,t,o={}){let{extractExperience:r=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await qo(e,t));let s=0;for(let i=0;i<2;i++){let u=await e.evaluate(()=>document.body.scrollHeight);for(let f=1;f<=6;f++)await e.evaluate(d=>window.scrollTo(0,d),u*f/6),await g(900);let c=await e.evaluate(()=>document.body.scrollHeight);if(c===s)break;s=c}await g(800);let l=await e.evaluate(()=>{let i=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),u=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),c=A=>{let I=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},f={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},d=document.querySelector("main");if(!d)return f;let p=[...Array.from(d.querySelectorAll("h1")),...Array.from(d.querySelectorAll("h2"))],h=Array.from(d.querySelectorAll("h2")),m=p.find(A=>{let I=A.textContent&&A.textContent.trim(),j=(I||"").replace(/\s*\(\d+\)$/,"").trim();return I&&I.length>1&&I.length<100&&!i.has(j)&&!u.has(j)}),b=m?m.textContent.trim():null,y=m?m.parentElement:null;for(;y&&y!==d&&!Array.from(y.children).filter(I=>I.tagName==="P").some(I=>{let j=I.textContent&&I.textContent.trim();return j&&j.length>5&&!c(j)});)y=y.parentElement;let S=null,$=null,w=null,E=null;if(y&&y!==d){let A=Array.from(y.children).filter(j=>j.tagName==="P").filter(j=>{let pe=j.textContent&&j.textContent.trim();return pe&&pe.length>5&&!c(pe)});if(A[0]&&(S=A[0].textContent.trim()),A[1]){let j=A[1].textContent.trim().split(/\s*[·•]\s*/);$=j[0]||null,j.length>1&&(w=j.slice(1).join(" \xB7 "))}let I=Array.from(y.children).filter(j=>j.tagName==="DIV");for(let j=I.length-1;j>=0;j--){let pe=I[j].textContent&&I[j].textContent.trim();if(pe&&!(b&&pe.startsWith(b))&&(E=pe.split(/[·•]/)[0].trim(),E))break}}let P=null;if(y){let A=y.querySelectorAll("p, span, div");for(let I of A){let j=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(j==="1st"||j==="2nd"||j==="3rd"){P=j;break}}}let U=!!d.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),V=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),C=V&&V.src||null,L=d.textContent||"",z=null,W=L.match(/(\d+\+?)\s+connections\b/i);W&&(z=W[1]+" connections");let K=null,H=L.match(/(\d+)\s+mutual connection/i),_=L.match(/and\s+(\d+)\s+other mutual/i),G=L.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);H?K=parseInt(H[1],10):_?K=2+parseInt(_[1],10):G&&(K=2);let T=null,q=null,v=h.find(A=>A.textContent&&A.textContent.trim()==="About");if(v){let A=v.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let I=(A.textContent||"").trim();I=I.replace(/^About\s*/,"").trim();let j=I.match(/Top skills\s*(.+?)$/i);if(j){let Et=j[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Rn=>Rn.trim()).filter(Boolean);Et.length>0&&Et.length<10&&(q=Et)}I=I.split(/\n?…\s*more/i)[0].trim(),I=I.split(/\n?\.\.\.\s*more/i)[0].trim(),I=I.split(/\bTop skills\b/i)[0].trim(),I=I.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),T=I||null}}let O=null,N=h.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(N){let A=N.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let I=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);I&&(O=parseInt(I[1].replace(/,/g,""),10))}}let R=[...new Set(h.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==b).filter(A=>i.has(A)))],M=document.body.textContent||"",ce=/#OpenToWork\b/i.test(M)||/\bOpen to work\b/.test(M),be=/#Hiring\b/i.test(M)||/\bI'?m hiring\b/i.test(M)||/\bWe are hiring\b/i.test(M);return{name:b,title:S,location:E,currentCompany:$,currentSchool:w,connectionDegree:P,hasVerifiedBadge:U,photoUrl:C,connectionsLevel:z,mutualConnectionsCount:K,followers:O,openToWork:ce,hiring:be,about:T,topSkills:q,availableSections:R}});console.log(`Viewed: ${l.name} - ${l.title}`);let a=null;if(r){let{extractExperienceFromDetails:i}=await Promise.resolve().then(()=>(Do(),Lo));a=await i(e,t),console.log(` + Experience: ${a.length} entries`)}return{...l,profileUrl:t,...a!==null&&{experience:a}}}catch(n){console.error(`Error viewing profile ${t}:`,n.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(n.message||""))throw n;return null}}async function ze(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 Ft(e){let t=null,o=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(i=u.textContent?.trim(),i&&!i.includes("notification")))return i;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let i=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(c=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=c.toLowerCase().split(" ")[0],p=null,h=null;for(let m of f){let b=m.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(d)){p=m;break}h||(h=m)}return p||h||null},o);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(o){let i=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let u=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let b=m.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&d.test(b)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of d){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},i);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(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 u=await e.evaluate((c,f)=>{let d=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(c.getAttribute("aria-label")||"").toLowerCase(),b=m.includes("invite"),y=f?m.includes(f):!0;return{isMuted:d,isStickyHeader:p,inRecommendations:h,hasInvite:b,matchesName:y,ariaLabel:m}},i,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.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 u=await e.evaluate(c=>{let f=c.getBoundingClientRect(),d=f.width>0&&f.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:p,top:f.top}},i);if(u.isVisible&&!u.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 c=Array.from(document.querySelectorAll("button, a")).find(d=>{let p=d.innerText?.trim(),h=d.getAttribute("aria-label")||"",m=d.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let f=c.parentElement;for(let d=0;d<8&&f;d++){for(let p of f.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;f=f.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(c=>c.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let c=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let p=d.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=c?.asElement?.()||null,u||await c?.dispose?.().catch(()=>{})}if(!u){let c=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let p of f)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&d.push(m)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,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(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(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 nr(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(500);let o=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.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(c=>c.click(),t)]),await g(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await g(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await g(3e3)):(await e.evaluate(u=>u.click(),t),await g(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 rr(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 g(1500);let o=await Ft(e);if(o){await e.evaluate(n=>n.click(),o),await g(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 g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function sr(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 u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
12
|
-
--- Connecting: ${u} ---`),a.length>0){let y=X()[t]?.location;if(No(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),i.reason="excluded_location",i.profileInfo={location:y},i}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await qo(e,t),await g(2e3)),i.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),S=v=>{let O=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(O)},$={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return $;let E=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],P=Array.from(w.querySelectorAll("h2")),U=E.find(v=>{let O=v.textContent&&v.textContent.trim();return O&&O.length>1&&O.length<100&&!y.has(O)&&O!=="0 notifications"}),V=U?U.textContent.trim():null,C=U?U.parentElement:null;for(;C&&C!==w&&!Array.from(C.children).filter(N=>N.tagName==="P").some(N=>{let R=N.textContent&&N.textContent.trim();return R&&R.length>5&&!S(R)});)C=C.parentElement;let L=null,z=null,W=null;if(C&&C!==w){let v=Array.from(C.children),O=v.filter(R=>R.tagName==="P").filter(R=>{let M=R.textContent&&R.textContent.trim();return M&&M.length>5&&!S(M)});O[0]&&(L=O[0].textContent.trim()),O[1]&&(z=O[1].textContent.trim());let N=v.filter(R=>R.tagName==="DIV");for(let R=N.length-1;R>=0;R--){let M=N[R].textContent&&N[R].textContent.trim();if(M&&!(V&&M.startsWith(V))&&(W=M.split(/[·•]/)[0].trim(),W))break}}let K=null;if(C){let v=C.querySelectorAll("p, span, div");for(let O of v){let N=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(N==="1st"||N==="2nd"||N==="3rd"){K=N;break}}}let H=null,_=P.find(v=>v.textContent&&v.textContent.trim()==="About");if(_){let v=_.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;v&&(H=(v.textContent||"").trim().replace(/^About\s*/,"").trim()||null,H&&(H=H.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let G=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),T=G&&G.src||null,q=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:V,title:L,location:W,about:H,company:z,connectionDegree:K,connectionsCount:null,mutualConnections:null,photoUrl:T,hasVerifiedBadge:q}}),a.length>0){let y=i.profileInfo?.location,S=X()[t]?.location,$=y||S;if(No($,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${$}`),i.reason="excluded_location",i;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await ze(e);if(f==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await te(e);let d=await Ft(e);if(!d&&(await te(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),d=await Ft(e)),!d))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=d.method,await nr(e,d.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let y=await ze(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await te(e),await g(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),S),await g(500),await S.click().catch(()=>e.evaluate(w=>w.click(),S)),await g(2e3);let $=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if($){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(P=>P.click(),$),await g(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 g(3e3),i.reason="premium_required",i;if(await ze(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 g(500),i.reason="premium_required",i}catch($){return console.log(" More dropdown failed:",$.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await g(500),i.reason="email_required",i}let m=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!m&&!b){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let $=S.querySelector('button[aria-label="Add a note"]'),w=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!$,sendWithout:!!w}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=S?.asElement?.()||null,m||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=S?.asElement?.()||null,b||await S.dispose().catch(()=>{})}}if(n){if(m&&r){if(console.log(" Adding personalized note..."),await m.click(),await g(1500),await e.$("div.modal-upsell")){let $=await rr(e);return i.success=$,i.connectionSent=$,i.reason=$?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let $=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",$);await S.type(w,{delay:20}),await g(500);let E=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(E){try{await E.evaluate(P=>P.click())}catch{console.log(" Click timeout, likely still sent")}return await g(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(b){console.log(" Sending without note...");try{await b.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await g(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 y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y){try{await y.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3)),await te(e),await g(500);let S=await e.$$('button[id*="profile-overflow-action"]'),$=null;for(let w of S){let E=await e.evaluate(P=>{let U=P.getBoundingClientRect();return{visible:U.width>0&&U.height>0,inSticky:!!P.closest('.sticky-header, [class*="sticky"]')}},w);if(E.visible&&!E.inSticky){$=w;break}}!$&&S.length>0&&($=S[S.length-1]);for(let w of S)w!==$&&await w.dispose().catch(()=>{});if($)try{await e.evaluate(E=>E.scrollIntoView({behavior:"smooth",block:"center"}),$),await g(500),await $.click().catch(()=>e.evaluate(E=>E.click(),$)),await g(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 g(3e3);let E=e.url();if(E.includes("/premium/")||E.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await ze(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 ze(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 U=await e.$('button[aria-label="Send without a note"]');if(U){console.log(" Modal appeared via More dropdown, sending without note...");try{await U.evaluate(V=>V.click())}catch{}return await g(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(u){console.error(` \u2717 Error: ${u.message}`),i.reason="error",i.error=u.message;let c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{i.fatal=!0}return i}}async function Pt(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:c="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
13
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${s})`}`),l||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let p=
|
|
220
|
+
`),process.exit(1));var we=Wn({token:So});var Ie=12e4;async function Re(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 we.askLifebot(o,e,{timeout:Ie});return Ie=Math.max(12e4,Ie*.9),n.content}catch(n){if(n.constructor.name==="LifebotTimeoutError"&&r<t){Ie=Math.min(Ie*1.5,3e5),console.log(`Lifebot timeout (attempt ${r}/${t}), increasing timeout to ${Math.round(Ie/1e3)}s...`);continue}throw n}}async function Rt(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 Re(o)}async function st(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Re(o)}async function Ve(e,t){let o=`Choose the best answer: ${e} Available options: ${t.join(", ")} `;return await Re(o)}jt();import{LIFEBOT_MESSAGE_TYPES as _n}from"@ilivemylife/graph-sdk";Te();await Qe();async function Go(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 g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function Ho(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function kr(e,t,o={}){let{extractExperience:r=!1,extractFeatured:n=!1,extractEducation:s=!1,extractSkills:l=!1,extractRecommendations:a=!1,extractCertifications:i=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await Go(e,t));let c=0;for(let v=0;v<2;v++){let w=await e.evaluate(()=>document.body.scrollHeight);for(let q=1;q<=6;q++)await e.evaluate(D=>window.scrollTo(0,D),w*q/6),await g(900);let E=await e.evaluate(()=>document.body.scrollHeight);if(E===c)break;c=E}await g(800);let d=await e.evaluate(()=>{let v=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),w=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),E=A=>{let I=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},q={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},D=document.querySelector("main");if(!D)return q;let W=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],C=Array.from(D.querySelectorAll("h2")),N=W.find(A=>{let I=A.textContent&&A.textContent.trim(),L=(I||"").replace(/\s*\(\d+\)$/,"").trim();return I&&I.length>1&&I.length<100&&!v.has(L)&&!w.has(L)}),Y=N?N.textContent.trim():null,U=N?N.parentElement:null;for(;U&&U!==D&&!Array.from(U.children).filter(I=>I.tagName==="P").some(I=>{let L=I.textContent&&I.textContent.trim();return L&&L.length>5&&!E(L)});)U=U.parentElement;let ae=null,H=null,_=null,B=null;if(U&&U!==D){let A=Array.from(U.children).filter(L=>L.tagName==="P").filter(L=>{let me=L.textContent&&L.textContent.trim();return me&&me.length>5&&!E(me)});if(A[0]&&(ae=A[0].textContent.trim()),A[1]){let L=A[1].textContent.trim().split(/\s*[·•]\s*/);H=L[0]||null,L.length>1&&(_=L.slice(1).join(" \xB7 "))}let I=Array.from(U.children).filter(L=>L.tagName==="DIV");for(let L=I.length-1;L>=0;L--){let me=I[L].textContent&&I[L].textContent.trim();if(me&&!(Y&&me.startsWith(Y))&&(B=me.split(/[·•]/)[0].trim(),B))break}}let T=null;if(U){let A=U.querySelectorAll("p, span, div");for(let I of A){let L=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(L==="1st"||L==="2nd"||L==="3rd"){T=L;break}}}let P=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),x=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),M=x&&x.src||null,j=D.textContent||"",R=null,G=j.match(/(\d+\+?)\s+connections\b/i);G&&(R=G[1]+" connections");let z=null,pe=j.match(/(\d+)\s+mutual connection/i),Tt=j.match(/and\s+(\d+)\s+other mutual/i),Un=j.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);pe?z=parseInt(pe[1],10):Tt?z=2+parseInt(Tt[1],10):Un&&(z=2);let mo=null,ho=null,yo=C.find(A=>A.textContent&&A.textContent.trim()==="About");if(yo){let A=yo.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let I=(A.textContent||"").trim();I=I.replace(/^About\s*/,"").trim();let L=I.match(/Top skills\s*(.+?)$/i);if(L){let It=L[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Hn=>Hn.trim()).filter(Boolean);It.length>0&&It.length<10&&(ho=It)}I=I.split(/\n?…\s*more/i)[0].trim(),I=I.split(/\n?\.\.\.\s*more/i)[0].trim(),I=I.split(/\bTop skills\b/i)[0].trim(),I=I.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),mo=I||null}}let go=null,bo=C.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(bo){let A=bo.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let I=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);I&&(go=parseInt(I[1].replace(/,/g,""),10))}}let Bn=[...new Set(C.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==Y).filter(A=>v.has(A)))],Be=document.body.textContent||"",Jn=/#OpenToWork\b/i.test(Be)||/\bOpen to work\b/.test(Be),Vn=/#Hiring\b/i.test(Be)||/\bI'?m hiring\b/i.test(Be)||/\bWe are hiring\b/i.test(Be);return{name:Y,title:ae,location:B,currentCompany:H,currentSchool:_,connectionDegree:T,hasVerifiedBadge:P,photoUrl:M,connectionsLevel:R,mutualConnectionsCount:z,followers:go,openToWork:Jn,hiring:Vn,about:mo,topSkills:ho,availableSections:Bn}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,h=null,m=null,b=null,y=null;if(r||n||s||l||a||i){let v=await Promise.resolve().then(()=>(Vo(),Jo));r&&(f=await v.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),n&&(p=await v.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),s&&(h=await v.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(m=await v.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),a&&(b=await v.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${b.length} entries`)),i&&(y=await v.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${y.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...b!==null&&{recommendations:b},...y!==null&&{certifications:y}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function et(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 Jt(e){let t=null,o=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(i=u.textContent?.trim(),i&&!i.includes("notification")))return i;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let i=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p=null,h=null;for(let m of d){let b=m.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=m;break}h||(h=m)}return p||h||null},o);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(o){let i=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let u=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let b=m.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&f.test(b)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},i);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(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 u=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(c.getAttribute("aria-label")||"").toLowerCase(),b=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:b,matchesName:y,ariaLabel:m}},i,n);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.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 u=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},i);if(u.isVisible&&!u.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 c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});l=i?.asElement?.()||null,l||await i?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(c=>c.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=c?.asElement?.()||null,u||await c?.dispose?.().catch(()=>{})}if(!u){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,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(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=o.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(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 vr(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(500);let o=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.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(c=>c.click(),t)]),await g(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await g(2e3),"premium_redirect"}else s?(await e.evaluate(u=>u.click(),t),await g(3e3)):(await e.evaluate(u=>u.click(),t),await g(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 xr(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await g(1500);let o=await Jt(e);if(o){await e.evaluate(n=>n.click(),o),await g(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 g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function $r(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 u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
221
|
+
--- Connecting: ${u} ---`),a.length>0){let y=X()[t]?.location;if(Ho(y,a))return console.log(` \u26A0 Excluded location (stored): ${y}`),i.reason="excluded_location",i.profileInfo={location:y},i}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await Go(e,t),await g(2e3)),i.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=x=>{let M=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(M)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return v;let E=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],q=Array.from(w.querySelectorAll("h2")),D=E.find(x=>{let M=x.textContent&&x.textContent.trim();return M&&M.length>1&&M.length<100&&!y.has(M)&&M!=="0 notifications"}),W=D?D.textContent.trim():null,C=D?D.parentElement:null;for(;C&&C!==w&&!Array.from(C.children).filter(j=>j.tagName==="P").some(j=>{let R=j.textContent&&j.textContent.trim();return R&&R.length>5&&!k(R)});)C=C.parentElement;let N=null,Y=null,U=null;if(C&&C!==w){let x=Array.from(C.children),M=x.filter(R=>R.tagName==="P").filter(R=>{let G=R.textContent&&R.textContent.trim();return G&&G.length>5&&!k(G)});M[0]&&(N=M[0].textContent.trim()),M[1]&&(Y=M[1].textContent.trim());let j=x.filter(R=>R.tagName==="DIV");for(let R=j.length-1;R>=0;R--){let G=j[R].textContent&&j[R].textContent.trim();if(G&&!(W&&G.startsWith(W))&&(U=G.split(/[·•]/)[0].trim(),U))break}}let ae=null;if(C){let x=C.querySelectorAll("p, span, div");for(let M of x){let j=(M.textContent||"").trim().replace(/^[·•]\s*/,"");if(j==="1st"||j==="2nd"||j==="3rd"){ae=j;break}}}let H=null,_=q.find(x=>x.textContent&&x.textContent.trim()==="About");if(_){let x=_.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;x&&(H=(x.textContent||"").trim().replace(/^About\s*/,"").trim()||null,H&&(H=H.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let B=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),T=B&&B.src||null,P=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:W,title:N,location:U,about:H,company:Y,connectionDegree:ae,connectionsCount:null,mutualConnections:null,photoUrl:T,hasVerifiedBadge:P}}),a.length>0){let y=i.profileInfo?.location,k=X()[t]?.location,v=y||k;if(Ho(v,a))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),i.reason="excluded_location",i;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await et(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 te(e);let f=await Jt(e);if(!f&&(await te(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),f=await Jt(e)),!f))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;if(i.method=f.method,await vr(e,f.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let y=await et(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await te(e),await g(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),k),await g(500),await k.click().catch(()=>e.evaluate(w=>w.click(),k)),await g(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(v){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(q=>q.click(),v),await g(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 g(3e3),i.reason="premium_required",i;if(await et(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 g(500),i.reason="premium_required",i}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await g(500),i.reason="email_required",i}let m=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!m&&!b){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let v=k.querySelector('button[aria-label="Add a note"]'),w=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!w}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=k?.asElement?.()||null,b||await k.dispose().catch(()=>{})}}if(n){if(m&&r){if(console.log(" Adding personalized note..."),await m.click(),await g(1500),await e.$("div.modal-upsell")){let v=await xr(e);return i.success=v,i.connectionSent=v,i.reason=v?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=r.replace("{name}",v);await k.type(w,{delay:20}),await g(500);let E=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(E){try{await E.evaluate(q=>q.click())}catch{console.log(" Click timeout, likely still sent")}return await g(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(b){console.log(" Sending without note...");try{await b.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await g(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 y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3)),await te(e),await g(500);let k=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let w of k){let E=await e.evaluate(q=>{let D=q.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!q.closest('.sticky-header, [class*="sticky"]')}},w);if(E.visible&&!E.inSticky){v=w;break}}!v&&k.length>0&&(v=k[k.length-1]);for(let w of k)w!==v&&await w.dispose().catch(()=>{});if(v)try{await e.evaluate(E=>E.scrollIntoView({behavior:"smooth",block:"center"}),v),await g(500),await v.click().catch(()=>e.evaluate(E=>E.click(),v)),await g(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(W=>W.click(),w),await g(3e3);let E=e.url();if(E.includes("/premium/")||E.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await et(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 et(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(W=>W.click())}catch{}return await g(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(u){console.error(` \u2717 Error: ${u.message}`),i.reason="error",i.error=u.message;let c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{i.fatal=!0}return i}}async function Vt(e,t,o={}){let{message:r=null,useCustomMessage:n=!0,maxConnections:s=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:c="unknown"}=o,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
222
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${s})`}`),l||console.log(`Custom messages: ${n?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let p=Ke();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let f=0;for(let p=0;p<t.length;p++){let h=t[p];try{if(e.isClosed()){console.log(`
|
|
14
223
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
15
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=
|
|
16
|
-
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),
|
|
17
|
-
\u26A0 ${
|
|
18
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!l){let p=Ye();console.log(` Quota remaining: today ${p.daily.remaining}/${p.daily.max} | week ${p.weekly.remaining}/${p.weekly.max}`)}return f}await Qe();Te();async function Oo(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 f of r)if(n=document.querySelector(f),n){s=f;break}if(!n){let f=document.querySelector("li.scaffold-layout__list-item");if(f){let d=f.parentElement;for(;d&&d!==document.body;){if(d.scrollHeight>d.clientHeight){n=d,s="parent of li.scaffold-layout__list-item";break}d=d.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let l=n.scrollTop,a=300,i=300,u=50,c=0;for(;c<u&&(n.scrollBy(0,a),await new Promise(f=>setTimeout(f,i)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)c++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:c}},t)}async function Fo(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],u=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),c=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),f=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:i,isEasyApply:l,applyType:l?"easy-apply":"external",dataId:a.getAttribute("data-control-id"),href:`https://linkedin.com${i}`,jobTitle:u,companyName:c,location:f,salary:d||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 Po(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 g(2e3),t.success}async function Mt(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 g(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 Mo(e,t,o,r){for(let n of t){await Mt(e,r)&&(await te(e),await g(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(d=>d.scrollIntoView({block:"center"}),l),await g(300),await l.click(),await g(1500);let u=!1;for(let d=0;d<8;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==i){u=!0;break}await g(500)}if(!u){await e.evaluate(d=>d.click(),l),await g(1500);for(let d=0;d<6;d++){let p=await e.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"");if(p&&p!==i){u=!0;break}await g(500)}u||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let c=await e.evaluate(()=>{let d=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of d)for(let h of p.querySelectorAll("button")){let m=h.innerText?.trim();if(m==="Continue applying"||m==="Got it"||m==="Dismiss")return h.click(),m}return null});c&&console.log(` Dismissed popup before processing (${c})`);let{keepGoing:f}=await o(e,n);if(!f)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 Uo(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 Bo(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 M of s){let ce=M.querySelector(".job-criteria__subheader")?.textContent?.trim(),be=M.querySelector(".job-criteria__text")?.textContent?.trim();ce&&be&&(n[ce.toLowerCase()]=be)}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 M of l)new RegExp("\\b"+M.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(M.replace(/\\\+/g,"+"));let u=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,f=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,d=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=d?.innerText?.trim()||null,m=(d?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",$=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=y.match(/(\d[\d,]*)\s+applicant/i),E=w?parseInt(w[1].replace(/,/g,"")):null,P=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),U=Array.from(P).map(M=>M.innerText?.trim()?.replace(/\s+/g," ")),C=U.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,L=U.join(" ")+" "+y,z=/\bremote\b/i.test(L)?"remote":/\bhybrid\b/i.test(L)?"hybrid":/\bon-?site\b/i.test(L)?"onsite":null,W=/\bcontract\b/i.test(L)?"contract":/\bfull-?time\b/i.test(L)?"full-time":/\bpart-?time\b/i.test(L)?"part-time":/\bfreelance\b/i.test(L)?"freelance":/\btemporary\b/i.test(L)?"temporary":null,H=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",G=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",T=(H+" "+r+" "+G).toLowerCase(),q=H.toLowerCase(),v=[];/\bremote\b/.test(T)&&v.push("remote"),/\bhybrid\b/.test(T)&&v.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(T)&&v.push("onsite"),(v.length===0||!v.includes("remote")&&!v.includes("hybrid")&&!v.includes("onsite"))&&/remote/i.test(G)&&v.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(q)&&v.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(q)&&v.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(q)&&!v.includes("managerial")&&v.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(q)?v.push("junior"):/\b(senior|sr\.?)\b/i.test(q)?v.push("senior"):/\b(staff|principal|distinguished)\b/i.test(q)?v.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(q)?v.push("executive"):/\b(lead|team lead)\b/i.test(q)&&v.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(T)&&v.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(T)&&v.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(T)&&v.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(T)&&v.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(T)&&v.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(T)&&v.push("mobile"),/\b(architect)\b/i.test(q)&&v.push("architect"),/\b(consultant|consulting)\b/i.test(q)&&v.push("consultant");let O=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(O)||/\bcontract\b/i.test(T))&&v.push("contract"),/full.?time|permanent/i.test(O)&&v.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(G)&&v.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(G)&&v.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&v.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:f,companyName:p,companyUrl:m?m.startsWith("/")?"https://www.linkedin.com"+m:m:null,aboutCompany:u,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:$,applicantCount:E,companySize:C,workplaceType:z,contractType:W,techStack:[...new Set(a)],jobTags:[...new Set(v)]}})}import"dotenv/config";import*as ne from"fs";import*as ee from"path";import{fileURLToPath as ir}from"url";var lr=ir(import.meta.url),ar=ee.dirname(ee.dirname(lr)),$e=process.env.DATA_DIR?ee.resolve(process.env.DATA_DIR,"market-research"):ee.join(ar,"market-research"),Jo=ee.join($e,"scouted-jobs.json"),ni=ee.join($e,"discovered-people.json"),ri=ee.join($e,"visit-log.json"),Ho=ee.join($e,"companies.json"),Go=ee.join($e,"job-decisions.json");function Ut(){ne.existsSync($e)||ne.mkdirSync($e,{recursive:!0})}function Bt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ne.writeFileSync(r,o);for(let n=0;n<3;n++)try{ne.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Jt(e){try{if(ne.existsSync(e))return JSON.parse(ne.readFileSync(e,"utf-8"))}catch{}return null}function Vo(){Ke=null,Xe=null,ur=null,Ze=null,fr=null}var Ke=null;function cr(){return Ke||(Ke=Jt(Jo)||{},Ke)}function Wo(e,t){if(!e)return;Ut();let o=cr(),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{Bt(Jo,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var Xe=null;function Yo(){return Xe||(Xe=Jt(Go)||{},Xe)}function Me(e,t,o={}){if(!e||!t)return;Ut();let r=Yo(),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{Bt(Go,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function Qo(e){return Yo()[e]||null}var ur=null;var Ze=null;function dr(){return Ze||(Ze=Jt(Ho)||{},Ze)}function Ht(e,t){if(!e)return;Ut();let o=dr(),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{Bt(Ho,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var fr=null;import"dotenv/config";import*as x from"fs";import*as Kt from"os";import*as D from"path";import{fileURLToPath as Ir}from"url";var Wt={};_e(Wt,{NAME:()=>mr,VERSION:()=>pr,up:()=>gr});import*as re from"fs";import*as gt from"path";var pr=1,mr="normalize-jobs-and-questions",hr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],yr=50;function Gt(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function Vt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{re.writeFileSync(r,o)}catch(n){try{re.unlinkSync(r)}catch{}throw n}try{re.renameSync(r,e)}catch(n){try{re.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function gr(e,t){let o=gt.join(e,"jobs.json"),r=gt.join(t,"scouted-jobs.json"),n=gt.join(e,"application-questions.json"),s=Gt(o)||{},l=Gt(r)||{},a=0,i=[];for(let c of Object.keys(s)){if(!l[c])continue;let f=l[c],d=s[c];for(let p of hr)f[p]!=null&&d[p]==null&&(d[p]=f[p]);i.push(c),a++}a>0?(Vt(o,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Gt(n);if(u&&Array.isArray(u.applications)){let c={},f=0;for(let d of u.applications){let p=d.jobId||"unknown";c[p]||(c[p]={applications:[]});let h=(d.questions||[]).map(m=>{let b={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=yr?b.options=m.options:(b.optionsOmitted=!0,f++)),m.page&&(b.page=m.page),m.wasPreFilled&&(b.wasPreFilled=!0),m.wasRetry&&(b.wasRetry=!0),b});c[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||h.length,questions:h})}Vt(n,c),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let c of i)delete l[c];Vt(r,l),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Yt={};_e(Yt,{NAME:()=>wr,VERSION:()=>br,up:()=>vr});import*as se from"fs";import*as zo from"path";var br=2,wr="reset-unread-flags";function Sr(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function kr(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{se.writeFileSync(r,o)}catch(n){try{se.unlinkSync(r)}catch{}throw n}try{se.renameSync(r,e)}catch(n){try{se.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function vr(e){let t=zo.join(e,"conversations.json"),o=Sr(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}kr(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Qt={};_e(Qt,{NAME:()=>$r,VERSION:()=>xr,up:()=>Tr});import*as ie from"fs";import*as Ko from"path";var xr=3,$r="recompute-last-message-by",Er=new Set(["draft","confirmed","rejected","needs_review"]);function Cr(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function Ar(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ie.writeFileSync(r,o)}catch(n){try{ie.unlinkSync(r)}catch{}throw n}try{ie.renameSync(r,e)}catch(n){try{ie.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}function _r(e,t){if(!e||e.length===0)return"them";let o=e.filter(s=>!Er.has(s.status));if(o.length===0)return"them";let r=o.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,l)=>l.t-s.t).map(s=>s.m),n=r.length>0?r:[...o].reverse();for(let s of n){let l=s.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Tr(e){let t=Ko.join(e,"conversations.json"),o=Cr(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,s=0,l=0;for(let a of Object.keys(o)){let i=o[a];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,s++);let u=Array.isArray(i.messages)?i.messages:[],c=_r(u,r),f=c==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==c&&l++,i.lastMessageBy=c,i.conversationStatus=f,n++}if(n===0){console.log(" No conversations to recompute.");return}Ar(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}await Qe();var Rr=Ir(import.meta.url),jr=D.dirname(Rr),Lr=D.dirname(D.dirname(jr));function Dr(e){return e&&(e==="~"?Kt.homedir():e.startsWith("~/")||e.startsWith("~\\")?D.join(Kt.homedir(),e.slice(2)):e)}var ae=process.env.DATA_DIR?D.resolve(Dr(process.env.DATA_DIR)):Lr,Ce=D.join(ae,"collected-profiles"),Ae=D.join(ae,"market-research"),Q=D.join(ae,".schema-version"),Xo=[D.join(Ce,".schema-version"),D.join(Ae,".schema-version")],ye=3,fe=[{version:1,module:Wt},{version:2,module:Yt},{version:3,module:Qt}];(function(){fe.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of fe){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=fe.length?fe[fe.length-1].version:0;if(o!==ye)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${ye}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<fe.length;r++){let n=r+1;if(fe[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${fe[r].version}`)}})();function on(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
224
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=ht(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,i&&await i(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl}`);let b=null;if(l){let y=await kr(e,h.profileUrl);y?(he(h.profileUrl,{...y,source:c}),d.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y}):(d.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let y=St();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await $r(e,h.profileUrl,{message:r,useCustomMessage:n,excludeLocations:u}),b.success)d.connectionsSent++,b.connectionSent&&bt(h.profileUrl,c);else switch(b.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(b?.fatal){console.log(`
|
|
225
|
+
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(b?.reason==="error"){if(f++,f>=3){console.log(`
|
|
226
|
+
\u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(b&&b.reason&&(yt(h.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),Pe(h.profileUrl,{source:c||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:b.reason})),i&&await i(h,d,b),p<t.length-1){let y=a+Math.random()*2e3;await g(y)}}if(console.log(`
|
|
227
|
+
=== 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=Ke();console.log(` Quota remaining: today ${p.daily.remaining}/${p.daily.max} | week ${p.weekly.remaining}/${p.weekly.max}`)}return d}await Qe();Te();async function Wo(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 f=d.parentElement;for(;f&&f!==document.body;){if(f.scrollHeight>f.clientHeight){n=f,s="parent of li.scaffold-layout__list-item";break}f=f.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let l=n.scrollTop,a=300,i=300,u=50,c=0;for(;c<u&&(n.scrollBy(0,a),await new Promise(d=>setTimeout(d,i)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)c++;return{found:!0,usedSelector:s,initialScroll:l,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:c}},t)}async function Yo(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],u=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),c=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),d=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),f=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:u,companyName:c,location:d,salary:f||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 Ko(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 g(2e3),t.success}async function Ht(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 g(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 Qo(e,t,o,r){for(let n of t){await Ht(e,r)&&(await te(e),await g(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(f=>f.scrollIntoView({block:"center"}),l),await g(300),await l.click(),await g(1500);let u=!1;for(let f=0;f<8;f++){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){u=!0;break}await g(500)}if(!u){await e.evaluate(f=>f.click(),l),await g(1500);for(let f=0;f<6;f++){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){u=!0;break}await g(500)}u||console.log(` \u26A0 Panel did not update after retry click for: ${n.jobTitle}`)}let c=await e.evaluate(()=>{let f=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let p of f)for(let h of p.querySelectorAll("button")){let m=h.innerText?.trim();if(m==="Continue applying"||m==="Got it"||m==="Dismiss")return h.click(),m}return null});c&&console.log(` Dismissed popup before processing (${c})`);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 zo(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 Xo(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},s=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let G of s){let z=G.querySelector(".job-criteria__subheader")?.textContent?.trim(),pe=G.querySelector(".job-criteria__text")?.textContent?.trim();z&&pe&&(n[z.toLowerCase()]=pe)}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 G of l)new RegExp("\\b"+G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&a.push(G.replace(/\\\+/g,"+"));let u=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,f=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=f?.innerText?.trim()||null,m=(f?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,y=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",v=y.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,w=y.match(/(\d[\d,]*)\s+applicant/i),E=w?parseInt(w[1].replace(/,/g,"")):null,q=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),D=Array.from(q).map(G=>G.innerText?.trim()?.replace(/\s+/g," ")),C=D.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,N=D.join(" ")+" "+y,Y=/\bremote\b/i.test(N)?"remote":/\bhybrid\b/i.test(N)?"hybrid":/\bon-?site\b/i.test(N)?"onsite":null,U=/\bcontract\b/i.test(N)?"contract":/\bfull-?time\b/i.test(N)?"full-time":/\bpart-?time\b/i.test(N)?"part-time":/\bfreelance\b/i.test(N)?"freelance":/\btemporary\b/i.test(N)?"temporary":null,H=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",B=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",T=(H+" "+r+" "+B).toLowerCase(),P=H.toLowerCase(),x=[];/\bremote\b/.test(T)&&x.push("remote"),/\bhybrid\b/.test(T)&&x.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(T)&&x.push("onsite"),(x.length===0||!x.includes("remote")&&!x.includes("hybrid")&&!x.includes("onsite"))&&/remote/i.test(B)&&x.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(P)&&x.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(P)&&x.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(P)&&!x.includes("managerial")&&x.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(P)?x.push("junior"):/\b(senior|sr\.?)\b/i.test(P)?x.push("senior"):/\b(staff|principal|distinguished)\b/i.test(P)?x.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(P)?x.push("executive"):/\b(lead|team lead)\b/i.test(P)&&x.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(T)&&x.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(T)&&x.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(T)&&x.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(T)&&x.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(T)&&x.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(T)&&x.push("mobile"),/\b(architect)\b/i.test(P)&&x.push("architect"),/\b(consultant|consulting)\b/i.test(P)&&x.push("consultant");let M=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(M)||/\bcontract\b/i.test(T))&&x.push("contract"),/full.?time|permanent/i.test(M)&&x.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(B)&&x.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(B)&&x.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&x.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:d,companyName:p,companyUrl:m?m.startsWith("/")?"https://www.linkedin.com"+m:m:null,aboutCompany:u,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:v,applicantCount:E,companySize:C,workplaceType:Y,contractType:U,techStack:[...new Set(a)],jobTags:[...new Set(x)]}})}import"dotenv/config";import*as ne from"fs";import*as ee from"path";import{fileURLToPath as Er}from"url";var Cr=Er(import.meta.url),Ar=ee.dirname(ee.dirname(Cr)),$e=process.env.DATA_DIR?ee.resolve(process.env.DATA_DIR,"market-research"):ee.join(Ar,"market-research"),Zo=ee.join($e,"scouted-jobs.json"),vi=ee.join($e,"discovered-people.json"),xi=ee.join($e,"visit-log.json"),en=ee.join($e,"companies.json"),tn=ee.join($e,"job-decisions.json");function Gt(){ne.existsSync($e)||ne.mkdirSync($e,{recursive:!0})}function Wt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";ne.writeFileSync(r,o);for(let n=0;n<3;n++)try{ne.renameSync(r,e);return}catch(s){if(n<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Yt(e){try{if(ne.existsSync(e))return JSON.parse(ne.readFileSync(e,"utf-8"))}catch{}return null}function on(){tt=null,ot=null,Tr=null,nt=null,Rr=null}var tt=null;function _r(){return tt||(tt=Yt(Zo)||{},tt)}function nn(e,t){if(!e)return;Gt();let o=_r(),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{Wt(Zo,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var ot=null;function rn(){return ot||(ot=Yt(tn)||{},ot)}function Me(e,t,o={}){if(!e||!t)return;Gt();let r=rn(),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{Wt(tn,r)}catch(s){console.error(`[!] Failed to save job-decisions.json: ${s.message}`)}}function sn(e){return rn()[e]||null}var Tr=null;var nt=null;function Ir(){return nt||(nt=Yt(en)||{},nt)}function Kt(e,t){if(!e)return;Gt();let o=Ir(),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{Wt(en,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var Rr=null;import"dotenv/config";import*as $ from"fs";import*as oo from"os";import*as F from"path";import{fileURLToPath as Kr}from"url";var Xt={};_e(Xt,{NAME:()=>Lr,VERSION:()=>Dr,up:()=>Fr});import*as re from"fs";import*as kt from"path";var Dr=1,Lr="normalize-jobs-and-questions",jr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Nr=50;function Qt(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function zt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{re.writeFileSync(r,o)}catch(n){try{re.unlinkSync(r)}catch{}throw n}try{re.renameSync(r,e)}catch(n){try{re.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function Fr(e,t){let o=kt.join(e,"jobs.json"),r=kt.join(t,"scouted-jobs.json"),n=kt.join(e,"application-questions.json"),s=Qt(o)||{},l=Qt(r)||{},a=0,i=[];for(let c of Object.keys(s)){if(!l[c])continue;let d=l[c],f=s[c];for(let p of jr)d[p]!=null&&f[p]==null&&(f[p]=d[p]);i.push(c),a++}a>0?(zt(o,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Qt(n);if(u&&Array.isArray(u.applications)){let c={},d=0;for(let f of u.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let h=(f.questions||[]).map(m=>{let b={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=Nr?b.options=m.options:(b.optionsOmitted=!0,d++)),m.page&&(b.page=m.page),m.wasPreFilled&&(b.wasPreFilled=!0),m.wasRetry&&(b.wasRetry=!0),b});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}zt(n,c),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let c of i)delete l[c];zt(r,l),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Zt={};_e(Zt,{NAME:()=>Pr,VERSION:()=>qr,up:()=>Ur});import*as se from"fs";import*as ln from"path";var qr=2,Pr="reset-unread-flags";function Or(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Mr(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{se.writeFileSync(r,o)}catch(n){try{se.unlinkSync(r)}catch{}throw n}try{se.renameSync(r,e)}catch(n){try{se.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}async function Ur(e){let t=ln.join(e,"conversations.json"),o=Or(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Mr(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var eo={};_e(eo,{NAME:()=>Jr,VERSION:()=>Br,up:()=>Yr});import*as ie from"fs";import*as an from"path";var Br=3,Jr="recompute-last-message-by",Vr=new Set(["draft","confirmed","rejected","needs_review"]);function Hr(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function Gr(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{ie.writeFileSync(r,o)}catch(n){try{ie.unlinkSync(r)}catch{}throw n}try{ie.renameSync(r,e)}catch(n){try{ie.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=n.code,s}throw n}}function Wr(e,t){if(!e||e.length===0)return"them";let o=e.filter(s=>!Vr.has(s.status));if(o.length===0)return"them";let r=o.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,l)=>l.t-s.t).map(s=>s.m),n=r.length>0?r:[...o].reverse();for(let s of n){let l=s.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Yr(e){let t=an.join(e,"conversations.json"),o=Hr(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,s=0,l=0;for(let a of Object.keys(o)){let i=o[a];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,s++);let u=Array.isArray(i.messages)?i.messages:[],c=Wr(u,r),d=c==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==c&&l++,i.lastMessageBy=c,i.conversationStatus=d,n++}if(n===0){console.log(" No conversations to recompute.");return}Gr(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}await Qe();var Qr=Kr(import.meta.url),zr=F.dirname(Qr),Xr=F.dirname(F.dirname(zr));function Zr(e){return e&&(e==="~"?oo.homedir():e.startsWith("~/")||e.startsWith("~\\")?F.join(oo.homedir(),e.slice(2)):e)}var ce=process.env.DATA_DIR?F.resolve(Zr(process.env.DATA_DIR)):Xr,Ce=F.join(ce,"collected-profiles"),Ae=F.join(ce,"market-research"),Q=F.join(ce,".schema-version"),cn=[F.join(Ce,".schema-version"),F.join(Ae,".schema-version")],ge=3,fe=[{version:1,module:Xt},{version:2,module:Zt},{version:3,module:eo}];(function(){fe.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of fe){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=fe.length?fe[fe.length-1].version:0;if(o!==ge)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${ge}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<fe.length;r++){let n=r+1;if(fe[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${fe[r].version}`)}})();function pn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
19
228
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
20
|
-
`),process.exit(1));try{
|
|
21
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
22
|
-
`),process.exit(1))}let e;try{e
|
|
23
|
-
[FATAL] DATA_DIR (${
|
|
229
|
+
`),process.exit(1));try{$.mkdirSync(ce,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
230
|
+
[FATAL] Cannot create DATA_DIR (${ce}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
231
|
+
`),process.exit(1))}let e;try{e=$.statSync(ce)}catch(t){console.error(`
|
|
232
|
+
[FATAL] DATA_DIR (${ce}) is not accessible: ${t.message}
|
|
24
233
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
25
|
-
[FATAL] DATA_DIR (${
|
|
26
|
-
`),process.exit(1));for(let t of[Ce,Ae]){let o;try{o
|
|
234
|
+
[FATAL] DATA_DIR (${ce}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
235
|
+
`),process.exit(1));for(let t of[Ce,Ae]){let o;try{o=$.lstatSync(t)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
|
|
27
236
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
28
|
-
`),process.exit(1))}}var Ee=
|
|
237
|
+
`),process.exit(1))}}var Ee=F.join(ce,".migration-lock");function es(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return $.writeFileSync(Ee,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse($.readFileSync(Ee,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(l){l.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,s=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(s=Date.now()-l)}r&&s<n&&(console.error(`
|
|
29
238
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Ee}
|
|
30
239
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
31
|
-
`),process.exit(1)),r&&s>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Ee+".tmp";try{return
|
|
240
|
+
`),process.exit(1)),r&&s>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Ee+".tmp";try{return $.writeFileSync(o,e),$.renameSync(o,Ee),!0}catch(r){try{$.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function no(){try{if(JSON.parse($.readFileSync(Ee,"utf-8")).pid!==process.pid)return;$.unlinkSync(Ee)}catch{}}var un=!1;function ts(){if(un)return;un=!0;let e=()=>{try{no()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function os(){if($.existsSync(Q))return;let e=[],t=[];for(let s of cn)if($.existsSync(s))try{e.push({file:s,schema:vt(s)})}catch(l){t.push({file:s,err:l.message})}if(t.length>0){console.error(`
|
|
32
241
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
|
|
33
242
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
34
243
|
`),process.exit(1)}if(e.length===0)return;let o=e.map(s=>s.schema.version);if(new Set(o).size>1){console.error(`
|
|
35
244
|
[FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
36
|
-
`),process.exit(1)}let r=e[0].schema,n=Q+".tmp";try{
|
|
245
|
+
`),process.exit(1)}let r=e[0].schema,n=Q+".tmp";try{$.writeFileSync(n,JSON.stringify(r,null,2)),$.renameSync(n,Q)}catch(s){try{$.unlinkSync(n)}catch{}throw s}for(let s of cn)if($.existsSync(s))try{$.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${Q}`)}function ns(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function vt(e){let t=$.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function dn(){if(os(),!$.existsSync(Q))return{version:0,migrations:[]};let e;try{e=vt(Q)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
37
246
|
[FATAL] ${Q} is not valid JSON: ${o.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
38
|
-
`),process.exit(1)}let t=
|
|
247
|
+
`),process.exit(1)}let t=ns(e);return t===null&&(console.error(`
|
|
39
248
|
[FATAL] ${Q} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
40
|
-
`),process.exit(1)),t}function
|
|
41
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
42
|
-
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${
|
|
249
|
+
`),process.exit(1)),t}function mn(e){try{$.chmodSync(e,384)}catch{}}function rs(e){if(pn(),$.existsSync(Q))try{if($.lstatSync(Q).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${Q}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=Q+".tmp";try{$.writeFileSync(t,JSON.stringify(e,null,2)),mn(t),$.renameSync(t,Q)}catch(o){try{$.unlinkSync(t)}catch{}throw o}}function fn(e,t){if(!$.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=$.readdirSync(e).filter(a=>{let i=a.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return $.statSync(F.join(e,a)).isFile()}catch{return!1}}),n=0,s=0,l=[];for(let a of r){let i=F.join(e,a),u=F.join(e,a+o);if($.existsSync(u)){s++;continue}try{yn(i,u),n++}catch(c){l.push({file:a,err:c.message})}}if(l.length>0){let a=new Error(`Failed to back up ${l.length} file(s) in ${F.basename(e)}/: `+l.map(i=>`${i.file} (${i.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(n>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${F.basename(e)}/ (${o})${a}`)}}var to=!1;async function hn(){if(to)return;pn(),cs();let t=dn().version;if(t===ge){to=!0;return}ts(),es(),process.on("exit",no),t>ge&&(console.error(`
|
|
250
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${ge}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
251
|
+
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${ge}.
|
|
43
252
|
`),process.exit(1)),console.log(`
|
|
44
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
253
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${ge}`);let o=us();if(!o.ok){console.error(`
|
|
45
254
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of o.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
|
|
46
255
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
47
256
|
`),process.exit(1)}let r=fe.filter(n=>n.version>t);for(let n of r){console.log(`
|
|
48
|
-
Running migration v${String(n.version).padStart(3,"0")}...`);let s=`v${String(n.version).padStart(3,"0")}`,l=`.pre-${s}.backup`;try{
|
|
257
|
+
Running migration v${String(n.version).padStart(3,"0")}...`);let s=`v${String(n.version).padStart(3,"0")}`,l=`.pre-${s}.backup`;try{fn(Ce,n.version),fn(Ae,n.version)}catch(i){console.error(`
|
|
49
258
|
[FATAL] Pre-migration backup failed for ${s}: ${i.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
50
259
|
`),process.exit(1)}let a=n.module;try{await a.up(Ce,Ae)}catch(i){console.error(`
|
|
51
|
-
[FATAL] Migration ${s} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let u=
|
|
260
|
+
[FATAL] Migration ${s} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let u=ds(l);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
52
261
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
53
262
|
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
54
|
-
`)}process.exit(1)}try{let i=new Date().toISOString(),u={version:n.version,name:a.NAME||s,appliedAt:i},c=
|
|
263
|
+
`)}process.exit(1)}try{let i=new Date().toISOString(),u={version:n.version,name:a.NAME||s,appliedAt:i},c=dn();c.version=n.version,c.migratedAt=i,c.migrations=c.migrations||[],c.migrations.push(u),rs(c)}catch(i){console.error(`
|
|
55
264
|
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${i.message}`),console.error(` Your data is in the v${n.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
56
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{
|
|
57
|
-
\u2713 Schema is now at v${
|
|
58
|
-
`)}var
|
|
265
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Mt()}catch{}try{on()}catch{}to=!0,no(),console.log(`
|
|
266
|
+
\u2713 Schema is now at v${ge}
|
|
267
|
+
`)}var ss=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function is(e){let t=e.toLowerCase();return ss.some(o=>o.test(t))}var ls=6e4;function as(){let e=Date.now(),t=[];for(let o of[ce,Ce,Ae]){if(!$.existsSync(o))continue;let r;try{r=$.readdirSync(o)}catch{continue}for(let n of r){if(!is(n))continue;let s=F.join(o,n);try{let l=$.statSync(s);if(!l.isFile()||e-l.mtimeMs<ls)continue;t.push({dir:o,file:n,fullPath:s})}catch{}}}return t}function cs({verbose:e=!1}={}){let t=as();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{$.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${F.basename(r.dir)}/${r.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${r.fullPath}: ${n.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function us(){let e=[];for(let t of[Ce,Ae]){if(!$.existsSync(t))continue;let o=$.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=F.join(t,r);try{vt(n)}catch(s){e.push({dir:F.basename(t),file:r,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ds(e){let t=[],o=[];for(let s of[Ce,Ae]){if(!$.existsSync(s))continue;let l=$.readdirSync(s).filter(a=>a.endsWith(e));for(let a of l){let i=F.join(s,a),u=a.slice(0,-e.length),c=F.join(s,u);try{u.toLowerCase().endsWith(".json")?vt(i):$.accessSync(i,$.constants.R_OK),t.push({backupPath:i,originalPath:c,fileName:a,dir:s})}catch(d){o.push(`${F.basename(s)}/${a}: ${d.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:s,originalPath:l,fileName:a,dir:i}of t)try{yn(s,l),r++}catch(u){n.push(`${F.basename(i)}/${a}: ${u.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function yn(e,t){let o=t+".tmp";try{$.copyFileSync(e,o),mn(o)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,t)}catch(r){try{$.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let n=new Error(`File locked: ${t} (${r.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw n.code=r.code,n}throw r}}import"dotenv/config";import*as le from"fs";import*as be from"path";import{fileURLToPath as ms}from"url";import"dotenv/config";function fs(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 ps({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?` ${fs(n)}`:"",i=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${u} \u2014 ${i} \u2014 ${l}${a}`}async function gn({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=`**${ps({scriptName:e,mode:t,status:o,error:n,duration:s})}**
|
|
59
268
|
|
|
60
269
|
${r.join(`
|
|
61
|
-
`)}`;try{await we.addMessage(l,i)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var
|
|
62
|
-
--- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(c){if(Ue(c))await vt(e,`pass-${r} navigation: ${c.message?.slice(0,80)}`);else throw c}await g(3e3)}let n=k.submitted,s=k.cdpRecoveries+k.browserRestarts,l=!0,a=!0;for(;l&&a;){if(!await mn(e.page)){await vt(e,"liveness probe failed twice");continue}try{await io(e.page,t);let f=await Ts(e.page,In,us);a=f.keepGoing;let d=f.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(d.length),!a)break;l=await fs(e.page),e._pageRecoveryStreak=0}catch(f){if(!Ue(f))throw f;await vt(e,`mid-iteration: ${f.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let i=k.submitted-n,u=k.cdpRecoveries+k.browserRestarts-s;if(i===0){if(u>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${u} CDP recover${u===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${i} new jobs in pass ${r}.`)}}async function Sn(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return Mo(e,t,o,r)}async function kn(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 hs(e,t){try{let o=await Uo(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},Ge("recruiters-from-jobs",o)?($t++,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($t).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}`),me(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){ut(o.profileUrl,n),Fe(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=o.fromJob?.companyUrl;s&&Ht(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 xt(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 Tn(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 vn(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 u=i.innerText?.trim();if(u==="Continue applying"||u==="Got it"||u==="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 u=i.innerText?.trim();if(u==="Easy Apply"||u==="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(u=>u.disabled,r))return await xt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(u=>u.tagName==="A",r)){await e.evaluate(u=>u.click(),r),await g(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 g(2e3)}}else await r.click(),await g(1500);return await xt(e)?(await Tn(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await xt(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function ys(e){return await e.evaluate(async()=>{function t(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let u=document.querySelector("#interop-outlet")?.shadowRoot;return u&&(i=u.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"),u=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),c=a.querySelectorAll('input[type="radio"]'),f=a.querySelector("select[data-test-text-entity-list-form-select]"),d=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(d),i&&u)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&c.length){let h=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,m=Array.from(c).map(y=>{let $=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:$||y.value}}),b=m.map(y=>y.label);return{type:"radio",labelText:h,errorMsgText:s,options:b,optionsData:m}}else if(f){let h=a.querySelector('label[for="'+f.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),m=h?h.querySelector("span:nth-of-type(2)")?.textContent.trim():null,b=Array.from(f.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:m,errorMsgText:s,options:b}}else if(d){let h=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:h}}else{if(p)return{type:"datePicker",errorMsgText:s};{let h=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 b=Array.from(m).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:h,errorMsgText:s,options:b}}else return null}}}return null})}async function gs(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 u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let c=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},f=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),f(p),await new Promise(h=>setTimeout(h,100)),c(p)})(i)}}return null},t,o)}async function bs(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"]'),u=n;if(r.optionsData){let c=r.optionsData.find(f=>f.label.toLowerCase()===n.toLowerCase());c&&(u=c.value,console.log(`Radio: matched label "${n}" to value "${u}"`))}for(let c of i){let d=(document.querySelector(`label[for="${c.id}"]`)||c.nextElementSibling)?.textContent?.trim()||"";if(c.value.toLowerCase()===u.toLowerCase()||d.toLowerCase()===n.toLowerCase()){c.checked=!0;let p=new Event("change",{bubbles:!0});c.dispatchEvent(p),console.log(`Radio selected: value="${c.value}", label="${d}"`);break}}}return null},t,o)}async function ws(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 u=Array.from(i.options),c=u.find(d=>d.text.toLowerCase()===n.toLowerCase())||u.find(d=>d.text.toLowerCase().includes(n.toLowerCase()));c?i.value=c.value:i.value=n;let f=new Event("change",{bubbles:!0});i.dispatchEvent(f)}return null},t,o)}async function Ss(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(u=>{if(u.nextElementSibling.textContent.trim()===n.trim()){u.checked=!0;let c=new Event("change",{bubbles:!0});u.dispatchEvent(c)}})}return null},t,o)}async function ks(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 u(c,f,d){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let h=new Blob([new Uint8Array(f)]),m=new File([h],d,{type:"application/pdf"}),b=new DataTransfer;b.items.add(m),c.files=b.files;let y=new Event("change",{bubbles:!0});c.dispatchEvent(y)}await u(i,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function xn(e){let t=await ys(e);if(t===null)return null;if(t?.type==="input"){let n=await Ct(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await gs(e,t,n)}else if(t?.type==="radio"){let n=await tt(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 tt(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 bs(e,t,n)}else if(t?.type==="select"){let n=await Je(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 Je(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 ws(e,t,n)}else if(t?.type==="checkbox"){let n=await Je(t.labelText,t.options);t.answer=n,await Ss(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 ks(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 vs(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]"),u=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),c=r.querySelector('input[type="file"]');if(n&&l&&a.length===0){let f=n.textContent.trim();t.push({type:"input",labelText:f,answer:l.value,isRequired:s,wasPreFilled:!!l.value})}else if(n&&a.length){let f=n?n.querySelector("span:nth-of-type(1)")?.textContent.trim():null,d=Array.from(a).map(h=>h.value),p=(Array.from(a).find(h=>h.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:f,options:d,answer:p,isRequired:s,wasPreFilled:!!p})}else if(i){let f=r.querySelector('label[for="'+i.id+'"]')||r.querySelector(".fb-dash-form-element__label-title--is-required"),d=f?.querySelector("span:nth-of-type(2)")?.textContent.trim()||f?.querySelector('span[aria-hidden="true"]')?.textContent.trim()||f?.querySelector("span")?.textContent.trim()||f?.textContent?.trim()||null,p=Array.from(i.options).map(m=>m.value).filter(m=>m!=="Select an option"),h=i.value!=="Select an option"?i.value:"";t.push({type:"select",labelText:d,options:p,answer:h,isRequired:s,wasPreFilled:!!h})}else if(u.length>0){let f=r.querySelector("legend span")?.textContent?.trim(),d=Array.from(u).map(m=>({label:m.nextElementSibling?.textContent?.trim()||m.value,checked:m.checked})),p=d.some(m=>m.checked),h=d.filter(m=>m.checked).map(m=>m.label).join(", ");t.push({type:"checkbox",labelText:f,options:d.map(m=>m.label),answer:h,isRequired:s,wasPreFilled:p})}else if(c){let f=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:f,answer:c.value?"uploaded":"",isRequired:s,wasPreFilled:!!c.value})}}return t})}async function lo(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 u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r==="City"||r==="Location (city)"){let c=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},f=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),f(p),await new Promise(h=>setTimeout(h,100)),c(p)})(i)}return!0}}return!1},t,o)}async function xs(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 c=(n||"").toLowerCase();for(let f of a){let d=f.getRootNode(),h=(f.id&&d.querySelector(`label[for="${f.id}"]`)||f.nextElementSibling)?.textContent?.trim()||"";if(f.value.toLowerCase()===c||h.toLowerCase()===c)return f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function $s(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 c=Array.from(a.options),f=(n||"").toLowerCase(),d=c.find(p=>p.text.toLowerCase()===f)||c.find(p=>p.value.toLowerCase()===f)||c.find(p=>p.text.toLowerCase().includes(f));return d?(a.value=d.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function Es(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 c=!1;for(let f of i){let d=(f.nextElementSibling?.textContent||f.value||"").trim().toLowerCase();l.includes(d)&&!f.checked&&(f.checked=!0,f.dispatchEvent(new Event("change",{bubbles:!0})),c=!0)}return c}return!1},t,o)}async function Cs(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 Ct(o.labelText,"");else if(o.type==="radio")r=await tt(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await Je(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 lo(e,o.labelText,r):o.type==="radio"?n=await xs(e,o.labelText,r):o.type==="select"?n=await $s(e,o.labelText,r):o.type==="checkbox"&&(n=await Es(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 $n(e,t){let o=[],r=!0,n=0,s=null,l=0;for(;r;){if(n++,await xt(e))return console.log(" Daily limit reached during form navigation"),await Tn(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let u=(await vs(e)).filter(p=>!o.some(h=>h.labelText===p.labelText));o.push(...u);try{let p=o.find(m=>m.labelText==="City"||m.labelText==="Location (city)"),h=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 lo(e,p.labelText,m),p.answer=m}else if(h){let m=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!h.answer||h.answer!==m)&&(await g(1e4),await lo(e,h.labelText,m),h.answer=m,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Cs(e,u)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let c=null;try{c=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(c!==null){if(c.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:c};let p=c&&o.find(m=>m.errorMsgText&&m.labelText===c.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(c,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:c};let h=o.findIndex(m=>m.labelText===c.labelText&&!m.answer);h!==-1&&o.splice(h,1),o.push(c)}let f=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of p){let m=h.querySelectorAll("button");for(let b of m){let y=b.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return b.click(),y}}return null});f&&console.log(` Dismissed safety popup (${f})`);let d=await e.evaluate(async()=>{function p(w){let E=document.querySelector(w);if(E)return E;let P=document.querySelector("#interop-outlet")?.shadowRoot;return P?P.querySelector(w):null}function h(w){let E=document.querySelectorAll(w),P=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...E||[],...P||[]]}let m=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),b=h('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||h("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),S=async()=>{let w=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(E=>E.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},$=()=>{let w=h("button").find(E=>E.innerText?.trim()==="Review");w&&w.click()};return m?(await S(),{type:"next"}):b?(await $(),{type:"review"}):y?{type:"submit"}:{type:null}});if(d==null)return{filledFields:o,formPages:n,skip:!0};if(d.type&&console.log(` \u2192 ${d.type}`),d.type===null){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of h){let b=m.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of b){let S=y.innerText||"";if(S.includes("application was sent")||S.includes("resume into a profile")||S.includes("Application submitted")||S.includes("Next best action"))for(let $ of y.querySelectorAll("button")){let w=$.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return $.click(),w}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await g(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(l===0){let h=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),b=[],y=[];for(let S of m){for(let w of S.querySelectorAll("button")){let E=w.innerText?.trim();E&&E.length<60&&b.push(E)}let $=S.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');$&&y.push($.innerText?.slice(0,200))}return{buttons:b.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(h.buttons)}`),h.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(h.modalText)}`)}}if(d.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(c===null&&d.type===s?l++:l=0,s=d.type,l>=5){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),m=[],b=[];for(let y of h){for(let S of y.querySelectorAll(".artdeco-inline-feedback__message"))m.push(S.textContent?.trim()?.slice(0,60));for(let S of y.querySelectorAll(".fb-dash-form-element")){let $=S.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=S.querySelector("input, select, textarea"),E=!!S.querySelector(".artdeco-inline-feedback__message");$&&(E||w&&!w.value)&&b.push({label:$.slice(0,40),hasError:E,value:w?.value?.slice(0,20)||""})}}return{errors:m,emptyRequired:b.slice(0,5)}});return console.error(` \u26A0 Stuck on "${d.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_${d.type}`}}}await g(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function En(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 As(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 _s(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 g(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function kt(e){try{await e.waitForSelector('button[aria-label="Dismiss"]',{timeout:1e4});let t=await e.$('button[aria-label="Dismiss"]');t?(await t.click(),console.log("Popup \u0437\u0430\u043A\u0440\u044B\u0442!"),await g(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 so(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 g(500))}catch{console.log("No discard confirmation needed")}}async function In(e,t){let o=[],r=t._fromQueue;try{k.attempted++,console.log(`
|
|
63
|
-
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&
|
|
270
|
+
`)}`;try{await we.addMessage(l,i)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var hs=ms(import.meta.url),ys=be.dirname(be.dirname(hs)),ro=process.env.DATA_DIR?be.resolve(process.env.DATA_DIR,"collected-profiles"):be.join(ys,"collected-profiles"),so=be.join(ro,"run-log.json");function gs(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";le.writeFileSync(r,o);for(let n=0;n<3;n++)try{le.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 bn(){try{if(!le.existsSync(so))return{runs:[]};let e=JSON.parse(le.readFileSync(so,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function wn(e){le.existsSync(ro)||le.mkdirSync(ro,{recursive:!0});try{gs(so,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Sn(e,t="default"){let o=bn();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),wn(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function kn(e,t,o=null,r=null){if(!e)return;let n=null;try{let l=bn(),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(u=>u.script===e.script&&u.status==="running"&&u.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)}wn(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";gn({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 vn from"fs";import bs from"path";var ws="cookies.json";function Ss(){let e=process.env.ILML_SCOPE_DIR;return e?bs.join(e,"plugins-state","linkedin","cookies.json"):ws}function io(){let e=Ss();if(!vn.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=vn.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}Te();async function xt(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 Ue(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 xn(e,t=3e3){if(!e||e.isClosed?.())return!1;try{return await xt(e.evaluate(()=>1),t,"liveness"),!0}catch{return!1}}async function $n(e,{timeoutMs:t=3e3,retryDelayMs:o=5e3}={}){return await xn(e,t)?!0:(await g(o),await xn(e,t))}async function En(e,t=3e3){if(!e||!e.isConnected?.())return!1;try{return await xt(Promise.resolve(e.version()),t,"browser-version"),!0}catch{return!1}}async function Cn(e,t,{returnUrl:o,gotoTimeoutMs:r=6e4,cookiesProvider:n=null,setupPage:s=null}={}){try{await xt(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 An(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 xt(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 hn();var _t=0,vs=process.env.FUNNEL_USE_CUSTOM_MESSAGE==="true",xs=parseInt(process.env.FUNNEL_MAX_CONNECTIONS||"20",10),$s=process.env.FUNNEL_MESSAGE||"Hi {name}, I just applied for a position at your company and would love to connect!",lo=process.env.FUNNEL_EXCLUDE_LOCATIONS?process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(e=>e.trim()).filter(Boolean):[],$t=-1;async function Es(){if($t===-1){let e=await Re("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}"`);$t=wo(e)+1,console.log(`lastIndex initialized as: ${$t}`)}return $t++}var qn=process.env.MAX_APPLY_FOR_RUN;console.log(`maxRunIndex is: ${qn}`);var Cs=[{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}],rt={};function Pn(e){return Cs.find(t=>t.match(e))||null}function As(e){return rt[e]=(rt[e]||0)+1,rt[e]}function Tn(){for(let e of Object.keys(rt))rt[e]=0}var ao=0;function _s(){return ao++,ao>=qn?(console.log(`Max run counter reached with ${ao}`),!1):!0}async function Ts(e){let t=await Wo(e)}async function Is(e){return Yo(e,{easyApplyOnly:!0})}async function Rs(e){return Ko(e)}async function fo(e,t){return Ht(e,t)}var co=3,Ds=2;async function Ct(e,t){let{searchUrl:o,launchFn:r,setupPage:n,cookiesProvider:s}=e.recoveryCtx,l=await En(e.browser);if(!l||e._pageRecoveryStreak>=co){if(S.browserRestarts>=Ds)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?`${co} page recoveries in a row`:"browser-level CDP dead";console.log(`\u{1F504} Restarting browser (${i}). Reason: ${t}`);let u=await An(e.browser,{launchFn:r,setupPage:n,cookiesProvider:s,returnUrl:o});e.browser=u.browser,e.page=u.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}/${co}). Reason: ${t}`),e.page=await Cn(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 Ls(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(`
|
|
271
|
+
--- Pass ${r}/${o}: re-checking for new jobs ---`);try{await e.page.goto(t,{waitUntil:"domcontentloaded",timeout:6e4})}catch(c){if(Ue(c))await Ct(e,`pass-${r} navigation: ${c.message?.slice(0,80)}`);else throw c}await g(3e3)}let n=S.submitted,s=S.cdpRecoveries+S.browserRestarts,l=!0,a=!0;for(;l&&a;){if(!await $n(e.page)){await Ct(e,"liveness probe failed twice");continue}try{await fo(e.page,t);let d=await Ys(e.page,Mn,Ts);a=d.keepGoing;let f=d.jobsDone;if(console.log("keepGoing",a),console.log("pageDone"),console.log(f.length),!a)break;l=await Rs(e.page),e._pageRecoveryStreak=0}catch(d){if(!Ue(d))throw d;await Ct(e,`mid-iteration: ${d.message?.slice(0,80)}`)}}if(console.log(`Scraping pass ${r} complete.`),!a)break;let i=S.submitted-n,u=S.cdpRecoveries+S.browserRestarts-s;if(i===0){if(u>0&&r<o){console.log(`No new jobs applied in pass ${r}, but ${u} CDP recover${u===1?"y":"ies"} \u2014 pass ${r+1} will retry.`);continue}console.log("No new jobs applied in this pass \u2014 done.");break}console.log(`Applied ${i} new jobs in pass ${r}.`)}}async function In(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL;return Qo(e,t,o,r)}async function Rn(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 js(e,t){try{let o=await zo(e);if(o&&o.profileUrl){o.fromJob={title:t.jobTitle,company:t.companyName,url:t.href},Ge("recruiters-from-jobs",o)?(_t++,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(_t).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}`),he(o.profileUrl,{name:o.name,source:"recruiters-from-jobs"});let n=t.href?.match(/jobs\/view\/(\d+)/)?.[1];if(n){mt(o.profileUrl,n),Pe(o.profileUrl,{source:"job-apply",jobId:n,jobTitle:t.title||null,jobCompany:t.companyName||null,action:"recruiter_found"});let s=o.fromJob?.companyUrl;s&&Kt(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 At(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 On(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 Dn(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 u=i.innerText?.trim();if(u==="Continue applying"||u==="Got it"||u==="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 u=i.innerText?.trim();if(u==="Easy Apply"||u==="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(u=>u.disabled,r))return await At(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1,reason:"button_disabled"};if(await e.evaluate(u=>u.tagName==="A",r)){await e.evaluate(u=>u.click(),r),await g(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 g(2e3)}}else await r.click(),await g(1500);return await At(e)?(await On(e),{clicked:!1,dailyLimitReached:!0}):{clicked:!0}}return await At(e)?{clicked:!1,dailyLimitReached:!0}:{clicked:!1}}async function Ns(e){return await e.evaluate(async()=>{function t(){let i=document.querySelectorAll(".artdeco-inline-feedback__message");if(i.length>0)return i;let u=document.querySelector("#interop-outlet")?.shadowRoot;return u&&(i=u.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"),u=a.querySelector(".artdeco-text-input--input")||a.querySelector("input#"+a.querySelector('label[for^="single-typeahead-entity-form-component-formElement-urn-li-jobs-applyformcommon-easyApplyFormElement"][class*="fb-dash-form-element__label-title--is-required"]')?.getAttribute("for")),c=a.querySelectorAll('input[type="radio"]'),d=a.querySelector("select[data-test-text-entity-list-form-select]"),f=n.parentElement.parentElement.querySelector('input[type="file"]'),p=a.querySelector(".artdeco-datepicker");if(console.log("fileInput"),console.log(f),i&&u)return{type:"input",labelText:i.textContent.trim(),errorMsgText:s};if(i&&c.length){let h=i?i.querySelector("span:nth-of-type(1)")?.textContent.trim():null,m=Array.from(c).map(y=>{let v=(document.querySelector(`label[for="${y.id}"]`)||y.nextElementSibling)?.textContent?.trim();return{value:y.value,label:v||y.value}}),b=m.map(y=>y.label);return{type:"radio",labelText:h,errorMsgText:s,options:b,optionsData:m}}else if(d){let h=a.querySelector('label[for="'+d.id+'"]')||a.querySelector(".fb-dash-form-element__label-title--is-required"),m=h?h.querySelector("span:nth-of-type(2)")?.textContent.trim():null,b=Array.from(d.options).map(y=>y.value).filter(y=>y!=="Select an option");return{type:"select",labelText:m,errorMsgText:s,options:b}}else if(f){let h=n.parentElement.parentElement.querySelector("label")?.textContent.trim();return{type:"file",errorMsgText:s,labelText:h}}else{if(p)return{type:"datePicker",errorMsgText:s};{let h=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 b=Array.from(m).map(y=>y.nextElementSibling.textContent.trim());return{type:"checkbox",labelText:h,errorMsgText:s,options:b}}else return null}}}return null})}async function Fs(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 u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r.labelText=="City"||r.labelText=="Location (city)"){console.log("City/Location typeahead");let c=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),c(p)})(i)}}return null},t,o)}async function qs(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"]'),u=n;if(r.optionsData){let c=r.optionsData.find(d=>d.label.toLowerCase()===n.toLowerCase());c&&(u=c.value,console.log(`Radio: matched label "${n}" to value "${u}"`))}for(let c of i){let f=(document.querySelector(`label[for="${c.id}"]`)||c.nextElementSibling)?.textContent?.trim()||"";if(c.value.toLowerCase()===u.toLowerCase()||f.toLowerCase()===n.toLowerCase()){c.checked=!0;let p=new Event("change",{bubbles:!0});c.dispatchEvent(p),console.log(`Radio selected: value="${c.value}", label="${f}"`);break}}}return null},t,o)}async function Ps(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 u=Array.from(i.options),c=u.find(f=>f.text.toLowerCase()===n.toLowerCase())||u.find(f=>f.text.toLowerCase().includes(n.toLowerCase()));c?i.value=c.value:i.value=n;let d=new Event("change",{bubbles:!0});i.dispatchEvent(d)}return null},t,o)}async function Os(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(u=>{if(u.nextElementSibling.textContent.trim()===n.trim()){u.checked=!0;let c=new Event("change",{bubbles:!0});u.dispatchEvent(c)}})}return null},t,o)}async function Ms(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 u(c,d,f){if(!(await fetch(pdfUrl)).ok)throw new Error("Network response was not ok");let h=new Blob([new Uint8Array(d)]),m=new File([h],f,{type:"application/pdf"}),b=new DataTransfer;b.items.add(m),c.files=b.files;let y=new Event("change",{bubbles:!0});c.dispatchEvent(y)}await u(i,n,process.env.RESUME_FILENAME||"Resume.pdf")}return null},t,o)}async function Ln(e){let t=await Ns(e);if(t===null)return null;if(t?.type==="input"){let n=await Rt(t.labelText,t.errorMsgText);n=n?.trim()||n,t.answer=n,await Fs(e,t,n)}else if(t?.type==="radio"){let n=await st(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 st(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 qs(e,t,n)}else if(t?.type==="select"){let n=await Ve(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 Ve(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 Ps(e,t,n)}else if(t?.type==="checkbox"){let n=await Ve(t.labelText,t.options);t.answer=n,await Os(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 Ms(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 Us(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]"),u=r.querySelectorAll('fieldset[data-test-checkbox-form-component] input[type="checkbox"]'),c=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,f=Array.from(a).map(h=>h.value),p=(Array.from(a).find(h=>h.checked)||{}).value?.toLowerCase()??"";t.push({type:"radio",labelText:d,options:f,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"),f=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"),h=i.value!=="Select an option"?i.value:"";t.push({type:"select",labelText:f,options:p,answer:h,isRequired:s,wasPreFilled:!!h})}else if(u.length>0){let d=r.querySelector("legend span")?.textContent?.trim(),f=Array.from(u).map(m=>({label:m.nextElementSibling?.textContent?.trim()||m.value,checked:m.checked})),p=f.some(m=>m.checked),h=f.filter(m=>m.checked).map(m=>m.label).join(", ");t.push({type:"checkbox",labelText:d,options:f.map(m=>m.label),answer:h,isRequired:s,wasPreFilled:p})}else if(c){let d=r.querySelector("label")?.textContent?.trim();t.push({type:"file",labelText:d,answer:c.value?"uploaded":"",isRequired:s,wasPreFilled:!!c.value})}}return t})}async function po(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 u=new Event("input",{bubbles:!0});if(i.dispatchEvent(u),r==="City"||r==="Location (city)"){let c=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"Enter",keyCode:13,which:13});p.dispatchEvent(h)},d=p=>{let h=new KeyboardEvent("keydown",{bubbles:!0,cancelable:!0,key:"ArrowDown",keyCode:40,which:40});p.dispatchEvent(h)};await(async p=>{await new Promise(h=>setTimeout(h,500)),d(p),await new Promise(h=>setTimeout(h,100)),c(p)})(i)}return!0}}return!1},t,o)}async function Bs(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 c=(n||"").toLowerCase();for(let d of a){let f=d.getRootNode(),h=(d.id&&f.querySelector(`label[for="${d.id}"]`)||d.nextElementSibling)?.textContent?.trim()||"";if(d.value.toLowerCase()===c||h.toLowerCase()===c)return d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}return!1},t,o)}async function Js(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 c=Array.from(a.options),d=(n||"").toLowerCase(),f=c.find(p=>p.text.toLowerCase()===d)||c.find(p=>p.value.toLowerCase()===d)||c.find(p=>p.text.toLowerCase().includes(d));return f?(a.value=f.value,a.dispatchEvent(new Event("change",{bubbles:!0})),!0):!1}return!1},t,o)}async function Vs(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 c=!1;for(let d of i){let f=(d.nextElementSibling?.textContent||d.value||"").trim().toLowerCase();l.includes(f)&&!d.checked&&(d.checked=!0,d.dispatchEvent(new Event("change",{bubbles:!0})),c=!0)}return c}return!1},t,o)}async function Hs(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 Rt(o.labelText,"");else if(o.type==="radio")r=await st(o.labelText,o.options||[]);else if(o.type==="select"||o.type==="checkbox")r=await Ve(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 po(e,o.labelText,r):o.type==="radio"?n=await Bs(e,o.labelText,r):o.type==="select"?n=await Js(e,o.labelText,r):o.type==="checkbox"&&(n=await Vs(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 jn(e,t){let o=[],r=!0,n=0,s=null,l=0;for(;r;){if(n++,await At(e))return console.log(" Daily limit reached during form navigation"),await On(e),{filledFields:o,formPages:n,skip:!0,dailyLimitReached:!0};let u=(await Us(e)).filter(p=>!o.some(h=>h.labelText===p.labelText));o.push(...u);try{let p=o.find(m=>m.labelText==="City"||m.labelText==="Location (city)"),h=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 po(e,p.labelText,m),p.answer=m}else if(h){let m=process.env.CV_TEXT||"Check my CV or ask my personal assistant any question about me on iLiveMyLife";(!h.answer||h.answer!==m)&&(await g(1e4),await po(e,h.labelText,m),h.answer=m,console.log("CV set to link"))}}catch{console.log("Exception parsing trim?")}try{await Hs(e,u)}catch(p){console.error(` \u26A0 fillOptionalFields failed: ${p.message?.slice(0,100)}`)}let c=null;try{c=await t(e)}catch(p){return console.error(` \u26A0 fillErrorsWithAnswers failed: ${p.message?.slice(0,100)}`),{filledFields:o,formPages:n,skip:!0}}if(c!==null){if(c.type==="datePicker")return{filledFields:o,formPages:n,skip:!0,duplicateField:c};let p=c&&o.find(m=>m.errorMsgText&&m.labelText===c.labelText);if(p)return console.log("Duplicated error question detected"),console.log("Duplicate field details:",JSON.stringify(c,null,2)),console.log("Previous attempt:",JSON.stringify(p,null,2)),{filledFields:o,formPages:n,skip:!0,duplicateField:c};let h=o.findIndex(m=>m.labelText===c.labelText&&!m.answer);h!==-1&&o.splice(h,1),o.push(c)}let d=await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let h of p){let m=h.querySelectorAll("button");for(let b of m){let y=b.innerText?.trim();if(y==="Continue applying"||y==="Got it"||y==="Dismiss")return b.click(),y}}return null});d&&console.log(` Dismissed safety popup (${d})`);let f=await e.evaluate(async()=>{function p(w){let E=document.querySelector(w);if(E)return E;let q=document.querySelector("#interop-outlet")?.shadowRoot;return q?q.querySelector(w):null}function h(w){let E=document.querySelectorAll(w),q=document.querySelector("#interop-outlet")?.shadowRoot?.querySelectorAll(w);return[...E||[],...q||[]]}let m=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(w=>w.innerText?.trim()==="Next"),b=h('footer[role="presentation"] button').some(w=>w.innerText.trim()==="Review")||h("button").some(w=>w.innerText.trim()==="Review"&&w.getAttribute("aria-label")?.includes("Review")),y=p('button[aria-label="Submit application"]'),k=async()=>{let w=p("button[data-easy-apply-next-button]")||p('button[aria-label="Continue to next step"]')||h("footer button, button.artdeco-button--primary").find(E=>E.innerText?.trim()==="Next");w?w.click():console.log("Next button not found")},v=()=>{let w=h("button").find(E=>E.innerText?.trim()==="Review");w&&w.click()};return m?(await k(),{type:"next"}):b?(await v(),{type:"review"}):y?{type:"submit"}:{type:null}});if(f==null)return{filledFields:o,formPages:n,skip:!0};if(f.type&&console.log(` \u2192 ${f.type}`),f.type===null){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let m of h){let b=m.querySelectorAll('[role="dialog"], div.artdeco-modal');for(let y of b){let k=y.innerText||"";if(k.includes("application was sent")||k.includes("resume into a profile")||k.includes("Application submitted")||k.includes("Next best action"))for(let v of y.querySelectorAll("button")){let w=v.innerText?.trim();if(w==="Not now"||w==="Done"||w==="Dismiss"||w==="Got it")return v.click(),w}}}return null});if(p)return console.log(` Dismissed stale popup (${p}) \u2014 need to re-open Easy Apply`),await g(1500),{filledFields:o,formPages:n,skip:!1,stalePopupDismissed:!0};if(l===0){let h=await e.evaluate(()=>{let m=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),b=[],y=[];for(let k of m){for(let w of k.querySelectorAll("button")){let E=w.innerText?.trim();E&&E.length<60&&b.push(E)}let v=k.querySelector('.jobs-easy-apply-modal, .jobs-easy-apply-content, [role="dialog"]');v&&y.push(v.innerText?.slice(0,200))}return{buttons:b.slice(0,15),modalText:y.slice(0,2)}});console.log(` DEBUG null actionType \u2014 buttons: ${JSON.stringify(h.buttons)}`),h.modalText.length&&console.log(` DEBUG modal text: ${JSON.stringify(h.modalText)}`)}}if(f.type==="submit")return{filledFields:o,formPages:n,skip:!1};if(c===null&&f.type===s?l++:l=0,s=f.type,l>=5){let p=await e.evaluate(()=>{let h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean),m=[],b=[];for(let y of h){for(let k of y.querySelectorAll(".artdeco-inline-feedback__message"))m.push(k.textContent?.trim()?.slice(0,60));for(let k of y.querySelectorAll(".fb-dash-form-element")){let v=k.querySelector(".artdeco-text-input--label, legend span, label span")?.textContent?.trim(),w=k.querySelector("input, select, textarea"),E=!!k.querySelector(".artdeco-inline-feedback__message");v&&(E||w&&!w.value)&&b.push({label:v.slice(0,40),hasError:E,value:w?.value?.slice(0,20)||""})}}return{errors:m,emptyRequired:b.slice(0,5)}});return console.error(` \u26A0 Stuck on "${f.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_${f.type}`}}}await g(1500),r=!0}return{filledFields:o,formPages:n,skip:!1}}async function Nn(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 Gs(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 Ws(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 g(1e3)):console.log(" No post-apply popup found (Done/Not now)")}catch(t){console.log("closeApplicationSentPopup: "+t.message)}}async function Et(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 g(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 uo(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 g(500))}catch{console.log("No discard confirmation needed")}}async function Mn(e,t){let o=[],r=t._fromQueue;try{S.attempted++,console.log(`
|
|
272
|
+
--- Processing: ${t.jobTitle} at ${t.companyName} ---`);let n=t.id?.match(/\d+/)?.[0];if(n&&sn(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 f=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(),h=f.split(" ")[0],m=p.split(" ")[0];if(h&&m&&!f.includes(m)&&!p.includes(h))return S.mismatch++,console.log(` \u2298 MISMATCH: expected company "${t.companyName}" but panel shows "${f}"`),console.log(` job title: "${t.jobTitle}"`),{keepGoing:!0};if(await e.evaluate(()=>{let y=document.querySelector(".jobs-details__main-content, .job-details-jobs-unified-top-card");if(!y)return!1;let k=y.innerText;return/Applied\s+\d+\s+(second|minute|hour|day|week|month)s?\s+ago/i.test(k)||k.includes("Application submitted")}))return S.alreadyApplied++,console.log(` \u2298 ALREADY APPLIED (LinkedIn): ${t.jobTitle} \u2014 skipping`),n&&Me(n,"applied",{source:"detected"}),{keepGoing:!0};try{s=await Xo(e)}catch{}}let l=await Dn(e);if(l.dailyLimitReached){console.log(`
|
|
64
273
|
========================================`),console.log("LinkedIn daily application limit reached!"),console.log(`========================================
|
|
65
|
-
`);let
|
|
274
|
+
`);let f=De("recruiters-from-jobs");return console.log(`\u{1F4CA} Recruiters collected today: ${f.total}`),console.log(` - This session: ${_t}`),console.log(` - Unprocessed: ${f.unprocessed}`),S.dailyLimitHit=!0,{keepGoing:!1,dailyLimitReached:!0,recruitersSummary:f}}if(!l.clicked)return S.noApplyButton++,console.log(` \u2298 NO APPLY BUTTON: ${t.jobTitle} @ ${t.companyName}`),{keepGoing:!0};await Nn(e);let a=await Es();console.log(`Applying for job: ${t.id}`);let i=`### Job Information
|
|
66
275
|
- **Counter:** ${a}
|
|
67
276
|
- **Job Title:** ${t.jobTitle}
|
|
68
277
|
- **Company:** ${t.companyName}
|
|
69
278
|
- **Location:** ${t.location}
|
|
70
279
|
- **Salary:** ${t.salary}
|
|
71
|
-
- **Job URL:** ${t.href}`,u=process.env.NODE_EASY_APPLY_MAIN;await we.addMessage(u,i,{lifebot:
|
|
72
|
-
Closing browser...`);try{await o.close()}catch{}process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i);let u=await o.newPage();await l(u);let c=
|
|
280
|
+
- **Job URL:** ${t.href}`,u=process.env.NODE_EASY_APPLY_MAIN;await we.addMessage(u,i,{lifebot:_n.off});let c=await Re("Should I apply for this job? Answer only 'yes' or 'no'!!");if(Tn(),console.log(`Should I apply for ${t.jobTitle} ?? `+c),c.toLowerCase()==="no"){S.skippedByLifebot++,console.log(` \u2298 SKIPPED by Lifebot: ${t.jobTitle} @ ${t.companyName}`),await Et(e),await uo(e),await Rn(e,t.id);let f=t.id?.match(/\d+/)?.[0];return Oe({jobId:f,jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"skipped_by_lifebot",questions:[]}),Me(f,"skipped",{reason:"lifebot_rejected",source:"apply"}),{keepGoing:!0}}console.log("Starting processNavigation...");let d=await jn(e,Ln);if(d.stalePopupDismissed&&(console.log(" Retrying pressApplyButton after stale popup..."),(await Dn(e)).clicked?d=await jn(e,Ln):(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 Et(e),{keepGoing:!1,dailyLimitReached:!0};if(d.skip){if(await Et(e),await uo(e),d.duplicateField){await Rn(e,t.id);let f=process.env.NODE_EASY_APPLY_ERRORS;await we.addMessage(f,`${t.href} failed at label ${d.duplicateField?.labelText}`,{lifebot:_n.off})}S.failed++,console.log(` \u2717 FAILED: ${t.jobTitle} @ ${t.companyName} \u2014 ${d.duplicateField?.labelText||"form error"}`),Oe({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 Nn(e),await Gs(e),await g(2e3),await Ws(e),S.submitted++,console.log(` \u2713 APPLIED: ${t.jobTitle} @ ${t.companyName} (${d.formPages} pages, ${o.length} fields)`);let f=t.id?.match(/\d+/)?.[0];if(f&&(pt(f,{title:t.jobTitle,company:t.companyName,location:t.location,salary:t.salary,url:t.href,applied:!0}),nn(f,{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}),Me(f,"applied",{source:"easy-apply"}),s?.companyUrl&&Kt(s.companyUrl,{name:s.companyName||t.companyName,about:s.aboutCompany,size:s.companySize,industries:s.industries,jobId:f})),await js(e,t),Oe({jobId:t.id?.match(/\d+/)?.[0],jobTitle:t.jobTitle,jobCompany:t.companyName,jobUrl:t.href,result:"submitted",formPages:d.formPages,questions:o}),!_s())return{keepGoing:!1}}}catch(n){if(Ue(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=Pn(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=As(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 Et(e)}catch{}try{await uo(e)}catch{}}return l>=s.maxConsecutive?(console.log(`\u274C [${s.label}] ${s.maxConsecutive} consecutive \u2014 stopping.`),{keepGoing:!1}):(s.cooldownMs&&await g(s.cooldownMs),{keepGoing:!0})}return Tn(),{keepGoing:!0}}async function Ys(e,t,o){let r=process.env.LINKEDIN_SEARCH_URL,n=[],s=0;for(;;){await fo(e,r)&&(await te(e),await g(2e3));try{await e.waitForSelector("li.scaffold-layout__list-item",{timeout:3e4})}catch{}await o(e);let a=await Is(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 fo(e,r);continue}let u=await e.evaluate(()=>({totalCards:document.querySelectorAll("li.scaffold-layout__list-item").length,hasListContainer:!!document.querySelector(".jobs-search-results-list, .scaffold-layout__list-container")}));u.totalCards===0?console.log(` \u26A0 No job cards on page (container present: ${u.hasListContainer}). Either the search returned nothing, the page never finished loading, or LinkedIn changed its markup.`):console.log(` ${u.totalCards} job card(s) on page but none are Easy Apply \u2014 nothing to apply to with this search filter.`);break}if(s=0,n.length===0){n=a;let{keepGoing:i}=await In(e,a,t);if(!i)return{keepGoing:!1,jobsDone:n}}else{let i=a.filter(c=>!n.some(d=>d.id===c.id));if(console.log(` New jobs on page: ${i.length} (page: ${a.length}, total seen: ${n.length})`),i.length===0)break;let{keepGoing:u}=await In(e,i,t);if(n=[...n,...i],!u)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=Sn("apply",e?"queue":"search"),o=null,r=null,n=[],s=async()=>ks.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),l=async i=>{await i.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},a=()=>io();try{o=await s();let i=async()=>{console.log(`
|
|
281
|
+
Closing browser...`);try{await o.close()}catch{}process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i);let u=await o.newPage();await l(u);let c=io();await u.setCookie(...c);let d=process.argv.find(_=>_.startsWith("--job-urls=")),f=d?d.split("=").slice(1).join("=").replace(/^@/,""):null,p=process.env.LINKEDIN_SEARCH_URL,h=f?"https://www.linkedin.com/feed/":p;try{await u.goto(h,{waitUntil:"domcontentloaded",timeout:6e4})}catch(_){console.error("\u274C Navigation error:",_.message),console.log("Trying to continue anyway..."),await g(5e3)}let m=u.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 b=De("recruiters-from-jobs");b.total>0&&console.log(`
|
|
73
282
|
\u{1F4C2} Existing recruiters for today: ${b.total} (${b.unprocessed} unprocessed)
|
|
74
|
-
`),await g(2e3);let y={page:u,browser:o,recoveryCtx:{searchUrl:p,launchFn:s,setupPage:l,cookiesProvider:a}},
|
|
75
|
-
\u{1F4CB} Queue mode: ${_.length} jobs from ${
|
|
76
|
-
`);for(let
|
|
77
|
-
[${
|
|
78
|
-
Queue complete. ${
|
|
79
|
-
Queue done. Continuing with standard search...`);try{await u.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3)}catch(_){console.error(" Navigation to search failed:",_.message)}}y.page=u,y.browser=o;try{await
|
|
80
|
-
\u274C Apply phase ended: CDP channel could not be recovered after ${
|
|
283
|
+
`),await g(2e3);let y={page:u,browser:o,recoveryCtx:{searchUrl:p,launchFn:s,setupPage:l,cookiesProvider:a}},k=!1;if(f)try{let _=JSON.parse(Fn.readFileSync(f,"utf-8"));console.log(`
|
|
284
|
+
\u{1F4CB} Queue mode: ${_.length} jobs from ${f}
|
|
285
|
+
`);for(let B=0;B<_.length;B++){let T=typeof _[B]=="string"?{url:_[B]}:_[B],P=T.url,x=T.title||"Unknown",M=T.company||"";console.log(`
|
|
286
|
+
[${B+1}/${_.length}] ${x} @ ${M}`),console.log(` ${P}`),u=y.page,o=y.browser;try{let j=P.match(/jobs\/view\/(\d+)/)?.[1]||"";console.log(" Navigating to job page..."),await u.goto(P,{waitUntil:"domcontentloaded",timeout:6e4}),await g(8e3);let R=await u.evaluate(()=>{let pe=document.body.innerText;return{hasApply:!!document.querySelector('.jobs-apply-button, a[aria-label*="Easy Apply"]'),alreadyApplied:pe.includes("Application submitted"),noLongerAccepting:pe.includes("No longer accepting applications")}});if(R.alreadyApplied){console.log(" Already applied \u2014 skipping"),S.alreadyApplied++,Me(j,"applied",{applyMethod:"detected"});continue}if(R.noLongerAccepting){console.log(" No longer accepting \u2014 marking as expired"),S.expired++,Me(j,"expired",{reason:"no_longer_accepting"});continue}if(!R.hasApply){console.log(" No Easy Apply button \u2014 skipping"),S.noApplyButton++;continue}let G={id:`/jobs/view/${j}/`,href:P,jobTitle:x,companyName:M,location:T.location||"",salary:T.salary||null,_fromQueue:!0};console.log(" Calling jobProcessorFunc...");let z=await Mn(u,G);if(console.log(` Result: keepGoing=${z.keepGoing}, reason=${z.dailyLimitReached?"daily_limit":"ok"}`),!z.keepGoing){console.log(" Daily limit reached \u2014 stopping queue."),k=!0;break}}catch(j){if(Ue(j))try{await Ct(y,`queue job ${B+1}: ${j.message?.slice(0,80)}`),u=y.page,o=y.browser}catch(R){console.error(`\u274C Queue mode: CDP recovery failed: ${R.message}`),console.error(" Aborting queue, falling back to standard search if possible.");break}else{let R=Pn(j);if(R?.severity==="fatal"){console.error(`\u274C [${R.label}] Fatal \u2014 stopping queue: ${(j.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: ${j.message?.slice(0,80)}`)}}}console.log(`
|
|
287
|
+
Queue complete. ${k?"Daily limit hit.":"Continuing to search..."}`)}catch(_){console.error(`Failed to read job URLs file: ${_.message}`)}if(!k){if(f){console.log(`
|
|
288
|
+
Queue done. Continuing with standard search...`);try{await u.goto(p,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3)}catch(_){console.error(" Navigation to search failed:",_.message)}}y.page=u,y.browser=o;try{await Ls(y)}catch(_){Ue(_)||/CDP unrecoverable/.test(_.message||"")?(console.error(`
|
|
289
|
+
\u274C Apply phase ended: CDP channel could not be recovered after ${S.cdpRecoveries} page recoveries and ${S.browserRestarts} browser restarts.`),console.error(` Last error: ${_.message}`)):/Session expired/i.test(_.message||"")?(console.error(`
|
|
81
290
|
\u274C Apply phase ended: ${_.message}`),r=_):console.error(`
|
|
82
|
-
\u26A0 Apply phase crashed: ${_.message}`)}u=y.page,o=y.browser}let
|
|
83
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let _ of n)console.log(` ${_}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let
|
|
84
|
-
\u26A0 Skipping recruiter funnel \u2014 ${
|
|
85
|
-
--- Funnel: today's recruiters (${E.unprocessed}) ---`),
|
|
86
|
-
--- Funnel: backfill from previous days (${T.length} unprocessed) ---`),console.log(` Quota remaining: ${
|
|
291
|
+
\u26A0 Apply phase crashed: ${_.message}`)}u=y.page,o=y.browser}let v=S.submitted+S.skippedByLifebot+S.failed+S.mismatch+S.alreadyApplied+S.expired+S.noApplyButton,w=S.attempted-v,E=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: ${_t}`),n.push(`Recruiters total: ${E.total} (${E.unprocessed} unprocessed)`),console.log(`
|
|
292
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SESSION SUMMARY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let _ of n)console.log(` ${_}`);console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let 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",W=!D;W||(console.log(`
|
|
293
|
+
\u26A0 Skipping recruiter funnel \u2014 ${D}.`),console.log(` ${E.unprocessed} recruiters saved for next run.`),n.push(`Funnel: skipped (${D})`));let{markProfileProcessed:C}=await Promise.resolve().then(()=>(jt(),$o)),{canSendConnection:N,getQuotaStatus:Y}=await Qe().then(()=>Bo),U=()=>({message:$s,useCustomMessage:vs,maxConnections:xs,excludeLocations:lo,source:"recruiters-from-jobs",viewOnly:!1,onProfileProcessed:async(_,B,T)=>{C("recruiters-from-jobs",_.profileUrl,{status:T.reason,connectionSent:T.connectionSent,withCustomMessage:T.withCustomMessage,message:T.messageSent,method:T.method,reason:T.reason,error:T.error,profileInfo:T.profileInfo},_._fromDate||null)}});if(W&&E.unprocessed>0){console.log(`
|
|
294
|
+
--- Funnel: today's recruiters (${E.unprocessed}) ---`),lo.length>0&&console.log(` Excluding locations: ${lo.join(", ")}`);let _=lt("recruiters-from-jobs");await Vt(u,_,U())}let ae=N();if(W&&ae.allowed){let _=at("recruiters-from-jobs"),B=new Date().toISOString().split("T")[0],T=_.filter(P=>P._fromDate!==B);if(T.length>0){let P=Y();console.log(`
|
|
295
|
+
--- Funnel: backfill from previous days (${T.length} unprocessed) ---`),console.log(` Quota remaining: ${P.daily.remaining} today, ${P.weekly.remaining} this week`),await Vt(u,T,{...U(),maxConnections:P.daily.remaining})}}let H=Y();console.log(`
|
|
87
296
|
\u2705 Funnel done. Quota: ${H.daily.remaining}/${H.daily.max} today, ${H.weekly.remaining}/${H.weekly.max} this week`),n.push(`Funnel quota: ${H.daily.remaining}/${H.daily.max} today, ${H.weekly.remaining}/${H.weekly.max} week`)}catch(i){r=i,console.error(`
|
|
88
|
-
\u274C Apply session ended with error: ${i.message}`),i.stack&&console.error(i.stack)}
|
|
297
|
+
\u274C Apply session ended with error: ${i.message}`),i.stack&&console.error(i.stack)}kn(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)})();
|