ilml-plugin-linkedin 1.20.18 → 1.20.19
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 +6 -1
- package/dist/applyQueue.mjs +18 -20
- package/dist/connect.mjs +72 -74
- package/dist/daily.mjs +27 -29
- package/dist/enrichProfiles.mjs +26 -28
- package/dist/funnelRunner.mjs +41 -42
- package/dist/messageBot.mjs +56 -58
- package/dist/run.mjs +28 -30
- package/dist/scout.mjs +42 -44
- package/dist/syncAll.mjs +74 -76
- package/dist/syncConnections.mjs +30 -32
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +36 -38
- package/dist/visit.mjs +33 -35
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/scout.mjs
CHANGED
|
@@ -1,61 +1,59 @@
|
|
|
1
|
-
var
|
|
1
|
+
var oo=Object.defineProperty;var pe=(t,e)=>{for(var o in e)oo(t,o,{get:e[o],enumerable:!0})};import wo from"puppeteer";import{addExtra as ko}from"puppeteer-extra";import vo from"puppeteer-extra-plugin-stealth";import _ from"fs";import U from"path";var no="cookies.json";function ve(){let t=process.env.ILML_SCOPE_DIR;return t?U.join(t,"plugins-state","linkedin","cookies.json"):no}function ro(){let t=ve(),e=U.dirname(t);return e&&e!=="."&&!_.existsSync(e)&&_.mkdirSync(e,{recursive:!0}),t}function qe(t){let e=ro();return _.writeFileSync(e,JSON.stringify(t)),e}function Be(){let t=ve();if(!_.existsSync(t))throw new Error(`Cookies not found at ${t}. Run: ilml linkedin login`);let e;try{e=_.readFileSync(t,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${t}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(e)}catch{throw new Error(`Cookies file at ${t} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${t} is empty or not an array. Run: ilml linkedin login`);return o}function Je(){return _.existsSync(ve())}function so(){let t=process.env.ILML_SCOPE_DIR;return t?U.join(t,"plugins-state","linkedin"):"."}function He(t){let e=String(t||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(e)?e:"default"}function io(){let t=process.env.MY_LINKEDIN_URL,e=t&&t.match(/\/in\/([^/?#]+)/);return e&&e[1]?He(e[1]):"default"}function We(t){let e=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(e)return _.existsSync(e)||_.mkdirSync(e,{recursive:!0}),U.resolve(e);let o=He(t||io()),r=U.join(so(),"chrome-profile",o);return _.existsSync(r)||_.mkdirSync(r,{recursive:!0}),U.resolve(r)}var Ge=".ilml-seeded";function Ve(t){return!_.existsSync(U.join(t,Ge))}function Ke(t){try{_.writeFileSync(U.join(t,Ge),new Date().toISOString())}catch{}}function Ye(t){let e=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{_.rmSync(U.join(t,o),{force:!0}),e++}catch{}return e}async function j(t){let e=Math.floor(Math.random()*2001),o=t+e;return new Promise(r=>setTimeout(r,o))}async function ze(t,e,{timeout:o=45e3,poll:r=1e3,label:n="page"}={}){let i=Date.now();for(;Date.now()-i<o;){try{if(await t.evaluate(c=>!!document.querySelector(c),e)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${n})`),!0}}catch{}await new Promise(s=>setTimeout(s,r))}return!1}var Qe=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function de(t){return Qe.test(t||"")}async function Xe(t,{credentialWaitMs:e=36e4,label:o="page"}={}){console.log(` \u26A0 Auth wall on ${o} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await t.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let r=!!(process.stdin&&process.stdin.isTTY),n=r?e:Math.min(e,45e3),i=Date.now(),s=!1;for(;Date.now()-i<n;){let l="wait";try{l=await t.evaluate(a=>!new RegExp(a).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",Qe.source)}catch{}if(l==="in"){try{let a=await t.cookies();if(Array.isArray(a)&&a.some(m=>m.name==="li_at")){let m=qe(a);console.log(` \u2713 Session recovered \u2014 re-saved ${a.length} cookies (${m}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(a){console.log(` \u2713 Session recovered (cookie re-save skipped: ${a.message}).`)}return!0}if(l==="creds"){if(!r){let a=new Error(`Session expired (${o}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}s||(s=!0,console.log(`
|
|
2
2
|
\u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
|
|
3
|
-
`))}await new Promise(a=>setTimeout(a,2500))}let c=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}import{getPluginConfig as
|
|
4
|
-
`).map(x=>x.trim()).filter(Boolean).filter(x=>x&&x!==w),T=A[0]||null,L=A.find(x=>x!==T&&/\((Remote|Hybrid|On-?site)\)|,\s*[A-Za-z]/.test(x))||A[1]||null,te=(f.match(/\$[\d,]+[^\n]*?(?:\/yr|\/hr|per year|per hour|K\b)|[\d,]+\s*(?:CAD|USD|EUR|GBP)[^\n]*?\/(?:hr|yr)/i)||[])[0]||null,Z=/Easy Apply/i.test(f);l.push({id:y?`https://www.linkedin.com/jobs/view/${y}/`:null,href:y?`https://www.linkedin.com/jobs/view/${y}/`:null,jobId:y,cardIndex:u,isEasyApply:Z,isApplied:/(^|\s)Applied(\s|$)/.test(f),applyType:Z?"easy-apply":"external",jobTitle:w||null,companyName:T,location:L,salary:te||null,under10Applicants:/Under 10 applicants/i.test(f),activelyReviewing:/Actively reviewing/i.test(f),promoted:/Promoted/i.test(f),postedText:(f.match(/Posted[^\n]*/i)||[])[0]||null})}),{ui:"new",jobs:l}}),r=o.jobs||[];return o.ui==="new"?t?r.filter(n=>n.isEasyApply):r:t?r.filter(n=>n.isEasyApply&&n.href):r.filter(n=>n.href)}async function yt(e){let t=()=>parseInt((e.url().match(/[?&]start=(\d+)/)||[])[1]||"0",10),o=t(),r=await e.evaluate(()=>{let n=[...document.querySelectorAll('button[aria-label^="Page "]')],i=a=>parseInt((a.getAttribute("aria-label")||"").replace(/[^\d]/g,""),10),s=n.find(a=>a.getAttribute("aria-current")==="true"||a.getAttribute("aria-current")==="page");if(s){let a=i(s),u=n.find(m=>i(m)===a+1);return u&&!u.disabled?(u.scrollIntoView({block:"center"}),u.click(),{clicked:!0,to:`page ${a+1}`}):{clicked:!1,reason:`last page (${a})`}}let c=[...document.querySelectorAll("button")].find(a=>(/^Next$/i.test((a.innerText||"").trim())||/view next|next page/i.test(a.getAttribute("aria-label")||""))&&!a.disabled&&a.offsetParent!==null);if(c)return c.scrollIntoView({block:"center"}),c.click(),{clicked:!0,to:"next"};let l=document.querySelector('button[aria-label="View next page"], .jobs-search-pagination__button--next');return l&&!l.disabled?(l.click(),{clicked:!0,to:"legacy-next"}):{clicked:!1,reason:"No next page button found"}});if(!r.clicked)return console.log(" Pagination:",r.reason),!1;for(let n=0;n<16&&(await j(500),t()===o);n++);return await j(1500),t()===o?(console.log(" Pagination: clicked but page did not advance \u2014 stopping"),!1):(console.log(` Pagination \u2192 ${r.to}`),!0)}async function gt(e,t){let o=e.url();if(!de(o)&&o.includes("/jobs/"))return!1;if(de(o)){if(!await Xe(e,".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list",{timeout:45e3,label:"job search"})&&de(e.url())&&await et(e,{label:"job search"}),e.url().includes("/jobs/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await j(2e3)),!e.url().includes("/jobs/"))throw new Error(`Session expired \u2014 could not return to job search (landed on ${e.url().slice(0,60)}). Run: ilml linkedin login`);return!0}console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3);let r=e.url();if(!r.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${r.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function St(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),c=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:c?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let c=s.textContent?.trim();if(c&&c.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(c))return{name:c,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function bt(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let W of i){let ke=W.querySelector(".job-criteria__subheader")?.textContent?.trim(),Be=W.querySelector(".job-criteria__text")?.textContent?.trim();ke&&Be&&(n[ke.toLowerCase()]=Be)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],c=[];for(let W of s)new RegExp("\\b"+W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&c.push(W.replace(/\\\+/g,"+"));let a=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,m=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"),d=f?.innerText?.trim()||null,y=(f?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,S=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",T=S.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,L=S.match(/(\d[\d,]*)\s+applicant/i),te=L?parseInt(L[1].replace(/,/g,"")):null,Z=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),x=Array.from(Z).map(W=>W.innerText?.trim()?.replace(/\s+/g," ")),we=x.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,J=x.join(" ")+" "+S,to=/\bremote\b/i.test(J)?"remote":/\bhybrid\b/i.test(J)?"hybrid":/\bon-?site\b/i.test(J)?"onsite":null,oo=/\bcontract\b/i.test(J)?"contract":/\bfull-?time\b/i.test(J)?"full-time":/\bpart-?time\b/i.test(J)?"part-time":/\bfreelance\b/i.test(J)?"freelance":/\btemporary\b/i.test(J)?"temporary":null,Ue=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",fe=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",P=(Ue+" "+r+" "+fe).toLowerCase(),F=Ue.toLowerCase(),h=[];/\bremote\b/.test(P)&&h.push("remote"),/\bhybrid\b/.test(P)&&h.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(P)&&h.push("onsite"),(h.length===0||!h.includes("remote")&&!h.includes("hybrid")&&!h.includes("onsite"))&&/remote/i.test(fe)&&h.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(F)&&h.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(F)&&h.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(F)&&!h.includes("managerial")&&h.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(F)?h.push("junior"):/\b(senior|sr\.?)\b/i.test(F)?h.push("senior"):/\b(staff|principal|distinguished)\b/i.test(F)?h.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(F)?h.push("executive"):/\b(lead|team lead)\b/i.test(F)&&h.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(P)&&h.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(P)&&h.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(P)&&h.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(P)&&h.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(P)&&h.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(P)&&h.push("mobile"),/\b(architect)\b/i.test(F)&&h.push("architect"),/\b(consultant|consulting)\b/i.test(F)&&h.push("consultant");let qe=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(qe)||/\bcontract\b/i.test(P))&&h.push("contract"),/full.?time|permanent/i.test(qe)&&h.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(fe)&&h.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(fe)&&h.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&h.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:m,companyName:d,companyUrl:y?y.startsWith("/")?"https://www.linkedin.com"+y:y:null,aboutCompany:a,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:T,applicantCount:te,companySize:we,workplaceType:to,contractType:oo,techStack:[...new Set(c)],jobTags:[...new Set(h)]}})}import"dotenv/config";import*as $ from"fs";import*as C from"path";import{fileURLToPath as _o}from"url";function wt(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let o=t[1].trim();return o?`https://www.linkedin.com/in/${o}/`:null}var Eo=_o(import.meta.url),xo=C.dirname(C.dirname(Eo)),Y=process.env.DATA_DIR?C.resolve(process.env.DATA_DIR,"market-research"):C.join(xo,"market-research"),kt=C.join(Y,"scouted-jobs.json"),vt=C.join(Y,"discovered-people.json"),jo=C.join(Y,"visit-log.json"),At=C.join(Y,"companies.json"),Cr=C.join(Y,"job-decisions.json");function Ee(){$.existsSync(Y)||$.mkdirSync(Y,{recursive:!0})}function xe(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";$.writeFileSync(r,o);for(let n=0;n<3;n++)try{$.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function ye(e){try{if($.existsSync(e))return JSON.parse($.readFileSync(e,"utf-8"))}catch{}return null}function _t(){re=null,Co=null,se=null,ie=null,K=null}var re=null;function ge(){return re||(re=ye(kt)||{},re)}function Et(e,t){if(!e)return;Ee();let o=ge(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,i]of Object.entries(t))i!=null&&(o[e][n]=i);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{xe(kt,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var Co=null;var se=null;function xt(){return se||(se=ye(vt)||{},se)}function he(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function To(e,t){let o=wt(t)||t;if(e[o])return o;let r=he(t);if(!r)return o;let n=null;for(let[i,s]of Object.entries(e)){if(he(s&&(s.canonicalUrl||s.profileUrl)||i)===r)return i;!n&&s&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}return n||o}function jt(e,t){if(!e)return;Ee();let o=xt(),r=new Date().toISOString().slice(0,10),n=To(o,e),i=he(e);if(o[n]){let s=o[n];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&he(s.canonicalUrl||s.profileUrl||n)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[n]={canonicalUrl:n,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{xe(vt,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}var ie=null;function $o(){return ie||(ie=ye(At)||{},ie)}function Ct(e,t){if(!e)return;Ee();let o=$o(),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{xe(At,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var K=null;function Io(){return K||(K=ye(jo)||{visits:[]},Array.isArray(K.visits)||(K.visits=[]),K)}function Tt(){let e=ge(),t=xt(),o=Object.values(e),r=Object.values(t),n={};for(let f of o)f.company&&(n[f.company]=(n[f.company]||0)+1);let i=Object.entries(n).sort((f,d)=>d[1]-f[1]).slice(0,5).map(([f,d])=>`${f} (${d})`),s={};for(let f of o)for(let d of f.techStack||[])s[d]=(s[d]||0)+1;let c=Object.entries(s).sort((f,d)=>d[1]-f[1]).slice(0,8).map(([f,d])=>`${f} (${d})`),l=Io(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(f=>f.date.startsWith(a)).length,m=new Set(l.visits.map(f=>f.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:c,totalVisited:m,todayVisited:u,lastScoutDate:o.length>0?o.sort((f,d)=>(d.scoutedAt||"").localeCompare(f.scoutedAt||""))[0]?.scoutedAt:null}}import"dotenv/config";import*as k from"fs";import*as v from"path";import{fileURLToPath as Ro}from"url";var Do=Ro(import.meta.url),Oo=v.dirname(v.dirname(Do)),q=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"collected-profiles"):v.join(Oo,"collected-profiles"),No=v.join(q,"people.json"),Lo=v.join(q,"jobs.json"),Dr=v.join(q,"quota.json"),Or=v.join(q,"conversations.json"),Nr=v.join(q,"sync-state.json"),Lr=v.join(q,"application-questions.json"),Pr=v.join(q,"profile-history"),$t=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},Fr=$t(process.env.CONNECT_MAX_DAILY,20),Mr=$t(process.env.CONNECT_MAX_WEEKLY,100),ce=null,le=null,Po=null,Fo=null,Mo=null,Uo=null;function It(){ce=null,le=null,Po=null,Fo=null,Mo=null,Uo=null}function Rt(){k.existsSync(q)||k.mkdirSync(q,{recursive:!0})}function Dt(e,t){if(!k.existsSync(e))return null;try{let o=JSON.parse(k.readFileSync(e,"utf-8"));try{k.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(k.existsSync(r))try{let n=JSON.parse(k.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{k.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{k.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ot(){return ce||(Rt(),ce=Dt(No,"people.json")||{},ce)}function Nt(){return le||(Rt(),le=Dt(Lo,"jobs.json")||{},le)}import"dotenv/config";import*as I from"fs";import*as H from"path";import{fileURLToPath as Wo}from"url";import"dotenv/config";import{createGraphClient as qo,resolveToken as Bo}from"@ilivemylife/graph-sdk";import{config as Jo}from"dotenv";Jo();var Lt=Bo()||process.env.TOKEN;Lt||(console.error(`
|
|
3
|
+
`))}await new Promise(a=>setTimeout(a,2500))}let c=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}import{getPluginConfig as ao}from"@ilivemylife/graph-sdk";var co={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},Ze=t=>/^(1|true|yes|on)$/i.test(String(t??"").trim());function lo(t){return String(t??"").split(/[,\s|]+/).map(e=>e.trim()).filter(Boolean)}function et(t=process.env){let e=(t.JOB_SEARCH_KEYWORDS||"").trim();if(!e)return null;let o=new URLSearchParams;o.set("keywords",e);let r=(t.JOB_SEARCH_LOCATION||"").trim();r&&o.set("location",r);let n=(t.JOB_SEARCH_GEO_ID||"").trim();n&&o.set("geoId",n);let i=parseInt(t.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(i)&&i>0&&o.set("distance",String(i)),Ze(t.JOB_SEARCH_EASY_APPLY)&&o.set("f_AL","true"),Ze(t.JOB_SEARCH_IN_NETWORK)&&o.set("f_JIYN","true");let s=lo(t.JOB_SEARCH_COMPANY_IDS);s.length&&o.set("f_C",s.join(","));let c=(t.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&o.set("f_TPR",co[c]||c),o.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let l="https://www.linkedin.com/jobs/search/?"+o.toString(),a=(t.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(l+="&"+a),l}var uo=await ao();for(let[t,e]of Object.entries(uo))process.env[t]===void 0&&(process.env[t]=e);var tt=et(process.env);tt&&(process.env.LINKEDIN_SEARCH_URL=tt);var fo=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),nr=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),po=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]));import Ae from"fs";import mo from"path";var ho={headless:!1,defaultViewport:null,protocolTimeout:3e5},ne=new Set,ot=!1;async function me(){let t=[...ne].map(e=>{try{return Promise.resolve(e.close()).catch(()=>{})}catch{return Promise.resolve()}});ne.clear(),await Promise.race([Promise.all(t),new Promise(e=>setTimeout(e,5e3))])}function yo(){if(ot)return;ot=!0;let t=e=>async()=>{await me(),process.exit(e)};process.once("SIGINT",t(130)),process.once("SIGTERM",t(143)),process.once("SIGHUP",t(129)),process.once("uncaughtException",async e=>{await me(),console.error(e&&e.stack||e),process.exit(1)}),process.once("unhandledRejection",async e=>{await me(),console.error(e),process.exit(1)}),process.stdout.on("error",async e=>{e&&e.code==="EPIPE"&&(await me(),process.exit(0))}),process.on("exit",()=>{for(let e of ne)try{let o=e.process&&e.process();o&&o.kill("SIGKILL")}catch{}})}function _e(t){return mo.join(t,".ilml-browser-session.json")}function it(t,e={}){try{Ae.writeFileSync(_e(t),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...e}))}catch{}}function go(t,e){try{let o=e.wsEndpoint&&e.wsEndpoint();it(t,o?{wsEndpoint:o}:{})}catch{}}function So(t){let e=ct(t);e&&e.ownerPid===process.pid&&oe(t)}function oe(t){try{Ae.rmSync(_e(t),{force:!0})}catch{}}function ct(t){try{return JSON.parse(Ae.readFileSync(_e(t),"utf-8"))}catch{return null}}function nt(t){if(!t||t===process.pid)return!0;try{return process.kill(t,0),!0}catch(e){return!e||e.code!=="ESRCH"}}function rt(t,e,o){let r,n=new Promise(s=>{r=setTimeout(()=>s(o),e)}),i=Promise.resolve(t).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s});return Promise.race([i,n])}async function st(t,e,{probeTimeoutMs:o=4e3}={}){let r=ct(e);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&nt(r.ownerPid)?"live":(oe(e),"free");let n=Symbol("timeout"),i=t.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await rt(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return oe(e),"free";if(nt(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await rt(s.close().then(()=>!0).catch(()=>!1),o,!1))return oe(e),"free";try{s.disconnect()}catch{}return"live"}function bo(t,e){t&&(yo(),ne.add(t),t.on("disconnected",()=>{ne.delete(t),e&&oe(e)}))}async function lt(t,e={}){let o=We(),r={...ho,...e,userDataDir:o},n=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await st(t,o)==="live")throw new Error(n);it(o);let i;try{i=await t.launch(r)}catch{if(await st(t,o)==="live")throw new Error(n);Ye(o);try{i=await t.launch(r)}catch(c){throw So(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return bo(i,o),go(o,i),{browser:i,profileDir:o,needsSeed:Ve(o)}}async function at(t,e){if(!e||!e.needsSeed)return!1;if(!Je())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await t.setCookie(...Be()),Ke(e.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var ut=ko(wo);ut.use(vo());async function ft(){let{browser:t,profileDir:e,needsSeed:o}=await lt(ut),r=await t.newPage();return await r.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await at(r,{profileDir:e,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:t,page:r}}async function pt(t){let e=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await t.evaluate(async r=>{let n=null,i=null;for(let m of r)if(n=document.querySelector(m),n){i=m;break}if(!n){let m=document.querySelector("li.scaffold-layout__list-item");if(m){let f=m.parentElement;for(;f&&f!==document.body;){if(f.scrollHeight>f.clientHeight){n=f,i="parent of li.scaffold-layout__list-item";break}f=f.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,c=300,l=300,a=50,u=0;for(;u<a&&(n.scrollBy(0,c),await new Promise(m=>setTimeout(m,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},e)}async function dt(t,{easyApplyOnly:e=!0}={}){let o=await t.evaluate(()=>{let n=document.querySelectorAll("li.scaffold-layout__list-item");if(n.length)return{ui:"old",jobs:Array.from(n).map(u=>{let f=(u.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),p=u.querySelector("a.job-card-container__link");if(!p)return{isEasyApply:!1};let b=p.getAttribute("href").split("?")[0];return{id:b,isEasyApply:f,applyType:f?"easy-apply":"external",dataId:p.getAttribute("data-control-id"),href:`https://linkedin.com${b}`,jobTitle:u.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),companyName:u.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),location:u.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),salary:u.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim()||null,jobLink:f?p.href:null,cardIndex:null}})};let i=Array.from(document.querySelectorAll('button[aria-label^="Dismiss"]')),s=a=>{let u=a;for(let m=0;m<14&&u&&u.parentElement;m++){u=u.parentElement;let f=u.parentElement;if(!f)break;let b=Array.from(f.children).filter(y=>{try{return y.querySelectorAll('button[aria-label^="Dismiss"]').length===1}catch{return!1}});if(b.length>=5&&b.includes(u))return u}return null},c=new Set,l=[];return i.forEach((a,u)=>{let m=s(a);if(!m||c.has(m))return;c.add(m);let f=m.innerText||"",p=m.matches&&m.matches("[componentkey]")?m:m.querySelector("[componentkey]")||m.closest("[componentkey]"),y=((p&&p.getAttribute("componentkey")||"").match(/(\d{6,})/)||[])[1]||null,w=(a.getAttribute("aria-label")||"").replace(/^Dismiss\s+/,"").replace(/\s+job$/,"").trim(),A=f.split(`
|
|
4
|
+
`).map(x=>x.trim()).filter(Boolean).filter(x=>x&&x!==w),$=A[0]||null,L=A.find(x=>x!==$&&/\((Remote|Hybrid|On-?site)\)|,\s*[A-Za-z]/.test(x))||A[1]||null,te=(f.match(/\$[\d,]+[^\n]*?(?:\/yr|\/hr|per year|per hour|K\b)|[\d,]+\s*(?:CAD|USD|EUR|GBP)[^\n]*?\/(?:hr|yr)/i)||[])[0]||null,Z=/Easy Apply/i.test(f);l.push({id:y?`https://www.linkedin.com/jobs/view/${y}/`:null,href:y?`https://www.linkedin.com/jobs/view/${y}/`:null,jobId:y,cardIndex:u,isEasyApply:Z,isApplied:/(^|\s)Applied(\s|$)/.test(f),applyType:Z?"easy-apply":"external",jobTitle:w||null,companyName:$,location:L,salary:te||null,under10Applicants:/Under 10 applicants/i.test(f),activelyReviewing:/Actively reviewing/i.test(f),promoted:/Promoted/i.test(f),postedText:(f.match(/Posted[^\n]*/i)||[])[0]||null})}),{ui:"new",jobs:l}}),r=o.jobs||[];return o.ui==="new"?e?r.filter(n=>n.isEasyApply):r:e?r.filter(n=>n.isEasyApply&&n.href):r.filter(n=>n.href)}async function mt(t){let e=()=>parseInt((t.url().match(/[?&]start=(\d+)/)||[])[1]||"0",10),o=e(),r=await t.evaluate(()=>{let n=[...document.querySelectorAll('button[aria-label^="Page "]')],i=a=>parseInt((a.getAttribute("aria-label")||"").replace(/[^\d]/g,""),10),s=n.find(a=>a.getAttribute("aria-current")==="true"||a.getAttribute("aria-current")==="page");if(s){let a=i(s),u=n.find(m=>i(m)===a+1);return u&&!u.disabled?(u.scrollIntoView({block:"center"}),u.click(),{clicked:!0,to:`page ${a+1}`}):{clicked:!1,reason:`last page (${a})`}}let c=[...document.querySelectorAll("button")].find(a=>(/^Next$/i.test((a.innerText||"").trim())||/view next|next page/i.test(a.getAttribute("aria-label")||""))&&!a.disabled&&a.offsetParent!==null);if(c)return c.scrollIntoView({block:"center"}),c.click(),{clicked:!0,to:"next"};let l=document.querySelector('button[aria-label="View next page"], .jobs-search-pagination__button--next');return l&&!l.disabled?(l.click(),{clicked:!0,to:"legacy-next"}):{clicked:!1,reason:"No next page button found"}});if(!r.clicked)return console.log(" Pagination:",r.reason),!1;for(let n=0;n<16&&(await j(500),e()===o);n++);return await j(1500),e()===o?(console.log(" Pagination: clicked but page did not advance \u2014 stopping"),!1):(console.log(` Pagination \u2192 ${r.to}`),!0)}async function ht(t,e){let o=t.url();if(!de(o)&&o.includes("/jobs/"))return!1;if(de(o)){if(!await ze(t,".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list",{timeout:45e3,label:"job search"})&&de(t.url())&&await Xe(t,{label:"job search"}),t.url().includes("/jobs/")||(await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await j(2e3)),!t.url().includes("/jobs/"))throw new Error(`Session expired \u2014 could not return to job search (landed on ${t.url().slice(0,60)}). Run: ilml linkedin login`);return!0}console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3);let r=t.url();if(!r.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${r.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function yt(t){return t.evaluate(()=>{let e=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=e.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),c=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:c?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=e.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=e.querySelector(".job-details-people-who-can-help__section--two-pane")||e.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=e.querySelectorAll('a[href*="/in/"]');for(let s of i){let c=s.textContent?.trim();if(c&&c.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(c))return{name:c,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function gt(t){return t.evaluate(()=>{let e=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(e.querySelector(".jobs-description__content")||e.querySelector(".jobs-box__html-content")||e.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=e.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let G of i){let ke=G.querySelector(".job-criteria__subheader")?.textContent?.trim(),Ue=G.querySelector(".job-criteria__text")?.textContent?.trim();ke&&Ue&&(n[ke.toLowerCase()]=Ue)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],c=[];for(let G of s)new RegExp("\\b"+G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&c.push(G.replace(/\\\+/g,"+"));let a=e.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,m=e.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,f=e.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=f?.innerText?.trim()||null,y=(f?.querySelector('a[href*="/company/"]')||e.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,S=e.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",$=S.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,L=S.match(/(\d[\d,]*)\s+applicant/i),te=L?parseInt(L[1].replace(/,/g,"")):null,Z=e.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),x=Array.from(Z).map(G=>G.innerText?.trim()?.replace(/\s+/g," ")),we=x.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,J=x.join(" ")+" "+S,eo=/\bremote\b/i.test(J)?"remote":/\bhybrid\b/i.test(J)?"hybrid":/\bon-?site\b/i.test(J)?"onsite":null,to=/\bcontract\b/i.test(J)?"contract":/\bfull-?time\b/i.test(J)?"full-time":/\bpart-?time\b/i.test(J)?"part-time":/\bfreelance\b/i.test(J)?"freelance":/\btemporary\b/i.test(J)?"temporary":null,Fe=e.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",fe=e.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",P=(Fe+" "+r+" "+fe).toLowerCase(),F=Fe.toLowerCase(),h=[];/\bremote\b/.test(P)&&h.push("remote"),/\bhybrid\b/.test(P)&&h.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(P)&&h.push("onsite"),(h.length===0||!h.includes("remote")&&!h.includes("hybrid")&&!h.includes("onsite"))&&/remote/i.test(fe)&&h.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(F)&&h.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(F)&&h.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(F)&&!h.includes("managerial")&&h.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(F)?h.push("junior"):/\b(senior|sr\.?)\b/i.test(F)?h.push("senior"):/\b(staff|principal|distinguished)\b/i.test(F)?h.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(F)?h.push("executive"):/\b(lead|team lead)\b/i.test(F)&&h.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(P)&&h.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(P)&&h.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(P)&&h.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(P)&&h.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(P)&&h.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(P)&&h.push("mobile"),/\b(architect)\b/i.test(F)&&h.push("architect"),/\b(consultant|consulting)\b/i.test(F)&&h.push("consultant");let Me=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(Me)||/\bcontract\b/i.test(P))&&h.push("contract"),/full.?time|permanent/i.test(Me)&&h.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(fe)&&h.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(fe)&&h.push("usa"),(e.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&h.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:m,companyName:p,companyUrl:y?y.startsWith("/")?"https://www.linkedin.com"+y:y:null,aboutCompany:a,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:$,applicantCount:te,companySize:we,workplaceType:eo,contractType:to,techStack:[...new Set(c)],jobTags:[...new Set(h)]}})}import"dotenv/config";import*as T from"fs";import*as C from"path";import{fileURLToPath as Ao}from"url";function St(t){if(!t||typeof t!="string"||/custom-invite|\/search\//i.test(t)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(t))return null;let e=t.match(/\/in\/([^/?#]+)/i);if(!e||!e[1])return null;let o=e[1].trim();return o?`https://www.linkedin.com/in/${o}/`:null}var _o=Ao(import.meta.url),Eo=C.dirname(C.dirname(_o)),Y=process.env.DATA_DIR?C.resolve(process.env.DATA_DIR,"market-research"):C.join(Eo,"market-research"),bt=C.join(Y,"scouted-jobs.json"),wt=C.join(Y,"discovered-people.json"),xo=C.join(Y,"visit-log.json"),kt=C.join(Y,"companies.json"),Ir=C.join(Y,"job-decisions.json");function Ee(){T.existsSync(Y)||T.mkdirSync(Y,{recursive:!0})}function xe(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";T.writeFileSync(r,o);for(let n=0;n<3;n++)try{T.renameSync(r,t);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function ye(t){try{if(T.existsSync(t))return JSON.parse(T.readFileSync(t,"utf-8"))}catch{}return null}function vt(){re=null,jo=null,se=null,ie=null,K=null}var re=null;function ge(){return re||(re=ye(bt)||{},re)}function At(t,e){if(!t)return;Ee();let o=ge(),r=new Date().toISOString().slice(0,10);if(o[t]){for(let[n,i]of Object.entries(e))i!=null&&(o[t][n]=i);o[t].lastSeen=r}else o[t]={...e,scoutedAt:r,lastSeen:r};try{xe(bt,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var jo=null;var se=null;function _t(){return se||(se=ye(wt)||{},se)}function he(t){let e=String(t||"").match(/\/in\/([^/?#]+)/i);return e?e[1].toLowerCase():null}function Co(t,e){let o=St(e)||e;if(t[o])return o;let r=he(e);if(!r)return o;let n=null;for(let[i,s]of Object.entries(t)){if(he(s&&(s.canonicalUrl||s.profileUrl)||i)===r)return i;!n&&s&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}return n||o}function Et(t,e){if(!t)return;Ee();let o=_t(),r=new Date().toISOString().slice(0,10),n=Co(o,t),i=he(t);if(o[n]){let s=o[n];e.name&&(s.name=e.name),e.title&&(s.title=e.title),e.company&&(s.company=e.company),e.location&&(s.location=e.location),e.role&&(s.role=e.role),e.isConnected!=null&&(s.isConnected=e.isConnected),e.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(e.jobId)||s.jobIds.push(e.jobId)),i&&he(s.canonicalUrl||s.profileUrl||n)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[n]={canonicalUrl:n,aliases:[],name:e.name||null,title:e.title||null,company:e.company||null,location:e.location||null,role:e.role||null,source:e.source||"scout",isConnected:e.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:e.jobId?[e.jobId]:[]};try{xe(wt,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}var ie=null;function $o(){return ie||(ie=ye(kt)||{},ie)}function xt(t,e){if(!t)return;Ee();let o=$o(),r=new Date().toISOString().slice(0,10);if(o[t]){let n=o[t];e.name&&(n.name=e.name),e.about&&(n.about=e.about),e.size&&(n.size=e.size),e.industries&&(n.industries=e.industries),e.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(e.jobId)||n.jobIds.push(e.jobId)),e.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(e.recruiterUrl)||n.recruiterUrls.push(e.recruiterUrl)),n.lastSeen=r,n.jobCount=n.jobIds?.length||0}else o[t]={name:e.name||null,about:e.about||null,size:e.size||null,industries:e.industries||null,discoveredAt:r,lastSeen:r,jobIds:e.jobId?[e.jobId]:[],recruiterUrls:e.recruiterUrl?[e.recruiterUrl]:[],jobCount:e.jobId?1:0};try{xe(kt,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var K=null;function To(){return K||(K=ye(xo)||{visits:[]},Array.isArray(K.visits)||(K.visits=[]),K)}function jt(){let t=ge(),e=_t(),o=Object.values(t),r=Object.values(e),n={};for(let f of o)f.company&&(n[f.company]=(n[f.company]||0)+1);let i=Object.entries(n).sort((f,p)=>p[1]-f[1]).slice(0,5).map(([f,p])=>`${f} (${p})`),s={};for(let f of o)for(let p of f.techStack||[])s[p]=(s[p]||0)+1;let c=Object.entries(s).sort((f,p)=>p[1]-f[1]).slice(0,8).map(([f,p])=>`${f} (${p})`),l=To(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(f=>f.date.startsWith(a)).length,m=new Set(l.visits.map(f=>f.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:c,totalVisited:m,todayVisited:u,lastScoutDate:o.length>0?o.sort((f,p)=>(p.scoutedAt||"").localeCompare(f.scoutedAt||""))[0]?.scoutedAt:null}}import"dotenv/config";import*as k from"fs";import*as v from"path";import{fileURLToPath as Io}from"url";var Ro=Io(import.meta.url),Do=v.dirname(v.dirname(Ro)),q=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"collected-profiles"):v.join(Do,"collected-profiles"),Oo=v.join(q,"people.json"),No=v.join(q,"jobs.json"),Lr=v.join(q,"quota.json"),Pr=v.join(q,"conversations.json"),Fr=v.join(q,"sync-state.json"),Mr=v.join(q,"application-questions.json"),Ur=v.join(q,"profile-history"),Ct=(t,e)=>{let o=parseInt(t,10);return Number.isInteger(o)&&o>=0?o:e},qr=Ct(process.env.CONNECT_MAX_DAILY,20),Br=Ct(process.env.CONNECT_MAX_WEEKLY,100),ce=null,le=null,Lo=null,Po=null,Fo=null,Mo=null;function $t(){ce=null,le=null,Lo=null,Po=null,Fo=null,Mo=null}function Tt(){k.existsSync(q)||k.mkdirSync(q,{recursive:!0})}function It(t,e){if(!k.existsSync(t))return null;try{let o=JSON.parse(k.readFileSync(t,"utf-8"));try{k.copyFileSync(t,t+".backup")}catch{}return o}catch(o){console.error(`[!] ${e} is corrupted: ${o.message}`),console.error(` File: ${v.resolve(t)}`);let r=t+".backup";if(k.existsSync(r))try{let n=JSON.parse(k.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{k.copyFileSync(r,t)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${t}.corrupted`);try{k.copyFileSync(t,t+".corrupted")}catch{}return null}}function Rt(){return ce||(Tt(),ce=It(Oo,"people.json")||{},ce)}function Dt(){return le||(Tt(),le=It(No,"jobs.json")||{},le)}import"dotenv/config";import*as I from"fs";import*as H from"path";import{fileURLToPath as Vo}from"url";import"dotenv/config";import{createGraphClient as Uo,resolveToken as qo}from"@ilivemylife/graph-sdk";import{config as Bo}from"dotenv";Bo();var Ot=qo()||process.env.TOKEN;Ot||(console.error(`
|
|
5
5
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
6
6
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
7
7
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
8
|
-
`),process.exit(1));var
|
|
9
|
-
|
|
10
|
-
${r.join(`
|
|
11
|
-
`)}`;try{await Pt.addMessage(s,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Vo=Wo(import.meta.url),Ko=H.dirname(H.dirname(Vo)),je=process.env.DATA_DIR?H.resolve(process.env.DATA_DIR,"collected-profiles"):H.join(Ko,"collected-profiles"),Ce=H.join(je,"run-log.json");function Yo(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";I.writeFileSync(r,o);for(let n=0;n<3;n++)try{I.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Mt(){try{if(!I.existsSync(Ce))return{runs:[]};let e=JSON.parse(I.readFileSync(Ce,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ut(e){I.existsSync(je)||I.mkdirSync(je,{recursive:!0});try{Yo(Ce,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function qt(e,t="default"){let o=Mt();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),Ut(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Te(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=Mt(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=r,n=c.duration;else{let l=s.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}Ut(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Ft({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as p from"fs";import*as Pe from"os";import*as g from"path";import{fileURLToPath as wn}from"url";var Re={};pe(Re,{NAME:()=>Qo,VERSION:()=>zo,up:()=>en});import*as R from"fs";import*as Se from"path";var zo=1,Qo="normalize-jobs-and-questions",Xo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Zo=50;function $e(e){return R.existsSync(e)?JSON.parse(R.readFileSync(e,"utf-8")):null}function Ie(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{R.writeFileSync(r,o)}catch(n){try{R.unlinkSync(r)}catch{}throw n}try{R.renameSync(r,e)}catch(n){try{R.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function en(e,t){let o=Se.join(e,"jobs.json"),r=Se.join(t,"scouted-jobs.json"),n=Se.join(e,"application-questions.json"),i=$e(o)||{},s=$e(r)||{},c=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let m=s[u],f=i[u];for(let d of Xo)m[d]!=null&&f[d]==null&&(f[d]=m[d]);l.push(u),c++}c>0?(Ie(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=$e(n);if(a&&Array.isArray(a.applications)){let u={},m=0;for(let f of a.applications){let d=f.jobId||"unknown";u[d]||(u[d]={applications:[]});let b=(f.questions||[]).map(y=>{let w={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=Zo?w.options=y.options:(w.optionsOmitted=!0,m++)),y.page&&(w.page=y.page),y.wasPreFilled&&(w.wasPreFilled=!0),y.wasRetry&&(w.wasRetry=!0),w});u[d].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||b.length,questions:b})}Ie(n,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];Ie(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var De={};pe(De,{NAME:()=>on,VERSION:()=>tn,up:()=>sn});import*as D from"fs";import*as Bt from"path";var tn=2,on="reset-unread-flags";function nn(e){return D.existsSync(e)?JSON.parse(D.readFileSync(e,"utf-8")):null}function rn(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{D.writeFileSync(r,o)}catch(n){try{D.unlinkSync(r)}catch{}throw n}try{D.renameSync(r,e)}catch(n){try{D.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function sn(e){let t=Bt.join(e,"conversations.json"),o=nn(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}rn(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Oe={};pe(Oe,{NAME:()=>ln,VERSION:()=>cn,up:()=>dn});import*as O from"fs";import*as Jt from"path";var cn=3,ln="recompute-last-message-by",an=new Set(["draft","confirmed","rejected","needs_review"]);function un(e){return O.existsSync(e)?JSON.parse(O.readFileSync(e,"utf-8")):null}function fn(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{O.writeFileSync(r,o)}catch(n){try{O.unlinkSync(r)}catch{}throw n}try{O.renameSync(r,e)}catch(n){try{O.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function pn(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!an.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function dn(e){let t=Jt.join(e,"conversations.json"),o=un(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,i=0,s=0;for(let c of Object.keys(o)){let l=o[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let a=Array.isArray(l.messages)?l.messages:[],u=pn(a,r),m=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=m,n++}if(n===0){console.log(" No conversations to recompute.");return}fn(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ne={};pe(Ne,{NAME:()=>hn,VERSION:()=>mn,up:()=>bn});import*as N from"fs";import*as Ht from"path";var mn=4,hn="split-connection-timestamps",yn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function gn(e){if(!N.existsSync(e))return null;let t=N.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Sn(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{N.writeFileSync(r,o)}catch(n){try{N.unlinkSync(r)}catch{}throw n}try{N.renameSync(r,e)}catch(n){try{N.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function bn(e){let t=Ht.join(e,"people.json"),o=gn(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,yn.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Sn(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var kn=wn(import.meta.url),vn=g.dirname(kn),An=g.dirname(g.dirname(vn));function _n(e){return e&&(e==="~"?Pe.homedir():e.startsWith("~/")||e.startsWith("~\\")?g.join(Pe.homedir(),e.slice(2)):e)}var M=process.env.DATA_DIR?g.resolve(_n(process.env.DATA_DIR)):An,Q=g.join(M,"collected-profiles"),X=g.join(M,"market-research"),E=g.join(M,".schema-version"),Gt=[g.join(Q,".schema-version"),g.join(X,".schema-version")],G=4,B=[{version:1,module:Re},{version:2,module:De},{version:3,module:Oe},{version:4,module:Ne}];(function(){B.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of B){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=B.length?B[B.length-1].version:0;if(o!==G)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${G}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<B.length;r++){let n=r+1;if(B[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${B[r].version}`)}})();function Yt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
8
|
+
`),process.exit(1));var Nt=Uo({token:Ot});function Jo(t){if(!t||t<1e3)return`${t||0}ms`;let e=Math.round(t/1e3);if(e<60)return`${e}s`;let o=Math.floor(e/60),r=e%60;return r?`${o}m ${r}s`:`${o}m`}var Ho={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function Wo(t){let e=String(t||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(e)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(e)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(e)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(e)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(e)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function Go({scriptName:t,mode:e,status:o,summaryLines:r,error:n,duration:i}){let s=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",c=o==="error"?"stopped early":o==="quota-reached"?"daily limit reached":"done",l=Ho[t]||t,a=e&&e!=="default"?` \xB7 ${e}`:"",u=new Date().toISOString().slice(0,16).replace("T"," "),m=i?` \xB7 ${Jo(i)}`:"",f=[];f.push(`## ${s} ${l} \u2014 ${c}`),f.push(`_${u}${a}${m}_`),f.push("");for(let p of r)f.push(`- ${p}`);if(o==="error"){f.push(""),f.push(`**What happened:** ${Wo(n)}`);let p=String(n||"").replace(/\s+/g," ").trim();p&&f.push(`_Technical detail: ${p.slice(0,140)}_`)}return f.join(`
|
|
9
|
+
`)}async function Lt({scriptName:t,mode:e,status:o,summaryLines:r,error:n,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(r)||r.length===0)return;let c=Go({scriptName:t,mode:e,status:o,summaryLines:r,error:n,duration:i});try{await Nt.addMessage(s,c)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var Ko=Vo(import.meta.url),Yo=H.dirname(H.dirname(Ko)),je=process.env.DATA_DIR?H.resolve(process.env.DATA_DIR,"collected-profiles"):H.join(Yo,"collected-profiles"),Ce=H.join(je,"run-log.json");function zo(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";I.writeFileSync(r,o);for(let n=0;n<3;n++)try{I.renameSync(r,t);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Pt(){try{if(!I.existsSync(Ce))return{runs:[]};let t=JSON.parse(I.readFileSync(Ce,"utf-8"));return!t.runs||!Array.isArray(t.runs)?{runs:[]}:t}catch{return{runs:[]}}}function Ft(t){I.existsSync(je)||I.mkdirSync(je,{recursive:!0});try{zo(Ce,t)}catch(e){console.error(`[!] Failed to save run-log.json: ${e.message}`)}}function Qo(t,e="default"){let o=Pt();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:t,mode:e,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),Ft(o),{script:t,mode:e,startTime:r.getTime(),runIndex:o.runs.length-1}}function Xo(t,e,o=null,r=null){if(!t)return;let n=null;try{let s=Pt(),c=s.runs[t.runIndex];if(c&&c.status==="running"&&c.script===t.script)c.status=e,c.result=e,c.duration=Date.now()-t.startTime,c.stats=o,c.error=r,n=c.duration;else{let l=s.runs.find(a=>a.script===t.script&&a.status==="running"&&a.timestamp===new Date(t.startTime).toISOString());l&&(l.status=e,l.result=e,l.duration=Date.now()-t.startTime,l.stats=o,l.error=r,n=l.duration)}Ft(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=e==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Lt({scriptName:t.script,mode:t.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-t.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}async function Mt(t,e,o,r,n={}){let{rethrow:i=!0}=n,s=Qo(t,e),c={},l=null;try{await o(c)}catch(u){l=u}let a=[];try{let u=r?r(c):[];a=(Array.isArray(u)?u:[]).filter(m=>typeof m=="string"&&m.trim())}catch(u){console.error(`[runLog] summarize threw (report still sent): ${u.message}`)}if(a.length===0&&l&&(a=["(crashed before any progress was recorded)"]),l){let u=e&&e!=="default"?` (${e})`:"";console.error(`
|
|
10
|
+
\u2717 ${t}${u} failed: ${l.message||l}`)}try{Xo(s,l?"error":"success",{...c,summaryLines:a},l?l.message||String(l):null)}catch(u){console.error(`[runLog] endRun failed: ${u.message}`)}if(l&&i)throw l;return c}import"dotenv/config";import*as d from"fs";import*as Le from"os";import*as g from"path";import{fileURLToPath as An}from"url";var Ie={};pe(Ie,{NAME:()=>en,VERSION:()=>Zo,up:()=>nn});import*as R from"fs";import*as Se from"path";var Zo=1,en="normalize-jobs-and-questions",tn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],on=50;function $e(t){return R.existsSync(t)?JSON.parse(R.readFileSync(t,"utf-8")):null}function Te(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";try{R.writeFileSync(r,o)}catch(n){try{R.unlinkSync(r)}catch{}throw n}try{R.renameSync(r,t)}catch(n){try{R.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${t} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function nn(t,e){let o=Se.join(t,"jobs.json"),r=Se.join(e,"scouted-jobs.json"),n=Se.join(t,"application-questions.json"),i=$e(o)||{},s=$e(r)||{},c=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let m=s[u],f=i[u];for(let p of tn)m[p]!=null&&f[p]==null&&(f[p]=m[p]);l.push(u),c++}c>0?(Te(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=$e(n);if(a&&Array.isArray(a.applications)){let u={},m=0;for(let f of a.applications){let p=f.jobId||"unknown";u[p]||(u[p]={applications:[]});let b=(f.questions||[]).map(y=>{let w={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=on?w.options=y.options:(w.optionsOmitted=!0,m++)),y.page&&(w.page=y.page),y.wasPreFilled&&(w.wasPreFilled=!0),y.wasRetry&&(w.wasRetry=!0),w});u[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||b.length,questions:b})}Te(n,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];Te(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Re={};pe(Re,{NAME:()=>sn,VERSION:()=>rn,up:()=>an});import*as D from"fs";import*as Ut from"path";var rn=2,sn="reset-unread-flags";function cn(t){return D.existsSync(t)?JSON.parse(D.readFileSync(t,"utf-8")):null}function ln(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";try{D.writeFileSync(r,o)}catch(n){try{D.unlinkSync(r)}catch{}throw n}try{D.renameSync(r,t)}catch(n){try{D.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${t} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function an(t){let e=Ut.join(t,"conversations.json"),o=cn(e);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}ln(e,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var De={};pe(De,{NAME:()=>fn,VERSION:()=>un,up:()=>yn});import*as O from"fs";import*as qt from"path";var un=3,fn="recompute-last-message-by",pn=new Set(["draft","confirmed","rejected","needs_review"]);function dn(t){return O.existsSync(t)?JSON.parse(O.readFileSync(t,"utf-8")):null}function mn(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";try{O.writeFileSync(r,o)}catch(n){try{O.unlinkSync(r)}catch{}throw n}try{O.renameSync(r,t)}catch(n){try{O.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${t} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function hn(t,e){if(!t||t.length===0)return"them";let o=t.filter(i=>!pn.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===e)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function yn(t){let e=qt.join(t,"conversations.json"),o=dn(e);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,i=0,s=0;for(let c of Object.keys(o)){let l=o[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let a=Array.isArray(l.messages)?l.messages:[],u=hn(a,r),m=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=m,n++}if(n===0){console.log(" No conversations to recompute.");return}mn(e,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Oe={};pe(Oe,{NAME:()=>Sn,VERSION:()=>gn,up:()=>vn});import*as N from"fs";import*as Bt from"path";var gn=4,Sn="split-connection-timestamps",bn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function wn(t){if(!N.existsSync(t))return null;let e=N.readFileSync(t,"utf-8");return e.charCodeAt(0)===65279&&(e=e.slice(1)),JSON.parse(e)}function kn(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";try{N.writeFileSync(r,o)}catch(n){try{N.unlinkSync(r)}catch{}throw n}try{N.renameSync(r,t)}catch(n){try{N.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${t} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function vn(t){let e=Bt.join(t,"people.json"),o=wn(e);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,bn.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}kn(e,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var _n=An(import.meta.url),En=g.dirname(_n),xn=g.dirname(g.dirname(En));function jn(t){return t&&(t==="~"?Le.homedir():t.startsWith("~/")||t.startsWith("~\\")?g.join(Le.homedir(),t.slice(2)):t)}var M=process.env.DATA_DIR?g.resolve(jn(process.env.DATA_DIR)):xn,Q=g.join(M,"collected-profiles"),X=g.join(M,"market-research"),E=g.join(M,".schema-version"),Jt=[g.join(Q,".schema-version"),g.join(X,".schema-version")],W=4,B=[{version:1,module:Ie},{version:2,module:Re},{version:3,module:De},{version:4,module:Oe}];(function(){B.sort((r,n)=>r.version-n.version);let e=new Set;for(let r of B){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(e.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);e.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=B.length?B[B.length-1].version:0;if(o!==W)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${W}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<B.length;r++){let n=r+1;if(B[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${B[r].version}`)}})();function Vt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
12
11
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
13
|
-
`),process.exit(1));try{
|
|
14
|
-
[FATAL] Cannot create DATA_DIR (${M}): ${
|
|
15
|
-
`),process.exit(1))}let
|
|
16
|
-
[FATAL] DATA_DIR (${M}) is not accessible: ${
|
|
17
|
-
`),process.exit(1)}
|
|
12
|
+
`),process.exit(1));try{d.mkdirSync(M,{recursive:!0})}catch(e){e.code!=="EEXIST"&&(console.error(`
|
|
13
|
+
[FATAL] Cannot create DATA_DIR (${M}): ${e.message}`),console.error(` Fix the path or permissions and try again.
|
|
14
|
+
`),process.exit(1))}let t;try{t=d.statSync(M)}catch(e){console.error(`
|
|
15
|
+
[FATAL] DATA_DIR (${M}) is not accessible: ${e.message}
|
|
16
|
+
`),process.exit(1)}t.isDirectory()||(console.error(`
|
|
18
17
|
[FATAL] DATA_DIR (${M}) 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.
|
|
19
|
-
`),process.exit(1));for(let
|
|
20
|
-
[FATAL] Data subdirectory is a symbolic link: ${
|
|
21
|
-
`),process.exit(1))}}var z=g.join(M,".migration-lock");function
|
|
22
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${
|
|
18
|
+
`),process.exit(1));for(let e of[Q,X]){let o;try{o=d.lstatSync(e)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
|
|
19
|
+
[FATAL] Data subdirectory is a symbolic link: ${e}`),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.
|
|
20
|
+
`),process.exit(1))}}var z=g.join(M,".migration-lock");function Cn(){let t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return d.writeFileSync(z,t,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let e;try{e=JSON.parse(d.readFileSync(z,"utf-8"))}catch{e=null}if(e&&Number.isInteger(e.pid)){let r=!1;try{process.kill(e.pid,0),r=!0}catch(s){s.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,i=1/0;if(e.startedAt){let s=Date.parse(e.startedAt);Number.isNaN(s)||(i=Date.now()-s)}r&&i<n&&(console.error(`
|
|
21
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${e.pid}`),console.error(` Started at: ${e.startedAt||"(unknown)"}`),console.error(` Lock file: ${z}
|
|
23
22
|
`),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.
|
|
24
|
-
`),process.exit(1)),r&&i>=n&&console.log(` Lock holder PID ${
|
|
25
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of
|
|
23
|
+
`),process.exit(1)),r&&i>=n&&console.log(` Lock holder PID ${e.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${e?.pid??"?"} found \u2014 taking over.`);let o=z+".tmp";try{return d.writeFileSync(o,t),d.renameSync(o,z),!0}catch(r){try{d.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function Pe(){try{if(JSON.parse(d.readFileSync(z,"utf-8")).pid!==process.pid)return;d.unlinkSync(z)}catch{}}var Ht=!1;function $n(){if(Ht)return;Ht=!0;let t=()=>{try{Pe()}catch{}process.exit(1)};for(let e of["SIGINT","SIGTERM","SIGHUP"])try{process.on(e,t)}catch{}}function Tn(){if(d.existsSync(E))return;let t=[],e=[];for(let i of Jt)if(d.existsSync(i))try{t.push({file:i,schema:be(i)})}catch(s){e.push({file:i,err:s.message})}if(e.length>0){console.error(`
|
|
24
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of e)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
26
25
|
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.
|
|
27
|
-
`),process.exit(1)}if(
|
|
28
|
-
[FATAL] Legacy .schema-version files disagree:`);for(let i of
|
|
29
|
-
`),process.exit(1)}let r=
|
|
26
|
+
`),process.exit(1)}if(t.length===0)return;let o=t.map(i=>i.schema.version);if(new Set(o).size>1){console.error(`
|
|
27
|
+
[FATAL] Legacy .schema-version files disagree:`);for(let i of t)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
28
|
+
`),process.exit(1)}let r=t[0].schema,n=E+".tmp";try{d.writeFileSync(n,JSON.stringify(r,null,2)),d.renameSync(n,E)}catch(i){try{d.unlinkSync(n)}catch{}throw i}for(let i of Jt)if(d.existsSync(i))try{d.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${E}`)}function In(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;let e=Number(t.version);return!Number.isFinite(e)||e<0||!Number.isInteger(e)?null:(t.version=e,Array.isArray(t.migrations)||(t.migrations=[]),t)}function be(t){let e=d.readFileSync(t,"utf-8");return e.charCodeAt(0)===65279&&(e=e.slice(1)),JSON.parse(e)}function Wt(){if(Tn(),!d.existsSync(E))return{version:0,migrations:[]};let t;try{t=be(E)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
30
29
|
[FATAL] ${E} 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.
|
|
31
|
-
`),process.exit(1)}let
|
|
32
|
-
[FATAL] ${E} has invalid structure:`),console.error(` ${JSON.stringify(
|
|
33
|
-
`),process.exit(1)),
|
|
34
|
-
[FATAL] Your data schema is at v${
|
|
35
|
-
`),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${
|
|
30
|
+
`),process.exit(1)}let e=In(t);return e===null&&(console.error(`
|
|
31
|
+
[FATAL] ${E} has invalid structure:`),console.error(` ${JSON.stringify(t)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
32
|
+
`),process.exit(1)),e}function Kt(t){try{d.chmodSync(t,384)}catch{}}function Rn(t){if(Vt(),d.existsSync(E))try{if(d.lstatSync(E).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${E}. 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 e=E+".tmp";try{d.writeFileSync(e,JSON.stringify(t,null,2)),Kt(e),d.renameSync(e,E)}catch(o){try{d.unlinkSync(e)}catch{}throw o}}function Gt(t,e){if(!d.existsSync(t))return;let o=`.pre-v${String(e).padStart(3,"0")}.backup`,r=d.readdirSync(t).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return d.statSync(g.join(t,c)).isFile()}catch{return!1}}),n=0,i=0,s=[];for(let c of r){let l=g.join(t,c),a=g.join(t,c+o);if(d.existsSync(a)){i++;continue}try{zt(l,a),n++}catch(u){s.push({file:c,err:u.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${g.basename(t)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(n>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${g.basename(t)}/ (${o})${c}`)}}var Ne=!1;async function Yt(){if(Ne)return;Vt(),Pn();let e=Wt().version;if(e===W){Ne=!0;return}$n(),Cn(),process.on("exit",Pe),e>W&&(console.error(`
|
|
33
|
+
[FATAL] Your data schema is at v${e}, but this plugin build only understands up to v${W}.`),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.
|
|
34
|
+
`),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${W}.
|
|
36
35
|
`),process.exit(1)),console.log(`
|
|
37
|
-
\u{1F4E6} Schema migration: v${
|
|
36
|
+
\u{1F4E6} Schema migration: v${e} \u2192 v${W}`);let o=Fn();if(!o.ok){console.error(`
|
|
38
37
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of o.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
|
|
39
38
|
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'.
|
|
40
|
-
`),process.exit(1)}let r=B.filter(n=>n.version>
|
|
41
|
-
Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{
|
|
39
|
+
`),process.exit(1)}let r=B.filter(n=>n.version>e);for(let n of r){console.log(`
|
|
40
|
+
Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{Gt(Q,n.version),Gt(X,n.version)}catch(l){console.error(`
|
|
42
41
|
[FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
43
42
|
`),process.exit(1)}let c=n.module;try{await c.up(Q,X)}catch(l){console.error(`
|
|
44
|
-
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=
|
|
43
|
+
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=Mn(s);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${e}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
45
44
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
46
45
|
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
47
|
-
`)}process.exit(1)}try{let l=new Date().toISOString(),a={version:n.version,name:c.NAME||i,appliedAt:l},u=
|
|
48
|
-
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${n.version} state but .schema-version still shows v${
|
|
49
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{
|
|
50
|
-
\u2713 Schema is now at v${
|
|
51
|
-
`)}var
|
|
52
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" MARKET RESEARCH STATS"),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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Scouted jobs: ${
|
|
53
|
-
`)}async function
|
|
46
|
+
`)}process.exit(1)}try{let l=new Date().toISOString(),a={version:n.version,name:c.NAME||i,appliedAt:l},u=Wt();u.version=n.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),Rn(u)}catch(l){console.error(`
|
|
47
|
+
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${n.version} state but .schema-version still shows v${e}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
48
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{$t()}catch{}try{vt()}catch{}Ne=!0,Pe(),console.log(`
|
|
49
|
+
\u2713 Schema is now at v${W}
|
|
50
|
+
`)}var Dn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function On(t){let e=t.toLowerCase();return Dn.some(o=>o.test(e))}var Nn=6e4;function Ln(){let t=Date.now(),e=[];for(let o of[M,Q,X]){if(!d.existsSync(o))continue;let r;try{r=d.readdirSync(o)}catch{continue}for(let n of r){if(!On(n))continue;let i=g.join(o,n);try{let s=d.statSync(i);if(!s.isFile()||t-s.mtimeMs<Nn)continue;e.push({dir:o,file:n,fullPath:i})}catch{}}}return e}function Pn({verbose:t=!1}={}){let e=Ln();if(e.length===0)return t&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of e)try{d.unlinkSync(r.fullPath),o++,t&&console.log(` Removed orphan: ${g.basename(r.dir)}/${r.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${r.fullPath}: ${n.message}`)}return!t&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function Fn(){let t=[];for(let e of[Q,X]){if(!d.existsSync(e))continue;let o=d.readdirSync(e).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=g.join(e,r);try{be(n)}catch(i){t.push({dir:g.basename(e),file:r,err:i.message})}}}return t.length===0?{ok:!0}:{ok:!1,broken:t}}function Mn(t){let e=[],o=[];for(let i of[Q,X]){if(!d.existsSync(i))continue;let s=d.readdirSync(i).filter(c=>c.endsWith(t));for(let c of s){let l=g.join(i,c),a=c.slice(0,-t.length),u=g.join(i,a);try{a.toLowerCase().endsWith(".json")?be(l):d.accessSync(l,d.constants.R_OK),e.push({backupPath:l,originalPath:u,fileName:c,dir:i})}catch(m){o.push(`${g.basename(i)}/${c}: ${m.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of e)try{zt(i,s),r++}catch(a){n.push(`${g.basename(l)}/${c}: ${a.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function zt(t,e){let o=e+".tmp";try{d.copyFileSync(t,o),Kt(o)}catch(r){try{d.unlinkSync(o)}catch{}throw r}try{d.renameSync(o,e)}catch(r){try{d.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let n=new Error(`File locked: ${e} (${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}}await Yt();var ae=process.argv.slice(2),ee=parseInt(ae.find(t=>t.startsWith("--max="))?.split("=")[1]||"200"),Qt=parseInt(ae.find(t=>t.startsWith("--pages="))?.split("=")[1]||"20"),Xt=ae.find(t=>t.startsWith("--url="))?.split("=").slice(1).join("="),Un=ae.includes("--list"),Zt=ae.includes("--verbose");function qn(){if(Xt)return[Xt];let t=process.env.LINKEDIN_SCOUT_URLS;if(t)return t.split(",").map(o=>o.trim()).filter(Boolean);let e=process.env.LINKEDIN_SEARCH_URL;return e?[e]:[]}function Bn(){let t=jt();console.log(`
|
|
51
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" MARKET RESEARCH STATS"),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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Scouted jobs: ${t.totalJobs}`),console.log(` Discovered recruiters: ${t.totalRecruiters}`),console.log(` Last scout: ${t.lastScoutDate||"never"}`),console.log(` Profile visits: ${t.totalVisited} unique (${t.todayVisited} today)`),t.topTech.length>0&&console.log(` Top tech: ${t.topTech.join(", ")}`),t.topCompanies.length>0&&console.log(` Top companies: ${t.topCompanies.join(", ")}`),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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
52
|
+
`)}async function Jn(){if(console.log(`
|
|
54
53
|
LinkedIn Job Scout
|
|
55
|
-
`),
|
|
56
|
-
`)
|
|
57
|
-
\u2550\u2550\u2550 Scout URL ${
|
|
58
|
-
\u2500\u2500 Page ${m+1} \u2500\u2500`),await
|
|
59
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" Scout Complete"),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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` URLs processed: ${
|
|
60
|
-
`),
|
|
61
|
-
Error:`,l.message),Me&&console.error(l.stack),Te(t,"error",o,l.message)}finally{await s.close().catch(()=>{})}}Un().catch(e=>{console.error("Scout failed:",e),process.exit(1)});
|
|
54
|
+
`),Un){Bn();return}let t=qn();t.length===0&&(console.error("No search URL. Set LINKEDIN_SCOUT_URL or LINKEDIN_SCOUT_URLS in .env, or use --url=..."),process.exit(1));let e={scouted:0,recruitersFound:0,skipped:0,skippedApplied:0,alreadyConnected:0,pages:0,errors:0,urlsProcessed:0},o=ge(),r=Dt(),n=Rt();console.log(` Scout URLs: ${t.length}`),t.forEach((i,s)=>console.log(` ${s+1}. ${i.slice(0,80)}...`)),console.log(` Max jobs: ${ee} | Max pages per URL: ${Qt}
|
|
55
|
+
`),await Mt("scout",`max=${ee},urls=${t.length}`,async i=>{let{browser:s,page:c}=await ft();try{for(let l of t){if(e.scouted>=ee)break;e.urlsProcessed++,console.log(`
|
|
56
|
+
\u2550\u2550\u2550 Scout URL ${e.urlsProcessed}/${t.length}: ${l.slice(0,70)}... \u2550\u2550\u2550`),await c.goto(l,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3);let a=0,u=!1;for(let m=0;m<Qt&&e.scouted<ee&&!u;m++){e.pages++,console.log(`
|
|
57
|
+
\u2500\u2500 Page ${m+1} \u2500\u2500`),await ht(c,l),await pt(c),await j(1e3);let f=await dt(c,{easyApplyOnly:!1});console.log(` Found ${f.length} jobs on page`);for(let p of f){if(e.scouted>=ee)break;let b=p.href?.match(/jobs\/view\/(\d+)/)?.[1]||p.id?.match(/\d+/)?.[0];if(b&&o[b]){e.skipped++;continue}if(b&&r[b]){e.skippedApplied++;continue}try{let y=await c.$(`a[data-control-id="${p.dataId}"]`);if(!y)continue;let w=await c.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()?.slice(0,80)||"");await y.click(),await j(1500+Math.random()*1500);for(let $=0;$<8;$++){let L=await c.evaluate(te=>{let Z=document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24"),x=document.querySelector(".jobs-description__content"),ue=Z?.innerText?.trim()?.slice(0,80)||"",we=x?.innerText?.trim()?.length||0;return{title:ue,descLen:we,titleChanged:ue!==te&&ue.length>0}},w);if(L.titleChanged&&L.descLen>50)break;await j(600)}let S=await gt(c),A=await yt(c);if(b&&(At(b,{title:p.jobTitle,company:S.companyName||p.companyName,companyUrl:S.companyUrl,location:p.location,salary:p.salary,url:p.href,isEasyApply:p.isEasyApply,applyType:p.applyType||(p.isEasyApply?"easy-apply":"external"),externalApplyUrl:S.externalApplyUrl,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,recruiterUrl:A?.profileUrl||null}),e.scouted++),S.companyUrl&&xt(S.companyUrl,{name:S.companyName||p.companyName,about:S.aboutCompany,size:S.companySize,industries:S.industries,jobId:b,recruiterUrl:A?.profileUrl}),A?.profileUrl){let L=n[A.profileUrl]?.connectionStatus==="connected";Et(A.profileUrl,{name:A.name,source:"scout",role:"recruiter",jobId:b,jobTitle:p.jobTitle,isConnected:L}),e.recruitersFound++,L&&e.alreadyConnected++}if(Zt){let $=S.techStack?.slice(0,5).join(", ")||"none";console.log(` [${e.scouted}] ${p.jobTitle?.slice(0,40)} @ ${p.companyName?.slice(0,20)} | ${$}${A?" | \u{1F464} "+A.name:""}`)}else e.scouted%10===0&&console.log(` Scouted: ${e.scouted} (${e.recruitersFound} recruiters)`)}catch(y){e.errors++,a++,Zt&&console.error(` Error: ${y.message?.slice(0,80)}`);let w=(y.message||"").toLowerCase();if(w.includes("detached")||w.includes("session closed")||w.includes("target closed")||w.includes("browser has disconnected")||w.includes("protocol error")){console.log(" \u26A0 Fatal browser error \u2014 stopping scout"),u=!0;break}if(a>=5){console.log(" \u26A0 5 consecutive errors \u2014 stopping scout"),u=!0;break}continue}a=0}if(u)break;if(e.scouted<ee)try{if(!await mt(c)){console.log(" No more pages.");break}await j(2e3)}catch(p){console.log(` \u26A0 Pagination failed: ${p.message?.slice(0,60)}`);break}}if(u)break}console.log(`
|
|
58
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" Scout Complete"),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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` URLs processed: ${e.urlsProcessed}/${t.length}`),console.log(` Pages scanned: ${e.pages}`),console.log(` Jobs scouted: ${e.scouted}`),console.log(` Skipped (existing): ${e.skipped}`),console.log(` Skipped (applied): ${e.skippedApplied}`),console.log(` Recruiters found: ${e.recruitersFound} (${e.alreadyConnected} already connected)`),console.log(` Errors: ${e.errors}`),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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
59
|
+
`),Object.assign(i,e)}finally{await s.close().catch(()=>{})}},()=>[`${e.scouted} scouted, ${e.recruitersFound} recruiters, ${e.skipped} skipped, ${e.errors} errors`,`URLs ${e.urlsProcessed}/${t.length}, pages scanned ${e.pages}`])}Jn().catch(t=>{console.error("Scout failed:",t),process.exit(1)});
|