ilml-plugin-linkedin 1.20.4 → 1.20.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/scout.mjs CHANGED
@@ -1,58 +1,58 @@
1
- var zt=Object.defineProperty;var ue=(t,e)=>{for(var o in e)zt(t,o,{get:e[o],enumerable:!0})};import ao from"puppeteer";import{addExtra as uo}from"puppeteer-extra";import fo from"puppeteer-extra-plugin-stealth";async function D(t){let e=Math.floor(Math.random()*2001),o=t+e;return new Promise(r=>setTimeout(r,o))}import{getPluginConfig as Yt}from"@ilivemylife/graph-sdk";var Qt=await Yt();for(let[t,e]of Object.entries(Qt))process.env[t]===void 0&&(process.env[t]=e);var Xt=process.env.LINKEDIN_NAME,G=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Fn=Object.freeze(new Set([G.DRAFT,G.CONFIRMED,G.NEEDS_REVIEW])),Zt=Object.freeze(new Set([G.DRAFT,G.CONFIRMED,G.REJECTED,G.NEEDS_REVIEW]));import O from"fs";import B from"path";var eo="cookies.json";function qe(){let t=process.env.ILML_SCOPE_DIR;return t?B.join(t,"plugins-state","linkedin","cookies.json"):eo}function Be(){let t=qe();if(!O.existsSync(t))throw new Error(`Cookies not found at ${t}. Run: ilml linkedin login`);let e;try{e=O.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 O.existsSync(qe())}function to(){let t=process.env.ILML_SCOPE_DIR;return t?B.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 oo(){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 O.existsSync(e)||O.mkdirSync(e,{recursive:!0}),B.resolve(e);let o=He(t||oo()),r=B.join(to(),"chrome-profile",o);return O.existsSync(r)||O.mkdirSync(r,{recursive:!0}),B.resolve(r)}var Ge=".ilml-seeded";function Ve(t){return!O.existsSync(B.join(t,Ge))}function Ke(t){try{O.writeFileSync(B.join(t,Ge),new Date().toISOString())}catch{}}function ze(t){let e=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{O.rmSync(B.join(t,o),{force:!0}),e++}catch{}return e}import ve from"fs";import no from"path";var ro={headless:!1,defaultViewport:null,protocolTimeout:3e5},ee=new Set,Ye=!1;async function fe(){let t=[...ee].map(e=>{try{return Promise.resolve(e.close()).catch(()=>{})}catch{return Promise.resolve()}});ee.clear(),await Promise.race([Promise.all(t),new Promise(e=>setTimeout(e,5e3))])}function so(){if(Ye)return;Ye=!0;let t=e=>async()=>{await fe(),process.exit(e)};process.once("SIGINT",t(130)),process.once("SIGTERM",t(143)),process.once("SIGHUP",t(129)),process.once("uncaughtException",async e=>{await fe(),console.error(e&&e.stack||e),process.exit(1)}),process.once("unhandledRejection",async e=>{await fe(),console.error(e),process.exit(1)}),process.stdout.on("error",async e=>{e&&e.code==="EPIPE"&&(await fe(),process.exit(0))}),process.on("exit",()=>{for(let e of ee)try{let o=e.process&&e.process();o&&o.kill("SIGKILL")}catch{}})}function ke(t){return no.join(t,".ilml-browser-session.json")}function et(t,e={}){try{ve.writeFileSync(ke(t),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...e}))}catch{}}function io(t,e){try{let o=e.wsEndpoint&&e.wsEndpoint();et(t,o?{wsEndpoint:o}:{})}catch{}}function co(t){let e=tt(t);e&&e.ownerPid===process.pid&&Z(t)}function Z(t){try{ve.rmSync(ke(t),{force:!0})}catch{}}function tt(t){try{return JSON.parse(ve.readFileSync(ke(t),"utf-8"))}catch{return null}}function Qe(t){if(!t||t===process.pid)return!0;try{return process.kill(t,0),!0}catch(e){return!e||e.code!=="ESRCH"}}function Xe(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 Ze(t,e,{probeTimeoutMs:o=4e3}={}){let r=tt(e);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&Qe(r.ownerPid)?"live":(Z(e),"free");let n=Symbol("timeout"),i=t.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Xe(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return Z(e),"free";if(Qe(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Xe(s.close().then(()=>!0).catch(()=>!1),o,!1))return Z(e),"free";try{s.disconnect()}catch{}return"live"}function lo(t,e){t&&(so(),ee.add(t),t.on("disconnected",()=>{ee.delete(t),e&&Z(e)}))}async function ot(t,e={}){let o=We(),r={...ro,...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 Ze(t,o)==="live")throw new Error(n);et(o);let i;try{i=await t.launch(r)}catch{if(await Ze(t,o)==="live")throw new Error(n);ze(o);try{i=await t.launch(r)}catch(c){throw co(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 lo(i,o),io(o,i),{browser:i,profileDir:o,needsSeed:Ve(o)}}async function nt(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 rt=uo(ao);rt.use(fo());async function st(){let{browser:t,profileDir:e,needsSeed:o}=await ot(rt),r=await t.newPage();return await r.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await nt(r,{profileDir:e,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:t,page:r}}async function it(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 h of r)if(n=document.querySelector(h),n){i=h;break}if(!n){let h=document.querySelector("li.scaffold-layout__list-item");if(h){let u=h.parentElement;for(;u&&u!==document.body;){if(u.scrollHeight>u.clientHeight){n=u,i="parent of li.scaffold-layout__list-item";break}u=u.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,c=300,l=300,f=50,d=0;for(;d<f&&(n.scrollBy(0,c),await new Promise(h=>setTimeout(h,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)d++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:d}},e)}async function ct(t,{easyApplyOnly:e=!0}={}){let o=await t.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let s=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),c=n.querySelector("a.job-card-container__link");if(c){let l=c.getAttribute("href").split("?")[0],f=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),d=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),h=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),u=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:s,applyType:s?"easy-apply":"external",dataId:c.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:f,companyName:d,location:h,salary:u||null,jobLink:s?c.href:null}}return{isEasyApply:!1}})});return e?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function lt(t){let e=await t.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",e.success?e.pageState:e.reason),e.success&&await D(2e3),e.success}async function at(t,e){let o=t.url();if(o.includes("/jobs/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await D(3e3);let n=t.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function ut(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 ft(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 W of i){let we=W.querySelector(".job-criteria__subheader")?.textContent?.trim(),Ue=W.querySelector(".job-criteria__text")?.textContent?.trim();we&&Ue&&(n[we.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 W of s)new RegExp("\\b"+W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&c.push(W.replace(/\\\+/g,"+"));let f=e.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,h=e.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,u=e.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=u?.innerText?.trim()||null,S=(u?.querySelector('a[href*="/company/"]')||e.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,g=e.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",M=g.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,U=g.match(/(\d[\d,]*)\s+applicant/i),ge=U?parseInt(U[1].replace(/,/g,"")):null,Se=e.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),ce=Array.from(Se).map(W=>W.innerText?.trim()?.replace(/\s+/g," ")),be=ce.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,q=ce.join(" ")+" "+g,Vt=/\bremote\b/i.test(q)?"remote":/\bhybrid\b/i.test(q)?"hybrid":/\bon-?site\b/i.test(q)?"onsite":null,Kt=/\bcontract\b/i.test(q)?"contract":/\bfull-?time\b/i.test(q)?"full-time":/\bpart-?time\b/i.test(q)?"part-time":/\bfreelance\b/i.test(q)?"freelance":/\btemporary\b/i.test(q)?"temporary":null,Pe=e.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",ae=e.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",I=(Pe+" "+r+" "+ae).toLowerCase(),R=Pe.toLowerCase(),m=[];/\bremote\b/.test(I)&&m.push("remote"),/\bhybrid\b/.test(I)&&m.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(I)&&m.push("onsite"),(m.length===0||!m.includes("remote")&&!m.includes("hybrid")&&!m.includes("onsite"))&&/remote/i.test(ae)&&m.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(R)&&m.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(R)&&m.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(R)&&!m.includes("managerial")&&m.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(R)?m.push("junior"):/\b(senior|sr\.?)\b/i.test(R)?m.push("senior"):/\b(staff|principal|distinguished)\b/i.test(R)?m.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(R)?m.push("executive"):/\b(lead|team lead)\b/i.test(R)&&m.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(I)&&m.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(I)&&m.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(I)&&m.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(I)&&m.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(I)&&m.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(I)&&m.push("mobile"),/\b(architect)\b/i.test(R)&&m.push("architect"),/\b(consultant|consulting)\b/i.test(R)&&m.push("consultant");let Me=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(Me)||/\bcontract\b/i.test(I))&&m.push("contract"),/full.?time|permanent/i.test(Me)&&m.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(ae)&&m.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(ae)&&m.push("usa"),(e.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&m.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:h,companyName:p,companyUrl:S?S.startsWith("/")?"https://www.linkedin.com"+S:S:null,aboutCompany:f,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:M,applicantCount:ge,companySize:be,workplaceType:Vt,contractType:Kt,techStack:[...new Set(c)],jobTags:[...new Set(m)]}})}import"dotenv/config";import*as E from"fs";import*as _ from"path";import{fileURLToPath as po}from"url";function pt(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 mo=po(import.meta.url),ho=_.dirname(_.dirname(mo)),K=process.env.DATA_DIR?_.resolve(process.env.DATA_DIR,"market-research"):_.join(ho,"market-research"),dt=_.join(K,"scouted-jobs.json"),mt=_.join(K,"discovered-people.json"),yo=_.join(K,"visit-log.json"),ht=_.join(K,"companies.json"),mr=_.join(K,"job-decisions.json");function Ae(){E.existsSync(K)||E.mkdirSync(K,{recursive:!0})}function _e(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";E.writeFileSync(r,o);for(let n=0;n<3;n++)try{E.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 de(t){try{if(E.existsSync(t))return JSON.parse(E.readFileSync(t,"utf-8"))}catch{}return null}function yt(){te=null,go=null,oe=null,ne=null,V=null}var te=null;function me(){return te||(te=de(dt)||{},te)}function gt(t,e){if(!t)return;Ae();let o=me(),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{_e(dt,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var go=null;var oe=null;function St(){return oe||(oe=de(mt)||{},oe)}function pe(t){let e=String(t||"").match(/\/in\/([^/?#]+)/i);return e?e[1].toLowerCase():null}function So(t,e){let o=pt(e)||e;if(t[o])return o;let r=pe(e);if(!r)return o;let n=null;for(let[i,s]of Object.entries(t)){if(pe(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 bt(t,e){if(!t)return;Ae();let o=St(),r=new Date().toISOString().slice(0,10),n=So(o,t),i=pe(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&&pe(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{_e(mt,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}var ne=null;function bo(){return ne||(ne=de(ht)||{},ne)}function wt(t,e){if(!t)return;Ae();let o=bo(),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{_e(ht,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var V=null;function wo(){return V||(V=de(yo)||{visits:[]},Array.isArray(V.visits)||(V.visits=[]),V)}function vt(){let t=me(),e=St(),o=Object.values(t),r=Object.values(e),n={};for(let u of o)u.company&&(n[u.company]=(n[u.company]||0)+1);let i=Object.entries(n).sort((u,p)=>p[1]-u[1]).slice(0,5).map(([u,p])=>`${u} (${p})`),s={};for(let u of o)for(let p of u.techStack||[])s[p]=(s[p]||0)+1;let c=Object.entries(s).sort((u,p)=>p[1]-u[1]).slice(0,8).map(([u,p])=>`${u} (${p})`),l=wo(),f=new Date().toISOString().slice(0,10),d=l.visits.filter(u=>u.date.startsWith(f)).length,h=new Set(l.visits.map(u=>u.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:c,totalVisited:h,todayVisited:d,lastScoutDate:o.length>0?o.sort((u,p)=>(p.scoutedAt||"").localeCompare(u.scoutedAt||""))[0]?.scoutedAt:null}}import"dotenv/config";import*as b from"fs";import*as v from"path";import{fileURLToPath as vo}from"url";var ko=vo(import.meta.url),Ao=v.dirname(v.dirname(ko)),F=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"collected-profiles"):v.join(Ao,"collected-profiles"),_o=v.join(F,"people.json"),Eo=v.join(F,"jobs.json"),br=v.join(F,"quota.json"),wr=v.join(F,"conversations.json"),vr=v.join(F,"sync-state.json"),kr=v.join(F,"application-questions.json"),Ar=v.join(F,"profile-history"),kt=(t,e)=>{let o=parseInt(t,10);return Number.isInteger(o)&&o>=0?o:e},_r=kt(process.env.CONNECT_MAX_DAILY,20),Er=kt(process.env.CONNECT_MAX_WEEKLY,100),re=null,se=null,jo=null,xo=null,Co=null,To=null;function At(){re=null,se=null,jo=null,xo=null,Co=null,To=null}function _t(){b.existsSync(F)||b.mkdirSync(F,{recursive:!0})}function Et(t,e){if(!b.existsSync(t))return null;try{let o=JSON.parse(b.readFileSync(t,"utf-8"));try{b.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(b.existsSync(r))try{let n=JSON.parse(b.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{b.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{b.copyFileSync(t,t+".corrupted")}catch{}return null}}function jt(){return re||(_t(),re=Et(_o,"people.json")||{},re)}function xt(){return se||(_t(),se=Et(Eo,"jobs.json")||{},se)}import"dotenv/config";import*as j from"fs";import*as J from"path";import{fileURLToPath as No}from"url";import"dotenv/config";import{createGraphClient as $o,resolveToken as Io}from"@ilivemylife/graph-sdk";import{config as Ro}from"dotenv";Ro();var Ct=Io()||process.env.TOKEN;Ct||(console.error(`
1
+ var Yt=Object.defineProperty;var ue=(e,t)=>{for(var o in t)Yt(e,o,{get:t[o],enumerable:!0})};import uo from"puppeteer";import{addExtra as fo}from"puppeteer-extra";import po from"puppeteer-extra-plugin-stealth";async function j(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}async function ve(e,t,{timeout:o=45e3,poll:r=1e3,label:n="page"}={}){let i=Date.now();for(;Date.now()-i<o;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){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}import{getPluginConfig as Qt}from"@ilivemylife/graph-sdk";var Xt=await Qt();for(let[e,t]of Object.entries(Xt))process.env[e]===void 0&&(process.env[e]=t);var Zt=process.env.LINKEDIN_NAME,G=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Pn=Object.freeze(new Set([G.DRAFT,G.CONFIRMED,G.NEEDS_REVIEW])),eo=Object.freeze(new Set([G.DRAFT,G.CONFIRMED,G.REJECTED,G.NEEDS_REVIEW]));import O from"fs";import B from"path";var to="cookies.json";function Be(){let e=process.env.ILML_SCOPE_DIR;return e?B.join(e,"plugins-state","linkedin","cookies.json"):to}function Je(){let e=Be();if(!O.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=O.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function He(){return O.existsSync(Be())}function oo(){let e=process.env.ILML_SCOPE_DIR;return e?B.join(e,"plugins-state","linkedin"):"."}function We(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function no(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?We(t[1]):"default"}function Ge(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return O.existsSync(t)||O.mkdirSync(t,{recursive:!0}),B.resolve(t);let o=We(e||no()),r=B.join(oo(),"chrome-profile",o);return O.existsSync(r)||O.mkdirSync(r,{recursive:!0}),B.resolve(r)}var Ve=".ilml-seeded";function Ke(e){return!O.existsSync(B.join(e,Ve))}function ze(e){try{O.writeFileSync(B.join(e,Ve),new Date().toISOString())}catch{}}function Ye(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{O.rmSync(B.join(e,o),{force:!0}),t++}catch{}return t}import ke from"fs";import ro from"path";var so={headless:!1,defaultViewport:null,protocolTimeout:3e5},ee=new Set,Qe=!1;async function fe(){let e=[...ee].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ee.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function io(){if(Qe)return;Qe=!0;let e=t=>async()=>{await fe(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await fe(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await fe(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await fe(),process.exit(0))}),process.on("exit",()=>{for(let t of ee)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Ae(e){return ro.join(e,".ilml-browser-session.json")}function tt(e,t={}){try{ke.writeFileSync(Ae(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function co(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();tt(e,o?{wsEndpoint:o}:{})}catch{}}function lo(e){let t=ot(e);t&&t.ownerPid===process.pid&&Z(e)}function Z(e){try{ke.rmSync(Ae(e),{force:!0})}catch{}}function ot(e){try{return JSON.parse(ke.readFileSync(Ae(e),"utf-8"))}catch{return null}}function Xe(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Ze(e,t,o){let r,n=new Promise(s=>{r=setTimeout(()=>s(o),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s});return Promise.race([i,n])}async function et(e,t,{probeTimeoutMs:o=4e3}={}){let r=ot(t);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&Xe(r.ownerPid)?"live":(Z(t),"free");let n=Symbol("timeout"),i=e.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Ze(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return Z(t),"free";if(Xe(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Ze(s.close().then(()=>!0).catch(()=>!1),o,!1))return Z(t),"free";try{s.disconnect()}catch{}return"live"}function ao(e,t){e&&(io(),ee.add(e),e.on("disconnected",()=>{ee.delete(e),t&&Z(t)}))}async function nt(e,t={}){let o=Ge(),r={...so,...t,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 et(e,o)==="live")throw new Error(n);tt(o);let i;try{i=await e.launch(r)}catch{if(await et(e,o)==="live")throw new Error(n);Ye(o);try{i=await e.launch(r)}catch(c){throw lo(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 ao(i,o),co(o,i),{browser:i,profileDir:o,needsSeed:Ke(o)}}async function rt(e,t){if(!t||!t.needsSeed)return!1;if(!He())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Je()),ze(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var st=fo(uo);st.use(po());async function it(){let{browser:e,profileDir:t,needsSeed:o}=await nt(st),r=await e.newPage();return await r.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await rt(r,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:r}}async function ct(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,i=null;for(let h of r)if(n=document.querySelector(h),n){i=h;break}if(!n){let h=document.querySelector("li.scaffold-layout__list-item");if(h){let u=h.parentElement;for(;u&&u!==document.body;){if(u.scrollHeight>u.clientHeight){n=u,i="parent of li.scaffold-layout__list-item";break}u=u.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,c=300,l=300,f=50,d=0;for(;d<f&&(n.scrollBy(0,c),await new Promise(h=>setTimeout(h,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)d++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:d}},t)}async function lt(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let r=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(r).map(n=>{let s=(n.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),c=n.querySelector("a.job-card-container__link");if(c){let l=c.getAttribute("href").split("?")[0],f=n.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),d=n.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),h=n.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),u=n.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:s,applyType:s?"easy-apply":"external",dataId:c.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:f,companyName:d,location:h,salary:u||null,jobLink:s?c.href:null}}return{isEasyApply:!1}})});return t?o.filter(r=>r.isEasyApply&&r.href):o.filter(r=>r.href)}async function at(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let r=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:r}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await j(2e3),t.success}async function ut(e,t){let o=e.url();if(o.includes("/jobs/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint")){if(!await ve(e,".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list",{timeout:45e3,label:"job search"})&&(e.url().includes("/authwall")||e.url().includes("/login")||e.url().includes("/checkpoint")))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");if(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 n=e.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function ft(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 pt(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 we=W.querySelector(".job-criteria__subheader")?.textContent?.trim(),qe=W.querySelector(".job-criteria__text")?.textContent?.trim();we&&qe&&(n[we.toLowerCase()]=qe)}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 f=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,h=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,u=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),p=u?.innerText?.trim()||null,S=(u?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,g=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",M=g.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,U=g.match(/(\d[\d,]*)\s+applicant/i),ge=U?parseInt(U[1].replace(/,/g,"")):null,Se=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),ce=Array.from(Se).map(W=>W.innerText?.trim()?.replace(/\s+/g," ")),be=ce.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,q=ce.join(" ")+" "+g,Kt=/\bremote\b/i.test(q)?"remote":/\bhybrid\b/i.test(q)?"hybrid":/\bon-?site\b/i.test(q)?"onsite":null,zt=/\bcontract\b/i.test(q)?"contract":/\bfull-?time\b/i.test(q)?"full-time":/\bpart-?time\b/i.test(q)?"part-time":/\bfreelance\b/i.test(q)?"freelance":/\btemporary\b/i.test(q)?"temporary":null,Me=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",ae=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",R=(Me+" "+r+" "+ae).toLowerCase(),D=Me.toLowerCase(),m=[];/\bremote\b/.test(R)&&m.push("remote"),/\bhybrid\b/.test(R)&&m.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(R)&&m.push("onsite"),(m.length===0||!m.includes("remote")&&!m.includes("hybrid")&&!m.includes("onsite"))&&/remote/i.test(ae)&&m.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(D)&&m.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(D)&&m.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(D)&&!m.includes("managerial")&&m.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(D)?m.push("junior"):/\b(senior|sr\.?)\b/i.test(D)?m.push("senior"):/\b(staff|principal|distinguished)\b/i.test(D)?m.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(D)?m.push("executive"):/\b(lead|team lead)\b/i.test(D)&&m.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(R)&&m.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(R)&&m.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(R)&&m.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(R)&&m.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(R)&&m.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(R)&&m.push("mobile"),/\b(architect)\b/i.test(D)&&m.push("architect"),/\b(consultant|consulting)\b/i.test(D)&&m.push("consultant");let Ue=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(Ue)||/\bcontract\b/i.test(R))&&m.push("contract"),/full.?time|permanent/i.test(Ue)&&m.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(ae)&&m.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(ae)&&m.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&m.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:h,companyName:p,companyUrl:S?S.startsWith("/")?"https://www.linkedin.com"+S:S:null,aboutCompany:f,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:M,applicantCount:ge,companySize:be,workplaceType:Kt,contractType:zt,techStack:[...new Set(c)],jobTags:[...new Set(m)]}})}import"dotenv/config";import*as E from"fs";import*as _ from"path";import{fileURLToPath as mo}from"url";function dt(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 ho=mo(import.meta.url),yo=_.dirname(_.dirname(ho)),K=process.env.DATA_DIR?_.resolve(process.env.DATA_DIR,"market-research"):_.join(yo,"market-research"),mt=_.join(K,"scouted-jobs.json"),ht=_.join(K,"discovered-people.json"),go=_.join(K,"visit-log.json"),yt=_.join(K,"companies.json"),mr=_.join(K,"job-decisions.json");function _e(){E.existsSync(K)||E.mkdirSync(K,{recursive:!0})}function je(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";E.writeFileSync(r,o);for(let n=0;n<3;n++)try{E.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function de(e){try{if(E.existsSync(e))return JSON.parse(E.readFileSync(e,"utf-8"))}catch{}return null}function gt(){te=null,So=null,oe=null,ne=null,V=null}var te=null;function me(){return te||(te=de(mt)||{},te)}function St(e,t){if(!e)return;_e();let o=me(),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{je(mt,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var So=null;var oe=null;function bt(){return oe||(oe=de(ht)||{},oe)}function pe(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function bo(e,t){let o=dt(t)||t;if(e[o])return o;let r=pe(t);if(!r)return o;let n=null;for(let[i,s]of Object.entries(e)){if(pe(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 wt(e,t){if(!e)return;_e();let o=bt(),r=new Date().toISOString().slice(0,10),n=bo(o,e),i=pe(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&&pe(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{je(ht,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}var ne=null;function wo(){return ne||(ne=de(yt)||{},ne)}function vt(e,t){if(!e)return;_e();let o=wo(),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{je(yt,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var V=null;function vo(){return V||(V=de(go)||{visits:[]},Array.isArray(V.visits)||(V.visits=[]),V)}function kt(){let e=me(),t=bt(),o=Object.values(e),r=Object.values(t),n={};for(let u of o)u.company&&(n[u.company]=(n[u.company]||0)+1);let i=Object.entries(n).sort((u,p)=>p[1]-u[1]).slice(0,5).map(([u,p])=>`${u} (${p})`),s={};for(let u of o)for(let p of u.techStack||[])s[p]=(s[p]||0)+1;let c=Object.entries(s).sort((u,p)=>p[1]-u[1]).slice(0,8).map(([u,p])=>`${u} (${p})`),l=vo(),f=new Date().toISOString().slice(0,10),d=l.visits.filter(u=>u.date.startsWith(f)).length,h=new Set(l.visits.map(u=>u.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:c,totalVisited:h,todayVisited:d,lastScoutDate:o.length>0?o.sort((u,p)=>(p.scoutedAt||"").localeCompare(u.scoutedAt||""))[0]?.scoutedAt:null}}import"dotenv/config";import*as b from"fs";import*as v from"path";import{fileURLToPath as ko}from"url";var Ao=ko(import.meta.url),_o=v.dirname(v.dirname(Ao)),F=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"collected-profiles"):v.join(_o,"collected-profiles"),jo=v.join(F,"people.json"),Eo=v.join(F,"jobs.json"),br=v.join(F,"quota.json"),wr=v.join(F,"conversations.json"),vr=v.join(F,"sync-state.json"),kr=v.join(F,"application-questions.json"),Ar=v.join(F,"profile-history"),At=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},_r=At(process.env.CONNECT_MAX_DAILY,20),jr=At(process.env.CONNECT_MAX_WEEKLY,100),re=null,se=null,xo=null,Co=null,To=null,$o=null;function _t(){re=null,se=null,xo=null,Co=null,To=null,$o=null}function jt(){b.existsSync(F)||b.mkdirSync(F,{recursive:!0})}function Et(e,t){if(!b.existsSync(e))return null;try{let o=JSON.parse(b.readFileSync(e,"utf-8"));try{b.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(b.existsSync(r))try{let n=JSON.parse(b.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{b.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{b.copyFileSync(e,e+".corrupted")}catch{}return null}}function xt(){return re||(jt(),re=Et(jo,"people.json")||{},re)}function Ct(){return se||(jt(),se=Et(Eo,"jobs.json")||{},se)}import"dotenv/config";import*as x from"fs";import*as J from"path";import{fileURLToPath as Lo}from"url";import"dotenv/config";import{createGraphClient as Io,resolveToken as Ro}from"@ilivemylife/graph-sdk";import{config as Do}from"dotenv";Do();var Tt=Ro()||process.env.TOKEN;Tt||(console.error(`
2
2
  [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.
3
3
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
4
4
  `),console.error(` Or add ILML_TOKEN=... to .env
5
- `),process.exit(1));var Tt=$o({token:Ct});function Do(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`}function Oo({scriptName:t,mode:e,status:o,error:r,duration:n}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=n?` ${Do(n)}`:"",l=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",f=e&&e!=="default"?` (${e})`:"";return`${i} ${t}${f} \u2014 ${l} \u2014 ${s}${c}`}async function $t({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 l=`**${Oo({scriptName:t,mode:e,status:o,error:n,duration:i})}**
5
+ `),process.exit(1));var $t=Io({token:Tt});function Oo(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),r=t%60;return r?`${o}m ${r}s`:`${o}m`}function No({scriptName:e,mode:t,status:o,error:r,duration:n}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=n?` ${Oo(n)}`:"",l=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",f=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${f} \u2014 ${l} \u2014 ${s}${c}`}async function It({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(r)||r.length===0)return;let l=`**${No({scriptName:e,mode:t,status:o,error:n,duration:i})}**
6
6
 
7
7
  ${r.join(`
8
- `)}`;try{await Tt.addMessage(s,l)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Lo=No(import.meta.url),Fo=J.dirname(J.dirname(Lo)),Ee=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"collected-profiles"):J.join(Fo,"collected-profiles"),je=J.join(Ee,"run-log.json");function Po(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";j.writeFileSync(r,o);for(let n=0;n<3;n++)try{j.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 It(){try{if(!j.existsSync(je))return{runs:[]};let t=JSON.parse(j.readFileSync(je,"utf-8"));return!t.runs||!Array.isArray(t.runs)?{runs:[]}:t}catch{return{runs:[]}}}function Rt(t){j.existsSync(Ee)||j.mkdirSync(Ee,{recursive:!0});try{Po(je,t)}catch(e){console.error(`[!] Failed to save run-log.json: ${e.message}`)}}function Dt(t,e="default"){let o=It();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),Rt(o),{script:t,mode:e,startTime:r.getTime(),runIndex:o.runs.length-1}}function xe(t,e,o=null,r=null){if(!t)return;let n=null;try{let s=It(),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(f=>f.script===t.script&&f.status==="running"&&f.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)}Rt(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";$t({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}`))}}import"dotenv/config";import*as a from"fs";import*as Ne from"os";import*as y from"path";import{fileURLToPath as an}from"url";var $e={};ue($e,{NAME:()=>Uo,VERSION:()=>Mo,up:()=>Jo});import*as x from"fs";import*as he from"path";var Mo=1,Uo="normalize-jobs-and-questions",qo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Bo=50;function Ce(t){return x.existsSync(t)?JSON.parse(x.readFileSync(t,"utf-8")):null}function Te(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";try{x.writeFileSync(r,o)}catch(n){try{x.unlinkSync(r)}catch{}throw n}try{x.renameSync(r,t)}catch(n){try{x.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 Jo(t,e){let o=he.join(t,"jobs.json"),r=he.join(e,"scouted-jobs.json"),n=he.join(t,"application-questions.json"),i=Ce(o)||{},s=Ce(r)||{},c=0,l=[];for(let d of Object.keys(i)){if(!s[d])continue;let h=s[d],u=i[d];for(let p of qo)h[p]!=null&&u[p]==null&&(u[p]=h[p]);l.push(d),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 f=Ce(n);if(f&&Array.isArray(f.applications)){let d={},h=0;for(let u of f.applications){let p=u.jobId||"unknown";d[p]||(d[p]={applications:[]});let A=(u.questions||[]).map(S=>{let w={type:S.type||"input",question:S.question||"",answer:S.answer||""};return S.options&&(S.options.length<=Bo?w.options=S.options:(w.optionsOmitted=!0,h++)),S.page&&(w.page=S.page),S.wasPreFilled&&(w.wasPreFilled=!0),S.wasRetry&&(w.wasRetry=!0),w});d[p].applications.push({applicationId:u.applicationId,date:u.date,result:u.result||"submitted",formPages:u.formPages||null,duration:u.duration||null,retries:u.retries||0,failedField:u.failedField||null,questionCount:u.questionCount||A.length,questions:A})}Te(n,d),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(d).length} unique jobs)`),h>0&&console.log(` Phase 2: Stripped bloated options from ${h} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let d of l)delete s[d];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 Ie={};ue(Ie,{NAME:()=>Wo,VERSION:()=>Ho,up:()=>Ko});import*as C from"fs";import*as Ot from"path";var Ho=2,Wo="reset-unread-flags";function Go(t){return C.existsSync(t)?JSON.parse(C.readFileSync(t,"utf-8")):null}function Vo(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";try{C.writeFileSync(r,o)}catch(n){try{C.unlinkSync(r)}catch{}throw n}try{C.renameSync(r,t)}catch(n){try{C.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 Ko(t){let e=Ot.join(t,"conversations.json"),o=Go(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}Vo(e,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Re={};ue(Re,{NAME:()=>Yo,VERSION:()=>zo,up:()=>tn});import*as T from"fs";import*as Nt from"path";var zo=3,Yo="recompute-last-message-by",Qo=new Set(["draft","confirmed","rejected","needs_review"]);function Xo(t){return T.existsSync(t)?JSON.parse(T.readFileSync(t,"utf-8")):null}function Zo(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";try{T.writeFileSync(r,o)}catch(n){try{T.unlinkSync(r)}catch{}throw n}try{T.renameSync(r,t)}catch(n){try{T.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 en(t,e){if(!t||t.length===0)return"them";let o=t.filter(i=>!Qo.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 tn(t){let e=Nt.join(t,"conversations.json"),o=Xo(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 f=Array.isArray(l.messages)?l.messages:[],d=en(f,r),h=d==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==d&&s++,l.lastMessageBy=d,l.conversationStatus=h,n++}if(n===0){console.log(" No conversations to recompute.");return}Zo(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 De={};ue(De,{NAME:()=>nn,VERSION:()=>on,up:()=>ln});import*as $ from"fs";import*as Lt from"path";var on=4,nn="split-connection-timestamps",rn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function sn(t){if(!$.existsSync(t))return null;let e=$.readFileSync(t,"utf-8");return e.charCodeAt(0)===65279&&(e=e.slice(1)),JSON.parse(e)}function cn(t,e){let o=JSON.stringify(e,null,2),r=t+".tmp";try{$.writeFileSync(r,o)}catch(n){try{$.unlinkSync(r)}catch{}throw n}try{$.renameSync(r,t)}catch(n){try{$.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 ln(t){let e=Lt.join(t,"people.json"),o=sn(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++,rn.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}cn(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 un=an(import.meta.url),fn=y.dirname(un),pn=y.dirname(y.dirname(fn));function dn(t){return t&&(t==="~"?Ne.homedir():t.startsWith("~/")||t.startsWith("~\\")?y.join(Ne.homedir(),t.slice(2)):t)}var N=process.env.DATA_DIR?y.resolve(dn(process.env.DATA_DIR)):pn,Y=y.join(N,"collected-profiles"),Q=y.join(N,"market-research"),k=y.join(N,".schema-version"),Ft=[y.join(Y,".schema-version"),y.join(Q,".schema-version")],H=4,P=[{version:1,module:$e},{version:2,module:Ie},{version:3,module:Re},{version:4,module:De}];(function(){P.sort((r,n)=>r.version-n.version);let e=new Set;for(let r of P){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=P.length?P[P.length-1].version:0;if(o!==H)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${H}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<P.length;r++){let n=r+1;if(P[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${P[r].version}`)}})();function qt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
8
+ `)}`;try{await $t.addMessage(s,l)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Fo=Lo(import.meta.url),Po=J.dirname(J.dirname(Fo)),Ee=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"collected-profiles"):J.join(Po,"collected-profiles"),xe=J.join(Ee,"run-log.json");function Mo(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";x.writeFileSync(r,o);for(let n=0;n<3;n++)try{x.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 Rt(){try{if(!x.existsSync(xe))return{runs:[]};let e=JSON.parse(x.readFileSync(xe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Dt(e){x.existsSync(Ee)||x.mkdirSync(Ee,{recursive:!0});try{Mo(xe,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ot(e,t="default"){let o=Rt();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),Dt(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Ce(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=Rt(),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(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}Dt(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";It({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 a from"fs";import*as Le from"os";import*as y from"path";import{fileURLToPath as un}from"url";var Ie={};ue(Ie,{NAME:()=>qo,VERSION:()=>Uo,up:()=>Ho});import*as C from"fs";import*as he from"path";var Uo=1,qo="normalize-jobs-and-questions",Bo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Jo=50;function Te(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function $e(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{C.writeFileSync(r,o)}catch(n){try{C.unlinkSync(r)}catch{}throw n}try{C.renameSync(r,e)}catch(n){try{C.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 Ho(e,t){let o=he.join(e,"jobs.json"),r=he.join(t,"scouted-jobs.json"),n=he.join(e,"application-questions.json"),i=Te(o)||{},s=Te(r)||{},c=0,l=[];for(let d of Object.keys(i)){if(!s[d])continue;let h=s[d],u=i[d];for(let p of Bo)h[p]!=null&&u[p]==null&&(u[p]=h[p]);l.push(d),c++}c>0?($e(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Te(n);if(f&&Array.isArray(f.applications)){let d={},h=0;for(let u of f.applications){let p=u.jobId||"unknown";d[p]||(d[p]={applications:[]});let A=(u.questions||[]).map(S=>{let w={type:S.type||"input",question:S.question||"",answer:S.answer||""};return S.options&&(S.options.length<=Jo?w.options=S.options:(w.optionsOmitted=!0,h++)),S.page&&(w.page=S.page),S.wasPreFilled&&(w.wasPreFilled=!0),S.wasRetry&&(w.wasRetry=!0),w});d[p].applications.push({applicationId:u.applicationId,date:u.date,result:u.result||"submitted",formPages:u.formPages||null,duration:u.duration||null,retries:u.retries||0,failedField:u.failedField||null,questionCount:u.questionCount||A.length,questions:A})}$e(n,d),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(d).length} unique jobs)`),h>0&&console.log(` Phase 2: Stripped bloated options from ${h} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let d of l)delete s[d];$e(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={};ue(Re,{NAME:()=>Go,VERSION:()=>Wo,up:()=>zo});import*as T from"fs";import*as Nt from"path";var Wo=2,Go="reset-unread-flags";function Vo(e){return T.existsSync(e)?JSON.parse(T.readFileSync(e,"utf-8")):null}function Ko(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{T.writeFileSync(r,o)}catch(n){try{T.unlinkSync(r)}catch{}throw n}try{T.renameSync(r,e)}catch(n){try{T.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 zo(e){let t=Nt.join(e,"conversations.json"),o=Vo(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}Ko(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var De={};ue(De,{NAME:()=>Qo,VERSION:()=>Yo,up:()=>on});import*as $ from"fs";import*as Lt from"path";var Yo=3,Qo="recompute-last-message-by",Xo=new Set(["draft","confirmed","rejected","needs_review"]);function Zo(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function en(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{$.writeFileSync(r,o)}catch(n){try{$.unlinkSync(r)}catch{}throw n}try{$.renameSync(r,e)}catch(n){try{$.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 tn(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!Xo.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 on(e){let t=Lt.join(e,"conversations.json"),o=Zo(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 f=Array.isArray(l.messages)?l.messages:[],d=tn(f,r),h=d==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==d&&s++,l.lastMessageBy=d,l.conversationStatus=h,n++}if(n===0){console.log(" No conversations to recompute.");return}en(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 Oe={};ue(Oe,{NAME:()=>rn,VERSION:()=>nn,up:()=>an});import*as I from"fs";import*as Ft from"path";var nn=4,rn="split-connection-timestamps",sn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function cn(e){if(!I.existsSync(e))return null;let t=I.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ln(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{I.writeFileSync(r,o)}catch(n){try{I.unlinkSync(r)}catch{}throw n}try{I.renameSync(r,e)}catch(n){try{I.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 an(e){let t=Ft.join(e,"people.json"),o=cn(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++,sn.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}ln(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 fn=un(import.meta.url),pn=y.dirname(fn),dn=y.dirname(y.dirname(pn));function mn(e){return e&&(e==="~"?Le.homedir():e.startsWith("~/")||e.startsWith("~\\")?y.join(Le.homedir(),e.slice(2)):e)}var N=process.env.DATA_DIR?y.resolve(mn(process.env.DATA_DIR)):dn,Y=y.join(N,"collected-profiles"),Q=y.join(N,"market-research"),k=y.join(N,".schema-version"),Pt=[y.join(Y,".schema-version"),y.join(Q,".schema-version")],H=4,P=[{version:1,module:Ie},{version:2,module:Re},{version:3,module:De},{version:4,module:Oe}];(function(){P.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of P){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=P.length?P[P.length-1].version:0;if(o!==H)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${H}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<P.length;r++){let n=r+1;if(P[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${P[r].version}`)}})();function Bt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
9
9
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
10
- `),process.exit(1));try{a.mkdirSync(N,{recursive:!0})}catch(e){e.code!=="EEXIST"&&(console.error(`
11
- [FATAL] Cannot create DATA_DIR (${N}): ${e.message}`),console.error(` Fix the path or permissions and try again.
12
- `),process.exit(1))}let t;try{t=a.statSync(N)}catch(e){console.error(`
13
- [FATAL] DATA_DIR (${N}) is not accessible: ${e.message}
14
- `),process.exit(1)}t.isDirectory()||(console.error(`
10
+ `),process.exit(1));try{a.mkdirSync(N,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
11
+ [FATAL] Cannot create DATA_DIR (${N}): ${t.message}`),console.error(` Fix the path or permissions and try again.
12
+ `),process.exit(1))}let e;try{e=a.statSync(N)}catch(t){console.error(`
13
+ [FATAL] DATA_DIR (${N}) is not accessible: ${t.message}
14
+ `),process.exit(1)}e.isDirectory()||(console.error(`
15
15
  [FATAL] DATA_DIR (${N}) 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.
16
- `),process.exit(1));for(let e of[Y,Q]){let o;try{o=a.lstatSync(e)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
17
- [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.
18
- `),process.exit(1))}}var z=y.join(N,".migration-lock");function mn(){let t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(z,t,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let e;try{e=JSON.parse(a.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(`
19
- [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}
16
+ `),process.exit(1));for(let t of[Y,Q]){let o;try{o=a.lstatSync(t)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
17
+ [FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
18
+ `),process.exit(1))}}var z=y.join(N,".migration-lock");function hn(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(z,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse(a.readFileSync(z,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(s){s.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}r&&i<n&&(console.error(`
19
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${z}
20
20
  `),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.
21
- `),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 a.writeFileSync(o,t),a.renameSync(o,z),!0}catch(r){try{a.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function Le(){try{if(JSON.parse(a.readFileSync(z,"utf-8")).pid!==process.pid)return;a.unlinkSync(z)}catch{}}var Pt=!1;function hn(){if(Pt)return;Pt=!0;let t=()=>{try{Le()}catch{}process.exit(1)};for(let e of["SIGINT","SIGTERM","SIGHUP"])try{process.on(e,t)}catch{}}function yn(){if(a.existsSync(k))return;let t=[],e=[];for(let i of Ft)if(a.existsSync(i))try{t.push({file:i,schema:ye(i)})}catch(s){e.push({file:i,err:s.message})}if(e.length>0){console.error(`
22
- [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(`
21
+ `),process.exit(1)),r&&i>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=z+".tmp";try{return a.writeFileSync(o,e),a.renameSync(o,z),!0}catch(r){try{a.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function Fe(){try{if(JSON.parse(a.readFileSync(z,"utf-8")).pid!==process.pid)return;a.unlinkSync(z)}catch{}}var Mt=!1;function yn(){if(Mt)return;Mt=!0;let e=()=>{try{Fe()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function gn(){if(a.existsSync(k))return;let e=[],t=[];for(let i of Pt)if(a.existsSync(i))try{e.push({file:i,schema:ye(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
22
+ [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
23
23
  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.
24
- `),process.exit(1)}if(t.length===0)return;let o=t.map(i=>i.schema.version);if(new Set(o).size>1){console.error(`
25
- [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.
26
- `),process.exit(1)}let r=t[0].schema,n=k+".tmp";try{a.writeFileSync(n,JSON.stringify(r,null,2)),a.renameSync(n,k)}catch(i){try{a.unlinkSync(n)}catch{}throw i}for(let i of Ft)if(a.existsSync(i))try{a.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${k}`)}function gn(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 ye(t){let e=a.readFileSync(t,"utf-8");return e.charCodeAt(0)===65279&&(e=e.slice(1)),JSON.parse(e)}function Mt(){if(yn(),!a.existsSync(k))return{version:0,migrations:[]};let t;try{t=ye(k)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
24
+ `),process.exit(1)}if(e.length===0)return;let o=e.map(i=>i.schema.version);if(new Set(o).size>1){console.error(`
25
+ [FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
26
+ `),process.exit(1)}let r=e[0].schema,n=k+".tmp";try{a.writeFileSync(n,JSON.stringify(r,null,2)),a.renameSync(n,k)}catch(i){try{a.unlinkSync(n)}catch{}throw i}for(let i of Pt)if(a.existsSync(i))try{a.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${k}`)}function Sn(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function ye(e){let t=a.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ut(){if(gn(),!a.existsSync(k))return{version:0,migrations:[]};let e;try{e=ye(k)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
27
27
  [FATAL] ${k} 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.
28
- `),process.exit(1)}let e=gn(t);return e===null&&(console.error(`
29
- [FATAL] ${k} 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.
30
- `),process.exit(1)),e}function Bt(t){try{a.chmodSync(t,384)}catch{}}function Sn(t){if(qt(),a.existsSync(k))try{if(a.lstatSync(k).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${k}. 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=k+".tmp";try{a.writeFileSync(e,JSON.stringify(t,null,2)),Bt(e),a.renameSync(e,k)}catch(o){try{a.unlinkSync(e)}catch{}throw o}}function Ut(t,e){if(!a.existsSync(t))return;let o=`.pre-v${String(e).padStart(3,"0")}.backup`,r=a.readdirSync(t).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return a.statSync(y.join(t,c)).isFile()}catch{return!1}}),n=0,i=0,s=[];for(let c of r){let l=y.join(t,c),f=y.join(t,c+o);if(a.existsSync(f)){i++;continue}try{Ht(l,f),n++}catch(d){s.push({file:c,err:d.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${y.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 ${y.basename(t)}/ (${o})${c}`)}}var Oe=!1;async function Jt(){if(Oe)return;qt(),An();let e=Mt().version;if(e===H){Oe=!0;return}hn(),mn(),process.on("exit",Le),e>H&&(console.error(`
31
- [FATAL] Your data schema is at v${e}, but this plugin build only understands up to v${H}.`),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.
28
+ `),process.exit(1)}let t=Sn(e);return t===null&&(console.error(`
29
+ [FATAL] ${k} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
30
+ `),process.exit(1)),t}function Jt(e){try{a.chmodSync(e,384)}catch{}}function bn(e){if(Bt(),a.existsSync(k))try{if(a.lstatSync(k).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${k}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=k+".tmp";try{a.writeFileSync(t,JSON.stringify(e,null,2)),Jt(t),a.renameSync(t,k)}catch(o){try{a.unlinkSync(t)}catch{}throw o}}function qt(e,t){if(!a.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=a.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return a.statSync(y.join(e,c)).isFile()}catch{return!1}}),n=0,i=0,s=[];for(let c of r){let l=y.join(e,c),f=y.join(e,c+o);if(a.existsSync(f)){i++;continue}try{Wt(l,f),n++}catch(d){s.push({file:c,err:d.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${y.basename(e)}/: `+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 ${y.basename(e)}/ (${o})${c}`)}}var Ne=!1;async function Ht(){if(Ne)return;Bt(),_n();let t=Ut().version;if(t===H){Ne=!0;return}yn(),hn(),process.on("exit",Fe),t>H&&(console.error(`
31
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${H}.`),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.
32
32
  `),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${H}.
33
33
  `),process.exit(1)),console.log(`
34
- \u{1F4E6} Schema migration: v${e} \u2192 v${H}`);let o=_n();if(!o.ok){console.error(`
34
+ \u{1F4E6} Schema migration: v${t} \u2192 v${H}`);let o=jn();if(!o.ok){console.error(`
35
35
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of o.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
36
36
  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'.
37
- `),process.exit(1)}let r=P.filter(n=>n.version>e);for(let n of r){console.log(`
38
- Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{Ut(Y,n.version),Ut(Q,n.version)}catch(l){console.error(`
37
+ `),process.exit(1)}let r=P.filter(n=>n.version>t);for(let n of r){console.log(`
38
+ Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{qt(Y,n.version),qt(Q,n.version)}catch(l){console.error(`
39
39
  [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.
40
40
  `),process.exit(1)}let c=n.module;try{await c.up(Y,Q)}catch(l){console.error(`
41
- [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let f=En(s);f.ok?(console.error(` \u2713 Auto-rollback restored ${f.restored} files. Schema stays at v${e}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
41
+ [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let f=En(s);f.ok?(console.error(` \u2713 Auto-rollback restored ${f.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
42
42
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${f.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
43
43
  `))}catch(f){console.error(` [!] Auto-rollback CRASHED while restoring: ${f.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
44
- `)}process.exit(1)}try{let l=new Date().toISOString(),f={version:n.version,name:c.NAME||i,appliedAt:l},d=Mt();d.version=n.version,d.migratedAt=l,d.migrations=d.migrations||[],d.migrations.push(f),Sn(d)}catch(l){console.error(`
45
- [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.
46
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{At()}catch{}try{yt()}catch{}Oe=!0,Le(),console.log(`
44
+ `)}process.exit(1)}try{let l=new Date().toISOString(),f={version:n.version,name:c.NAME||i,appliedAt:l},d=Ut();d.version=n.version,d.migratedAt=l,d.migrations=d.migrations||[],d.migrations.push(f),bn(d)}catch(l){console.error(`
45
+ [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${n.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
46
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{_t()}catch{}try{gt()}catch{}Ne=!0,Fe(),console.log(`
47
47
  \u2713 Schema is now at v${H}
48
- `)}var bn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function wn(t){let e=t.toLowerCase();return bn.some(o=>o.test(e))}var vn=6e4;function kn(){let t=Date.now(),e=[];for(let o of[N,Y,Q]){if(!a.existsSync(o))continue;let r;try{r=a.readdirSync(o)}catch{continue}for(let n of r){if(!wn(n))continue;let i=y.join(o,n);try{let s=a.statSync(i);if(!s.isFile()||t-s.mtimeMs<vn)continue;e.push({dir:o,file:n,fullPath:i})}catch{}}}return e}function An({verbose:t=!1}={}){let e=kn();if(e.length===0)return t&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of e)try{a.unlinkSync(r.fullPath),o++,t&&console.log(` Removed orphan: ${y.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 _n(){let t=[];for(let e of[Y,Q]){if(!a.existsSync(e))continue;let o=a.readdirSync(e).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=y.join(e,r);try{ye(n)}catch(i){t.push({dir:y.basename(e),file:r,err:i.message})}}}return t.length===0?{ok:!0}:{ok:!1,broken:t}}function En(t){let e=[],o=[];for(let i of[Y,Q]){if(!a.existsSync(i))continue;let s=a.readdirSync(i).filter(c=>c.endsWith(t));for(let c of s){let l=y.join(i,c),f=c.slice(0,-t.length),d=y.join(i,f);try{f.toLowerCase().endsWith(".json")?ye(l):a.accessSync(l,a.constants.R_OK),e.push({backupPath:l,originalPath:d,fileName:c,dir:i})}catch(h){o.push(`${y.basename(i)}/${c}: ${h.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{Ht(i,s),r++}catch(f){n.push(`${y.basename(l)}/${c}: ${f.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function Ht(t,e){let o=e+".tmp";try{a.copyFileSync(t,o),Bt(o)}catch(r){try{a.unlinkSync(o)}catch{}throw r}try{a.renameSync(o,e)}catch(r){try{a.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 Jt();var ie=process.argv.slice(2),X=parseInt(ie.find(t=>t.startsWith("--max="))?.split("=")[1]||"200"),Wt=parseInt(ie.find(t=>t.startsWith("--pages="))?.split("=")[1]||"20"),Gt=ie.find(t=>t.startsWith("--url="))?.split("=").slice(1).join("="),jn=ie.includes("--list"),Fe=ie.includes("--verbose");function xn(){if(Gt)return[Gt];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 Cn(){let t=vt();console.log(`
49
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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
50
- `)}async function Tn(){if(console.log(`
48
+ `)}var wn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function vn(e){let t=e.toLowerCase();return wn.some(o=>o.test(t))}var kn=6e4;function An(){let e=Date.now(),t=[];for(let o of[N,Y,Q]){if(!a.existsSync(o))continue;let r;try{r=a.readdirSync(o)}catch{continue}for(let n of r){if(!vn(n))continue;let i=y.join(o,n);try{let s=a.statSync(i);if(!s.isFile()||e-s.mtimeMs<kn)continue;t.push({dir:o,file:n,fullPath:i})}catch{}}}return t}function _n({verbose:e=!1}={}){let t=An();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{a.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${y.basename(r.dir)}/${r.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${r.fullPath}: ${n.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function jn(){let e=[];for(let t of[Y,Q]){if(!a.existsSync(t))continue;let o=a.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=y.join(t,r);try{ye(n)}catch(i){e.push({dir:y.basename(t),file:r,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function En(e){let t=[],o=[];for(let i of[Y,Q]){if(!a.existsSync(i))continue;let s=a.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=y.join(i,c),f=c.slice(0,-e.length),d=y.join(i,f);try{f.toLowerCase().endsWith(".json")?ye(l):a.accessSync(l,a.constants.R_OK),t.push({backupPath:l,originalPath:d,fileName:c,dir:i})}catch(h){o.push(`${y.basename(i)}/${c}: ${h.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 t)try{Wt(i,s),r++}catch(f){n.push(`${y.basename(l)}/${c}: ${f.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function Wt(e,t){let o=t+".tmp";try{a.copyFileSync(e,o),Jt(o)}catch(r){try{a.unlinkSync(o)}catch{}throw r}try{a.renameSync(o,t)}catch(r){try{a.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let n=new Error(`File locked: ${t} (${r.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw n.code=r.code,n}throw r}}await Ht();var ie=process.argv.slice(2),X=parseInt(ie.find(e=>e.startsWith("--max="))?.split("=")[1]||"200"),Gt=parseInt(ie.find(e=>e.startsWith("--pages="))?.split("=")[1]||"20"),Vt=ie.find(e=>e.startsWith("--url="))?.split("=").slice(1).join("="),xn=ie.includes("--list"),Pe=ie.includes("--verbose");function Cn(){if(Vt)return[Vt];let e=process.env.LINKEDIN_SCOUT_URLS;if(e)return e.split(",").map(o=>o.trim()).filter(Boolean);let t=process.env.LINKEDIN_SEARCH_URL;return t?[t]:[]}function Tn(){let e=kt();console.log(`
49
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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: ${e.totalJobs}`),console.log(` Discovered recruiters: ${e.totalRecruiters}`),console.log(` Last scout: ${e.lastScoutDate||"never"}`),console.log(` Profile visits: ${e.totalVisited} unique (${e.todayVisited} today)`),e.topTech.length>0&&console.log(` Top tech: ${e.topTech.join(", ")}`),e.topCompanies.length>0&&console.log(` Top companies: ${e.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
50
+ `)}async function $n(){if(console.log(`
51
51
  LinkedIn Job Scout
52
- `),jn){Cn();return}let t=xn();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=Dt("scout",`max=${X},urls=${t.length}`),o={scouted:0,recruitersFound:0,skipped:0,skippedApplied:0,alreadyConnected:0,pages:0,errors:0,urlsProcessed:0},r=me(),n=xt(),i=jt();console.log(` Scout URLs: ${t.length}`),t.forEach((l,f)=>console.log(` ${f+1}. ${l.slice(0,80)}...`)),console.log(` Max jobs: ${X} | Max pages per URL: ${Wt}
53
- `);let{browser:s,page:c}=await st();try{for(let l of t){if(o.scouted>=X)break;o.urlsProcessed++,console.log(`
54
- \u2550\u2550\u2550 Scout URL ${o.urlsProcessed}/${t.length}: ${l.slice(0,70)}... \u2550\u2550\u2550`),await c.goto(l,{waitUntil:"domcontentloaded",timeout:6e4}),await D(3e3);let f=0,d=!1;for(let h=0;h<Wt&&o.scouted<X&&!d;h++){o.pages++,console.log(`
55
- \u2500\u2500 Page ${h+1} \u2500\u2500`),await at(c,l),await it(c),await D(1e3);let u=await ct(c,{easyApplyOnly:!1});console.log(` Found ${u.length} jobs on page`);for(let p of u){if(o.scouted>=X)break;let A=p.href?.match(/jobs\/view\/(\d+)/)?.[1]||p.id?.match(/\d+/)?.[0];if(A&&r[A]){o.skipped++;continue}if(A&&n[A]){o.skippedApplied++;continue}try{let S=await c.$(`a[data-control-id="${p.dataId}"]`);if(!S)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 S.click(),await D(1500+Math.random()*1500);for(let M=0;M<8;M++){let U=await c.evaluate(ge=>{let Se=document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24"),ce=document.querySelector(".jobs-description__content"),le=Se?.innerText?.trim()?.slice(0,80)||"",be=ce?.innerText?.trim()?.length||0;return{title:le,descLen:be,titleChanged:le!==ge&&le.length>0}},w);if(U.titleChanged&&U.descLen>50)break;await D(600)}let g=await ft(c),L=await ut(c);if(A&&(gt(A,{title:p.jobTitle,company:g.companyName||p.companyName,companyUrl:g.companyUrl,location:p.location,salary:p.salary,url:p.href,isEasyApply:p.isEasyApply,applyType:p.applyType||(p.isEasyApply?"easy-apply":"external"),externalApplyUrl:g.externalApplyUrl,description:g.description,techStack:g.techStack,jobTags:g.jobTags,seniority:g.seniority,employmentType:g.employmentType,industries:g.industries,jobFunction:g.jobFunction,postedTime:g.postedTime,applicantCount:g.applicantCount,companySize:g.companySize,workplaceType:g.workplaceType,contractType:g.contractType,recruiterUrl:L?.profileUrl||null}),o.scouted++),g.companyUrl&&wt(g.companyUrl,{name:g.companyName||p.companyName,about:g.aboutCompany,size:g.companySize,industries:g.industries,jobId:A,recruiterUrl:L?.profileUrl}),L?.profileUrl){let U=i[L.profileUrl]?.connectionStatus==="connected";bt(L.profileUrl,{name:L.name,source:"scout",role:"recruiter",jobId:A,jobTitle:p.jobTitle,isConnected:U}),o.recruitersFound++,U&&o.alreadyConnected++}if(Fe){let M=g.techStack?.slice(0,5).join(", ")||"none";console.log(` [${o.scouted}] ${p.jobTitle?.slice(0,40)} @ ${p.companyName?.slice(0,20)} | ${M}${L?" | \u{1F464} "+L.name:""}`)}else o.scouted%10===0&&console.log(` Scouted: ${o.scouted} (${o.recruitersFound} recruiters)`)}catch(S){o.errors++,f++,Fe&&console.error(` Error: ${S.message?.slice(0,80)}`);let w=(S.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"),d=!0;break}if(f>=5){console.log(" \u26A0 5 consecutive errors \u2014 stopping scout"),d=!0;break}continue}f=0}if(d)break;if(o.scouted<X)try{if(!await lt(c)){console.log(" No more pages.");break}await D(2e3)}catch(p){console.log(` \u26A0 Pagination failed: ${p.message?.slice(0,60)}`);break}}if(d)break}console.log(`
56
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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: ${o.urlsProcessed}/${t.length}`),console.log(` Pages scanned: ${o.pages}`),console.log(` Jobs scouted: ${o.scouted}`),console.log(` Skipped (existing): ${o.skipped}`),console.log(` Skipped (applied): ${o.skippedApplied}`),console.log(` Recruiters found: ${o.recruitersFound} (${o.alreadyConnected} already connected)`),console.log(` Errors: ${o.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
57
- `),xe(e,"success",o)}catch(l){console.error(`
58
- Error:`,l.message),Fe&&console.error(l.stack),xe(e,"error",o,l.message)}finally{await s.close().catch(()=>{})}}Tn().catch(t=>{console.error("Scout failed:",t),process.exit(1)});
52
+ `),xn){Tn();return}let e=Cn();e.length===0&&(console.error("No search URL. Set LINKEDIN_SCOUT_URL or LINKEDIN_SCOUT_URLS in .env, or use --url=..."),process.exit(1));let t=Ot("scout",`max=${X},urls=${e.length}`),o={scouted:0,recruitersFound:0,skipped:0,skippedApplied:0,alreadyConnected:0,pages:0,errors:0,urlsProcessed:0},r=me(),n=Ct(),i=xt();console.log(` Scout URLs: ${e.length}`),e.forEach((l,f)=>console.log(` ${f+1}. ${l.slice(0,80)}...`)),console.log(` Max jobs: ${X} | Max pages per URL: ${Gt}
53
+ `);let{browser:s,page:c}=await it();try{for(let l of e){if(o.scouted>=X)break;o.urlsProcessed++,console.log(`
54
+ \u2550\u2550\u2550 Scout URL ${o.urlsProcessed}/${e.length}: ${l.slice(0,70)}... \u2550\u2550\u2550`),await c.goto(l,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3);let f=0,d=!1;for(let h=0;h<Gt&&o.scouted<X&&!d;h++){o.pages++,console.log(`
55
+ \u2500\u2500 Page ${h+1} \u2500\u2500`),await ut(c,l),await ct(c),await j(1e3);let u=await lt(c,{easyApplyOnly:!1});console.log(` Found ${u.length} jobs on page`);for(let p of u){if(o.scouted>=X)break;let A=p.href?.match(/jobs\/view\/(\d+)/)?.[1]||p.id?.match(/\d+/)?.[0];if(A&&r[A]){o.skipped++;continue}if(A&&n[A]){o.skippedApplied++;continue}try{let S=await c.$(`a[data-control-id="${p.dataId}"]`);if(!S)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 S.click(),await j(1500+Math.random()*1500);for(let M=0;M<8;M++){let U=await c.evaluate(ge=>{let Se=document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24"),ce=document.querySelector(".jobs-description__content"),le=Se?.innerText?.trim()?.slice(0,80)||"",be=ce?.innerText?.trim()?.length||0;return{title:le,descLen:be,titleChanged:le!==ge&&le.length>0}},w);if(U.titleChanged&&U.descLen>50)break;await j(600)}let g=await pt(c),L=await ft(c);if(A&&(St(A,{title:p.jobTitle,company:g.companyName||p.companyName,companyUrl:g.companyUrl,location:p.location,salary:p.salary,url:p.href,isEasyApply:p.isEasyApply,applyType:p.applyType||(p.isEasyApply?"easy-apply":"external"),externalApplyUrl:g.externalApplyUrl,description:g.description,techStack:g.techStack,jobTags:g.jobTags,seniority:g.seniority,employmentType:g.employmentType,industries:g.industries,jobFunction:g.jobFunction,postedTime:g.postedTime,applicantCount:g.applicantCount,companySize:g.companySize,workplaceType:g.workplaceType,contractType:g.contractType,recruiterUrl:L?.profileUrl||null}),o.scouted++),g.companyUrl&&vt(g.companyUrl,{name:g.companyName||p.companyName,about:g.aboutCompany,size:g.companySize,industries:g.industries,jobId:A,recruiterUrl:L?.profileUrl}),L?.profileUrl){let U=i[L.profileUrl]?.connectionStatus==="connected";wt(L.profileUrl,{name:L.name,source:"scout",role:"recruiter",jobId:A,jobTitle:p.jobTitle,isConnected:U}),o.recruitersFound++,U&&o.alreadyConnected++}if(Pe){let M=g.techStack?.slice(0,5).join(", ")||"none";console.log(` [${o.scouted}] ${p.jobTitle?.slice(0,40)} @ ${p.companyName?.slice(0,20)} | ${M}${L?" | \u{1F464} "+L.name:""}`)}else o.scouted%10===0&&console.log(` Scouted: ${o.scouted} (${o.recruitersFound} recruiters)`)}catch(S){o.errors++,f++,Pe&&console.error(` Error: ${S.message?.slice(0,80)}`);let w=(S.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"),d=!0;break}if(f>=5){console.log(" \u26A0 5 consecutive errors \u2014 stopping scout"),d=!0;break}continue}f=0}if(d)break;if(o.scouted<X)try{if(!await at(c)){console.log(" No more pages.");break}await j(2e3)}catch(p){console.log(` \u26A0 Pagination failed: ${p.message?.slice(0,60)}`);break}}if(d)break}console.log(`
56
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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: ${o.urlsProcessed}/${e.length}`),console.log(` Pages scanned: ${o.pages}`),console.log(` Jobs scouted: ${o.scouted}`),console.log(` Skipped (existing): ${o.skipped}`),console.log(` Skipped (applied): ${o.skippedApplied}`),console.log(` Recruiters found: ${o.recruitersFound} (${o.alreadyConnected} already connected)`),console.log(` Errors: ${o.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
57
+ `),Ce(t,"success",o)}catch(l){console.error(`
58
+ Error:`,l.message),Pe&&console.error(l.stack),Ce(t,"error",o,l.message)}finally{await s.close().catch(()=>{})}}$n().catch(e=>{console.error("Scout failed:",e),process.exit(1)});