ilml-plugin-linkedin 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,57 +1,266 @@
1
- var Dt=Object.defineProperty;var Ve=(e,t)=>()=>(e&&(t=e(e=0)),t);var de=(e,t)=>{for(var o in t)Dt(e,o,{get:t[o],enumerable:!0})};async function $(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}async function We(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let n of t){let s=n.innerText||"",r=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),l=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),i=s.includes("Get hired faster")||s.includes("Get hired 2x");if(r||l||i){let a=n.querySelector('button[aria-label="Dismiss"]')||n.querySelector("button.artdeco-modal__dismiss")||n.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:s.substring(0,80)};let f=n.querySelectorAll("button");for(let c of f){let m=c.innerText?.trim().toLowerCase()||"",u=c.getAttribute("aria-label")?.toLowerCase()||"";if(m==="not now"||m==="no thanks"||m==="dismiss"||u.includes("dismiss"))return c.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let n=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(n)return n.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var se=Ve(()=>{});var tt={};de(tt,{extractExperienceFromDetails:()=>io});async function io(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let n=e.url();if(/\/(login|authwall|checkpoint)/i.test(n))throw new Error(`Session expired \u2014 bounced to ${n} when fetching /details/experience/`);for(let r=0;r<5;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(900);await $(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)s++,await $(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(700);return await e.evaluate(()=>{let r=document.querySelector("main");if(!r)return[];function l(c){let m=[];for(let u of c.querySelectorAll("div")){let h=Array.from(u.children).filter(w=>w.tagName==="DIV");if(h.length<3)continue;let v=h.filter(w=>(w.textContent||"").trim().length>50);v.length<3||(u.textContent||"").length<500||m.push({el:u,count:v.length,totalText:(u.textContent||"").length})}return m.sort((u,h)=>h.count-u.count||u.totalText-h.totalText),m[0]?.el}let i=l(r);if(!i)return[];let a=Array.from(i.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function f(c){let m=c[0]||null,u=null,h=null;if(c[1]){let b=c[1].split("\xB7").map(E=>E.trim());u=b[0]||null,b[1]&&(h=b[1])}let v=c.findIndex(b=>/(\d{4}|present)/i.test(b)&&/(-|–|—)/i.test(b)&&b.length<80),w=null,x=null;if(v>=0){let b=c[v].split("\xB7").map(E=>E.trim());w=b[0]||null,b[1]&&(x=b[1])}let A=null,ee=-1;if(v>=0&&c[v+1]){let b=c[v+1],E=/^[>*\-•]|^&gt;/.test(b),ce=/https?:\/\//.test(b),ue=/\d{4}/.test(b),Q=/,/.test(b)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(b);!E&&!ce&&!ue&&b.length<100&&Q&&(A=b,ee=v+1)}let te=null,oe=-1,H=c[c.length-1];if(H&&/and\s+\+\d+\s+skills?$/i.test(H)){oe=c.length-1;let b=H.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);b&&(te={listed:b[1].split(",").map(E=>E.trim()),additional:parseInt(b[2],10)})}let ie=new Set([0,1,v,ee,oe].filter(b=>b>=0)),le=c.filter((b,E)=>!ie.has(E)),ae=le.length>0?le.join(`
1
+ var Wt=Object.defineProperty;var nt=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{for(var n in t)Wt(e,n,{get:t[n],enumerable:!0})};async function k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ot(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),l=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),i=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||l||i){let a=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:r.substring(0,80)};let f=o.querySelectorAll("button");for(let c of f){let m=c.innerText?.trim().toLowerCase()||"",d=c.getAttribute("aria-label")?.toLowerCase()||"";if(m==="not now"||m==="no thanks"||m==="dismiss"||d.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var ie=nt(()=>{});var mt={};pe(mt,{extractCertificationsFromDetails:()=>$n,extractEducationFromDetails:()=>Cn,extractExperienceFromDetails:()=>vn,extractFeaturedFromDetails:()=>kn,extractRecommendationsFromDetails:()=>En,extractSkillsFromDetails:()=>xn});async function vn(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)r++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function l(c){let m=[];for(let d of c.querySelectorAll("div")){let p=Array.from(d.children).filter(b=>b.tagName==="DIV");if(p.length<3)continue;let v=p.filter(b=>(b.textContent||"").trim().length>50);v.length<3||(d.textContent||"").length<500||m.push({el:d,count:v.length,totalText:(d.textContent||"").length})}return m.sort((d,p)=>p.count-d.count||d.totalText-p.totalText),m[0]?.el}let i=l(s);if(!i)return[];let a=Array.from(i.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function f(c){let m=c[0]||null,d=null,p=null;if(c[1]){let y=c[1].split("\xB7").map(A=>A.trim());d=y[0]||null,y[1]&&(p=y[1])}let v=c.findIndex(y=>/(\d{4}|present)/i.test(y)&&/(-|–|—)/i.test(y)&&y.length<80),b=null,E=null;if(v>=0){let y=c[v].split("\xB7").map(A=>A.trim());b=y[0]||null,y[1]&&(E=y[1])}let W=null,we=-1;if(v>=0&&c[v+1]){let y=c[v+1],A=/^[>*\-•]|^&gt;/.test(y),ne=/https?:\/\//.test(y),T=/\d{4}/.test(y),de=/,/.test(y)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(y);!A&&!ne&&!T&&y.length<100&&de&&(W=y,we=v+1)}let $=null,te=-1,P=c[c.length-1];if(P&&/and\s+\+\d+\s+skills?$/i.test(P)){te=c.length-1;let y=P.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);y&&($={listed:y[1].split(",").map(A=>A.trim()),additional:parseInt(y[2],10)})}let Y=new Set([0,1,v,we,te].filter(y=>y>=0)),I=c.filter((y,A)=>!Y.has(A)),be=I.length>0?I.join(`
2
2
 
3
- `):null;return{title:m,company:u,employmentType:h,dates:w,duration:x,location:A,description:ae,skills:te,_raw:c}}return a.map(c=>{let u=(c.innerText||"").trim().split(`
4
- `).map(h=>h.trim()).filter(h=>h&&h.length<5e3);return f(u)}).filter(c=>c.title)})}catch(n){if(/session expired|bounced to|authwall|checkpoint/i.test(n.message||""))throw n;return console.error(`extractExperienceFromDetails failed for ${t}: ${n.message?.slice(0,120)}`),[]}}var ot=Ve(()=>{se()});import qt from"puppeteer";import{addExtra as Ut}from"puppeteer-extra";import Bt from"puppeteer-extra-plugin-stealth";se();import{getPluginConfig as Ot}from"@ilivemylife/graph-sdk";var jt=await Ot();for(let[e,t]of Object.entries(jt))process.env[e]===void 0&&(process.env[e]=t);var Nt=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),kn=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Lt=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]));import Je from"fs";import Mt from"path";var Ft="cookies.json";function Pt(){let e=process.env.ILML_SCOPE_DIR;return e?Mt.join(e,"plugins-state","linkedin","cookies.json"):Ft}function Ge(){let e=Pt();if(!Je.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Je.readFileSync(e,"utf-8")}catch(n){throw new Error(`Failed to read cookies at ${e}: ${n.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}var Ye=Ut(qt);Ye.use(Bt());async function ze(){let e=await Ye.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
5
- Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let o=await e.newPage();await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let n=Ge();await o.setCookie(...n),console.log(" Browser launched, cookies loaded.")}catch(n){console.error(`
6
- [!] ${n.message}
7
- `),await e.close(),process.exit(1)}return{browser:e,page:o}}se();import"dotenv/config";import*as k from"fs";import*as C from"path";import{fileURLToPath as Ht}from"url";var Vt=Ht(import.meta.url),Wt=C.dirname(C.dirname(Vt)),M=process.env.DATA_DIR?C.resolve(process.env.DATA_DIR,"collected-profiles"):C.join(Wt,"collected-profiles"),ge=C.join(M,"people.json"),qn=C.join(M,"jobs.json"),Un=C.join(M,"quota.json"),Ze=C.join(M,"conversations.json"),Bn=C.join(M,"sync-state.json"),Hn=C.join(M,"application-questions.json"),ye=C.join(M,"profile-history");var X=null,Jt=null,Gt=null,Z=null,Yt=null,zt=null;function Xe(){X=null,Jt=null,Gt=null,Z=null,Yt=null,zt=null}function we(){k.existsSync(M)||k.mkdirSync(M,{recursive:!0})}function be(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";k.writeFileSync(n,o);for(let s=0;s<3;s++)try{k.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw r}}function Se(e,t){if(!k.existsSync(e))return null;try{let o=JSON.parse(k.readFileSync(e,"utf-8"));try{k.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${C.resolve(e)}`);let n=e+".backup";if(k.existsSync(n))try{let s=JSON.parse(k.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{k.copyFileSync(n,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{k.copyFileSync(e,e+".corrupted")}catch{}return null}}function Kt(){return new Date().toISOString().split("T")[0]}var Qt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt"],Zt=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function ve(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Xt(){k.existsSync(ye)||k.mkdirSync(ye,{recursive:!0})}function et(e){let t=ve(e);return t?C.join(ye,`${t}.json`):null}function eo(e){let t=et(e);return t?Se(t,`profile-history/${ve(e)}.json`)||[]:[]}function to(e,t){let o=et(e);if(!o)return;Xt();let n=eo(e);n.unshift(t);try{be(o,n)}catch(s){console.error(`[!] Failed to append profile-history for ${ve(e)}: ${s.message}`)}}function Ke(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Qe(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function oo(e,t){if(!e)return[];let o=[];for(let n of Zt){let s=e[n],r=t[n];Ke(s)||Ke(r)||Qe(s)!==Qe(r)&&o.push(n)}return o}function no(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[n,s]of Object.entries(e))t.has(n)||(o[n]=s);return o}function W(){return X||(we(),X=Se(ge,"people.json")||{},X)}function so(e){we(),X=e;try{be(ge,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${C.resolve(ge)}`)}}function ke(){return Z||(we(),Z=Se(Ze,"conversations.json")||{},ro(Z),Z)}function ro(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let s=(o.messages||[]).find(r=>r.status==="draft");s&&o.draftStatus&&o.draftStatus!=="pending"&&(s.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{be(Ze,e)}catch{}}}function Ce(e,t={}){if(!e)return null;let o=W(),n=Kt(),s=new Date().toISOString(),r=o[e];if(r){let l=oo(r,t);l.length>0&&(to(e,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:l,snapshot:no(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=n,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let i of Qt)if(t[i]!=null){if(Array.isArray(t[i])&&t[i].length===0&&Array.isArray(r[i])&&r[i].length>0)continue;r[i]=t[i]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,firstSeen:n,lastSeen:n,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return so(o),o[e]}async function lo(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let n=e.url();return n.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${n.slice(0,80)}`),!0}async function nt(e,t,o={}){let{extractExperience:n=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await We(e)&&(console.log(" Dismissed Premium overlay"),await $(1500),await lo(e,t));let r=0;for(let a=0;a<2;a++){let f=await e.evaluate(()=>document.body.scrollHeight);for(let m=1;m<=6;m++)await e.evaluate(u=>window.scrollTo(0,u),f*m/6),await $(900);let c=await e.evaluate(()=>document.body.scrollHeight);if(c===r)break;r=c}await $(800);let l=await e.evaluate(()=>{let a=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),f=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),c=p=>{let g=(p||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(g)},m={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},u=document.querySelector("main");if(!u)return m;let h=[...Array.from(u.querySelectorAll("h1")),...Array.from(u.querySelectorAll("h2"))],v=Array.from(u.querySelectorAll("h2")),w=h.find(p=>{let g=p.textContent&&p.textContent.trim(),y=(g||"").replace(/\s*\(\d+\)$/,"").trim();return g&&g.length>1&&g.length<100&&!a.has(y)&&!f.has(y)}),x=w?w.textContent.trim():null,A=w?w.parentElement:null;for(;A&&A!==u&&!Array.from(A.children).filter(g=>g.tagName==="P").some(g=>{let y=g.textContent&&g.textContent.trim();return y&&y.length>5&&!c(y)});)A=A.parentElement;let ee=null,te=null,oe=null,H=null;if(A&&A!==u){let p=Array.from(A.children).filter(y=>y.tagName==="P").filter(y=>{let P=y.textContent&&y.textContent.trim();return P&&P.length>5&&!c(P)});if(p[0]&&(ee=p[0].textContent.trim()),p[1]){let y=p[1].textContent.trim().split(/\s*[·•]\s*/);te=y[0]||null,y.length>1&&(oe=y.slice(1).join(" \xB7 "))}let g=Array.from(A.children).filter(y=>y.tagName==="DIV");for(let y=g.length-1;y>=0;y--){let P=g[y].textContent&&g[y].textContent.trim();if(P&&!(x&&P.startsWith(x))&&(H=P.split(/[·•]/)[0].trim(),H))break}}let ie=null;if(A){let p=A.querySelectorAll("p, span, div");for(let g of p){let y=(g.textContent||"").trim().replace(/^[·•]\s*/,"");if(y==="1st"||y==="2nd"||y==="3rd"){ie=y;break}}}let le=!!u.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),ae=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),b=ae&&ae.src||null,E=u.textContent||"",ce=null,ue=E.match(/(\d+\+?)\s+connections\b/i);ue&&(ce=ue[1]+" connections");let Q=null,Me=E.match(/(\d+)\s+mutual connection/i),Fe=E.match(/and\s+(\d+)\s+other mutual/i),Et=E.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Me?Q=parseInt(Me[1],10):Fe?Q=2+parseInt(Fe[1],10):Et&&(Q=2);let Pe=null,qe=null,Ue=v.find(p=>p.textContent&&p.textContent.trim()==="About");if(Ue){let p=Ue.parentElement;for(;p&&p.tagName!=="SECTION";)p=p.parentElement;if(p){let g=(p.textContent||"").trim();g=g.replace(/^About\s*/,"").trim();let y=g.match(/Top skills\s*(.+?)$/i);if(y){let he=y[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Rt=>Rt.trim()).filter(Boolean);he.length>0&&he.length<10&&(qe=he)}g=g.split(/\n?…\s*more/i)[0].trim(),g=g.split(/\n?\.\.\.\s*more/i)[0].trim(),g=g.split(/\bTop skills\b/i)[0].trim(),g=g.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Pe=g||null}}let Be=null,He=v.find(p=>p.textContent&&p.textContent.trim()==="Activity");if(He){let p=He.parentElement;for(;p&&p.tagName!=="SECTION";)p=p.parentElement;if(p){let g=(p.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);g&&(Be=parseInt(g[1].replace(/,/g,""),10))}}let _t=[...new Set(v.map(p=>(p.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(p=>p&&p.length>1&&p.length<60&&p!==x).filter(p=>a.has(p)))],ne=document.body.textContent||"",It=/#OpenToWork\b/i.test(ne)||/\bOpen to work\b/.test(ne),Tt=/#Hiring\b/i.test(ne)||/\bI'?m hiring\b/i.test(ne)||/\bWe are hiring\b/i.test(ne);return{name:x,title:ee,location:H,currentCompany:te,currentSchool:oe,connectionDegree:ie,hasVerifiedBadge:le,photoUrl:b,connectionsLevel:ce,mutualConnectionsCount:Q,followers:Be,openToWork:It,hiring:Tt,about:Pe,topSkills:qe,availableSections:_t}});console.log(`Viewed: ${l.name} - ${l.title}`);let i=null;if(n){let{extractExperienceFromDetails:a}=await Promise.resolve().then(()=>(ot(),tt));i=await a(e,t),console.log(` + Experience: ${i.length} entries`)}return{...l,profileUrl:t,...i!==null&&{experience:i}}}catch(s){console.error(`Error viewing profile ${t}:`,s.message);try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(s.message||""))throw s;return null}}import"dotenv/config";import*as R from"fs";import*as T from"path";import{fileURLToPath as ao}from"url";var co=ao(import.meta.url),uo=T.dirname(T.dirname(co)),G=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"market-research"):T.join(uo,"market-research"),ns=T.join(G,"scouted-jobs.json"),ss=T.join(G,"discovered-people.json"),st=T.join(G,"visit-log.json"),rs=T.join(G,"companies.json"),is=T.join(G,"job-decisions.json");function fo(){R.existsSync(G)||R.mkdirSync(G,{recursive:!0})}function mo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";R.writeFileSync(n,o);for(let s=0;s<3;s++)try{R.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw r}}function po(e){try{if(R.existsSync(e))return JSON.parse(R.readFileSync(e,"utf-8"))}catch{}return null}function rt(){ho=null,go=null,yo=null,wo=null,J=null}var ho=null;var go=null;var yo=null;var wo=null;var J=null;function $e(){return J||(J=po(st)||{visits:[]},Array.isArray(J.visits)||(J.visits=[]),J)}function it(e,t={}){if(!e)return;fo();let o=$e();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let n=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(s=>new Date(s.date).getTime()>n);try{mo(st,o)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function lt(e){let t=$e();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}se();async function at(e,t,o={}){let{maxVisits:n=50,delayBetween:s=4e3,skipRecentDays:r=7,verbose:l=!1,extractExperience:i=!1}=o,a={visited:0,skipped:0,errors:0},f=Date.now()-r*24*60*60*1e3;for(let c of t){if(a.visited>=n)break;if(!c.profileUrl)continue;let m=lt(c.profileUrl);if(m&&new Date(m).getTime()>f){a.skipped++;continue}try{let u=await nt(e,c.profileUrl,{extractExperience:i}),h=c.source||"visit";if(u){let w={...u,source:h};i&&Array.isArray(u.experience)&&u.experience.length>0&&(w._lastEnrichedAt=new Date().toISOString()),Ce(c.profileUrl,w)}it(c.profileUrl,{name:u?.name||c.name||null,source:h}),a.visited++,l?console.log(` [${a.visited}] ${u?.name||c.profileUrl} \u2014 ${u?.title?.slice(0,40)||"?"}`):a.visited%10===0&&console.log(` Visited: ${a.visited}`);let v=Math.random()*4e3;await $(s+v)}catch(u){a.errors++,l&&console.error(` Error visiting ${c.name||c.profileUrl}: ${u.message?.slice(0,60)}`);let h=(u.message||"").toLowerCase();if(h.includes("detached")||h.includes("session closed")||h.includes("target closed")||h.includes("session expired")||h.includes("bounced to")||h.includes("authwall")||h.includes("checkpoint")||h.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return a}import"dotenv/config";import*as D from"fs";import*as q from"path";import{fileURLToPath as $o}from"url";import"dotenv/config";import{createGraphClient as bo,resolveToken as So}from"@ilivemylife/graph-sdk";import{config as vo}from"dotenv";vo();var ct=So()||process.env.TOKEN;ct||(console.error(`
3
+ `):null;return{title:m,company:d,employmentType:p,dates:b,duration:E,location:W,description:be,skills:$,_raw:c}}return a.map(c=>{let d=(c.innerText||"").trim().split(`
4
+ `).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return f(d)}).filter(c=>c.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function le(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);await k(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.click(),!0;return!1});)s++,await k(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(600)}async function ce(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw r;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function kn(e,t){return ce(t,"featured","extractFeaturedFromDetails",async()=>(await le(e,t,"featured"),await e.evaluate(`(() => {
5
+ ${ae}
6
+
7
+ const main = document.querySelector('main');
8
+ if (!main) return [];
9
+ const container = findEntryContainer(main);
10
+ if (!container) return [];
11
+
12
+ const entries = Array.from(container.children)
13
+ .filter(c => c.tagName === 'DIV')
14
+ .filter(c => (c.textContent || '').trim().length > 30);
15
+
16
+ return entries.map(entry => {
17
+ const raw = (entry.innerText || '').trim();
18
+ const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 2000);
19
+
20
+ // External link from any anchor inside the card (filter LinkedIn-internal)
21
+ const anchors = Array.from(entry.querySelectorAll('a[href]'));
22
+ const externalAnchor = anchors.find(a => {
23
+ const h = a.href || '';
24
+ return h.startsWith('http') &&
25
+ !h.includes('linkedin.com/in/') &&
26
+ !h.includes('linkedin.com/posts/') &&
27
+ !h.includes('#');
28
+ });
29
+ const url = externalAnchor?.href || anchors[0]?.href || null;
30
+
31
+ const title = lines[0] || null;
32
+ const caption = lines[1] && lines[1] !== title ? lines[1] : null;
33
+
34
+ return { title, caption, url, _raw: lines };
35
+ }).filter(e => {
36
+ if (!e.title) return false;
37
+ // Reject "People You May Know" sidebar cards: signature is
38
+ // exactly [title, "View"] with no url/caption beyond "View".
39
+ if (e._raw.length === 2 && e._raw[1] === 'View') return false;
40
+ return true;
41
+ });
42
+ })()`)))}async function Cn(e,t){return ce(t,"education","extractEducationFromDetails",async()=>(await le(e,t,"education"),await e.evaluate(`(() => {
43
+ ${ae}
44
+
45
+ const main = document.querySelector('main');
46
+ if (!main) return [];
47
+ const container = findEntryContainer(main);
48
+ if (!container) return [];
49
+
50
+ const entries = Array.from(container.children)
51
+ .filter(c => c.tagName === 'DIV')
52
+ .filter(c => (c.textContent || '').trim().length > 30);
53
+
54
+ return entries.map(entry => {
55
+ const raw = (entry.innerText || '').trim();
56
+ const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 5000);
57
+
58
+ const school = lines[0] || null;
59
+ const degree = lines[1] || null;
60
+ const dates = lines.find(l =>
61
+ /(\\d{4})/.test(l) &&
62
+ /(-|\u2013|\u2014)/i.test(l) &&
63
+ l.length < 80
64
+ ) || null;
65
+ const used = new Set([0, 1, dates ? lines.indexOf(dates) : -1].filter(i => i >= 0));
66
+ const descLines = lines.filter((_, i) => !used.has(i));
67
+ const description = descLines.length > 0 ? descLines.join(' / ') : null;
68
+
69
+ return { school, degree, dates, description, _raw: lines };
70
+ }).filter(e => {
71
+ if (!e.school) return false;
72
+ // Reject "People You May Know" sidebar cards: [title, "View"].
73
+ if (e._raw.length === 2 && e._raw[1] === 'View') return false;
74
+ return true;
75
+ });
76
+ })()`)))}async function xn(e,t){return ce(t,"skills","extractSkillsFromDetails",async()=>(await le(e,t,"skills"),await e.evaluate(`(() => {
77
+ ${ae}
78
+
79
+ const main = document.querySelector('main');
80
+ if (!main) return [];
81
+ const container = findEntryContainer(main);
82
+ if (!container) return [];
83
+
84
+ const entries = Array.from(container.children)
85
+ .filter(c => c.tagName === 'DIV')
86
+ .filter(c => (c.textContent || '').trim().length > 1);
87
+
88
+ const seen = new Set();
89
+ const skills = [];
90
+ for (const entry of entries) {
91
+ const raw = (entry.innerText || '').trim();
92
+ const lines = raw.split('\\n').map(l => l.trim()).filter(Boolean);
93
+ if (lines.length === 0) continue;
94
+
95
+ const name = lines[0];
96
+ if (!name || name.length > 100 || seen.has(name.toLowerCase())) continue;
97
+ seen.add(name.toLowerCase());
98
+
99
+ let endorsements = null;
100
+ for (const l of lines.slice(1)) {
101
+ const m = l.match(/(\\d+)\\s+endorsement/i);
102
+ if (m) { endorsements = parseInt(m[1], 10); break; }
103
+ }
104
+
105
+ skills.push({ name, endorsements, _raw: lines });
106
+ }
107
+ return skills;
108
+ })()`)))}async function $n(e,t){return ce(t,"certifications","extractCertificationsFromDetails",async()=>(await le(e,t,"certifications"),await e.evaluate(`(() => {
109
+ ${ae}
110
+
111
+ const main = document.querySelector('main');
112
+ if (!main) return [];
113
+ const container = findEntryContainer(main);
114
+ if (!container) return [];
115
+
116
+ const entries = Array.from(container.children)
117
+ .filter(c => c.tagName === 'DIV')
118
+ .filter(c => (c.textContent || '').trim().length > 20);
119
+
120
+ return entries.map(entry => {
121
+ const raw = (entry.innerText || '').trim();
122
+ const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 2000);
123
+
124
+ const name = lines[0] || null;
125
+ const issuer = lines[1] || null;
126
+ const issueDate = lines.find(l => /^Issued\\b/i.test(l)) || null;
127
+ const expiryDate = lines.find(l => /Expir(es|ed)\\b/i.test(l)) || null;
128
+ const credentialId = (lines.find(l => /credential id/i.test(l)) || '')
129
+ .replace(/^.*credential id[:\\s]*/i, '').trim() || null;
130
+
131
+ return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
132
+ }).filter(e => e.name);
133
+ })()`)))}async function En(e,t){return ce(t,"recommendations","extractRecommendationsFromDetails",async()=>(await le(e,t,"recommendations"),await e.evaluate(`(() => {
134
+ ${ae}
135
+
136
+ const main = document.querySelector('main');
137
+ if (!main) return [];
138
+ const container = findEntryContainer(main);
139
+ if (!container) return [];
140
+
141
+ const entries = Array.from(container.children)
142
+ .filter(c => c.tagName === 'DIV')
143
+ .filter(c => (c.textContent || '').trim().length > 50);
144
+
145
+ return entries.map(entry => {
146
+ const raw = (entry.innerText || '').trim();
147
+ const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 5000);
148
+
149
+ const recommender = lines[0] || null;
150
+ const recommenderTitle = lines[1] || null;
151
+ const relationship = lines.find(l =>
152
+ /\\b(was |worked |reported |managed |taught |studied )\\b/i.test(l) &&
153
+ l.length < 200
154
+ ) || null;
155
+ const date = lines.find(l => /(January|February|March|April|May|June|July|August|September|October|November|December)\\s+\\d{1,2}.*\\d{4}/i.test(l)) || null;
156
+ // Recommendation text is the longest non-meta line
157
+ const text = [...lines].sort((a, b) => b.length - a.length)[0] || '';
158
+
159
+ return { recommender, recommenderTitle, relationship, date, text, _raw: lines };
160
+ }).filter(e => {
161
+ if (!e.recommender || !e.text) return false;
162
+ // Reject "People You May Know" sidebar cards: [title, "View"].
163
+ if (e._raw.length === 2 && e._raw[1] === 'View') return false;
164
+ return true;
165
+ });
166
+ })()`)))}var ae,pt=nt(()=>{ie();ae=`
167
+ function findEntryContainer(root) {
168
+ const candidates = [];
169
+ for (const div of root.querySelectorAll('div')) {
170
+ const directDivs = Array.from(div.children).filter(c => c.tagName === 'DIV');
171
+ if (directDivs.length < 2) continue;
172
+ const substantial = directDivs.filter(c => (c.textContent || '').trim().length > 30);
173
+ if (substantial.length < 2) continue;
174
+ if ((div.textContent || '').length < 200) continue;
175
+
176
+ // Reject "People You May Know" suggestion containers: every substantial
177
+ // child is exactly [title, "View"] (a tiny suggestion card with a single
178
+ // "View" CTA). Real section entries always have richer per-child content
179
+ // (multiple text lines per entry).
180
+ const allLookLikePYMK = substantial.every(c => {
181
+ const lines = (c.innerText || '').trim().split('\\n').map(l => l.trim()).filter(Boolean);
182
+ return lines.length === 2 && lines[1] === 'View';
183
+ });
184
+ if (allLookLikePYMK) continue;
185
+
186
+ // Reject LinkedIn footer/legal blocks: when a /details/<section>/ page
187
+ // renders empty, LinkedIn falls back to "Questions? Visit our Help
188
+ // Center", "Select language" (35+ languages), "Recommendation
189
+ // transparency" and similar nav cards inside <main>. These are unique
190
+ // marker strings that never appear inside real section entries.
191
+ const containerText = div.textContent || '';
192
+ const FOOTER_MARKERS = [
193
+ 'Visit our Help Center',
194
+ 'Select language',
195
+ 'Recommendation transparency',
196
+ 'Manage your account and privacy',
197
+ 'Go to your Settings',
198
+ 'Who your viewers also viewed', // "Private to you" PYMK block on empty pages
199
+ 'People also viewed',
200
+ 'People you may know',
201
+ ];
202
+ if (FOOTER_MARKERS.some(m => containerText.includes(m))) continue;
203
+
204
+ candidates.push({ el: div, count: substantial.length, totalText: (div.textContent || '').length });
205
+ }
206
+ // Sort: most children first, then RICHER children (larger totalText) \u2014 real
207
+ // section entries dominate via content density, not just child count. The
208
+ // previous "smaller totalText wins" tie-break gave PYMK sidebars priority
209
+ // over the real Education / Recommendations lists.
210
+ candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
211
+ return candidates[0]?.el;
212
+ }
213
+ `});import en from"puppeteer";import{addExtra as tn}from"puppeteer-extra";import nn from"puppeteer-extra-plugin-stealth";ie();import{getPluginConfig as Yt}from"@ilivemylife/graph-sdk";var Gt=await Yt();for(let[e,t]of Object.entries(Gt))process.env[e]===void 0&&(process.env[e]=t);var Kt=process.env.LINKEDIN_NAME,G=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Uo=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 rt from"fs";import Qt from"path";var Zt="cookies.json";function Xt(){let e=process.env.ILML_SCOPE_DIR;return e?Qt.join(e,"plugins-state","linkedin","cookies.json"):Zt}function st(){let e=Xt();if(!rt.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=rt.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}var it=tn(en);it.use(nn());async function lt(){let e=await it.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
214
+ Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=st();await n.setCookie(...o),console.log(" Browser launched, cookies loaded.")}catch(o){console.error(`
215
+ [!] ${o.message}
216
+ `),await e.close(),process.exit(1)}return{browser:e,page:n}}ie();import"dotenv/config";import*as C from"fs";import*as x from"path";import{fileURLToPath as on}from"url";var rn=on(import.meta.url),sn=x.dirname(x.dirname(rn)),q=process.env.DATA_DIR?x.resolve(process.env.DATA_DIR,"collected-profiles"):x.join(sn,"collected-profiles"),ke=x.join(q,"people.json"),sr=x.join(q,"jobs.json"),ir=x.join(q,"quota.json"),ut=x.join(q,"conversations.json"),lr=x.join(q,"sync-state.json"),ar=x.join(q,"application-questions.json"),Ce=x.join(q,"profile-history");var re=null,ln=null,an=null,oe=null,cn=null,un=null;function dt(){re=null,ln=null,an=null,oe=null,cn=null,un=null}function xe(){C.existsSync(q)||C.mkdirSync(q,{recursive:!0})}function $e(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";C.writeFileSync(o,n);for(let r=0;r<3;r++)try{C.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function Ee(e,t){if(!C.existsSync(e))return null;try{let n=JSON.parse(C.readFileSync(e,"utf-8"));try{C.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${x.resolve(e)}`);let o=e+".backup";if(C.existsSync(o))try{let r=JSON.parse(C.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{C.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{C.copyFileSync(e,e+".corrupted")}catch{}return null}}function dn(){return new Date().toISOString().split("T")[0]}var fn=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],mn=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function Ae(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function pn(){C.existsSync(Ce)||C.mkdirSync(Ce,{recursive:!0})}function ft(e){let t=Ae(e);return t?x.join(Ce,`${t}.json`):null}function hn(e){let t=ft(e);return t?Ee(t,`profile-history/${Ae(e)}.json`)||[]:[]}function gn(e,t){let n=ft(e);if(!n)return;pn();let o=hn(e);o.unshift(t);try{$e(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${Ae(e)}: ${r.message}`)}}function at(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function ct(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function yn(e,t){if(!e)return[];let n=[];for(let o of mn){let r=e[o],s=t[o];at(r)||at(s)||ct(r)!==ct(s)&&n.push(o)}return n}function wn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function K(){return re||(xe(),re=Ee(ke,"people.json")||{},re)}function bn(e){xe(),re=e;try{$e(ke,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${x.resolve(ke)}`)}}function _e(){return oe||(xe(),oe=Ee(ut,"conversations.json")||{},Sn(oe),oe)}function Sn(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let r=(n.messages||[]).find(s=>s.status==="draft");r&&n.draftStatus&&n.draftStatus!=="pending"&&(r.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{$e(ut,e)}catch{}}}function Ie(e,t={}){if(!e)return null;let n=K(),o=dn(),r=new Date().toISOString(),s=n[e];if(s){let l=yn(s,t);l.length>0&&(gn(e,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:l,snapshot:wn(s)}),s.lastSnapshotAt=r),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=r,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let i of fn)if(t[i]!=null){if(Array.isArray(t[i])&&t[i].length===0&&Array.isArray(s[i])&&s[i].length>0)continue;s[i]=t[i]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=r)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return bn(n),n[e]}async function An(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function ht(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:l=!1,extractRecommendations:i=!1,extractCertifications:a=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),await ot(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await An(e,t));let c=0;for(let $=0;$<2;$++){let te=await e.evaluate(()=>document.body.scrollHeight);for(let Y=1;Y<=6;Y++)await e.evaluate(I=>window.scrollTo(0,I),te*Y/6),await k(900);let P=await e.evaluate(()=>document.body.scrollHeight);if(P===c)break;c=P}await k(800);let m=await e.evaluate(()=>{let $=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),te=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),P=h=>{let g=(h||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(g)},Y={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},I=document.querySelector("main");if(!I)return Y;let be=[...Array.from(I.querySelectorAll("h1")),...Array.from(I.querySelectorAll("h2"))],y=Array.from(I.querySelectorAll("h2")),A=be.find(h=>{let g=h.textContent&&h.textContent.trim(),w=(g||"").replace(/\s*\(\d+\)$/,"").trim();return g&&g.length>1&&g.length<100&&!$.has(w)&&!te.has(w)}),ne=A?A.textContent.trim():null,T=A?A.parentElement:null;for(;T&&T!==I&&!Array.from(T.children).filter(g=>g.tagName==="P").some(g=>{let w=g.textContent&&g.textContent.trim();return w&&w.length>5&&!P(w)});)T=T.parentElement;let de=null,Ve=null,He=null,Se=null;if(T&&T!==I){let h=Array.from(T.children).filter(w=>w.tagName==="P").filter(w=>{let B=w.textContent&&w.textContent.trim();return B&&B.length>5&&!P(B)});if(h[0]&&(de=h[0].textContent.trim()),h[1]){let w=h[1].textContent.trim().split(/\s*[·•]\s*/);Ve=w[0]||null,w.length>1&&(He=w.slice(1).join(" \xB7 "))}let g=Array.from(T.children).filter(w=>w.tagName==="DIV");for(let w=g.length-1;w>=0;w--){let B=g[w].textContent&&g[w].textContent.trim();if(B&&!(ne&&B.startsWith(ne))&&(Se=B.split(/[·•]/)[0].trim(),Se))break}}let Je=null;if(T){let h=T.querySelectorAll("p, span, div");for(let g of h){let w=(g.textContent||"").trim().replace(/^[·•]\s*/,"");if(w==="1st"||w==="2nd"||w==="3rd"){Je=w;break}}}let Pt=!!I.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),We=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),qt=We&&We.src||null,fe=I.textContent||"",Ye=null,Ge=fe.match(/(\d+\+?)\s+connections\b/i);Ge&&(Ye=Ge[1]+" connections");let me=null,Ke=fe.match(/(\d+)\s+mutual connection/i),ze=fe.match(/and\s+(\d+)\s+other mutual/i),Ut=fe.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Ke?me=parseInt(Ke[1],10):ze?me=2+parseInt(ze[1],10):Ut&&(me=2);let Qe=null,Ze=null,Xe=y.find(h=>h.textContent&&h.textContent.trim()==="About");if(Xe){let h=Xe.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").trim();g=g.replace(/^About\s*/,"").trim();let w=g.match(/Top skills\s*(.+?)$/i);if(w){let ve=w[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Jt=>Jt.trim()).filter(Boolean);ve.length>0&&ve.length<10&&(Ze=ve)}g=g.split(/\n?…\s*more/i)[0].trim(),g=g.split(/\n?\.\.\.\s*more/i)[0].trim(),g=g.split(/\bTop skills\b/i)[0].trim(),g=g.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Qe=g||null}}let et=null,tt=y.find(h=>h.textContent&&h.textContent.trim()==="Activity");if(tt){let h=tt.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);g&&(et=parseInt(g[1].replace(/,/g,""),10))}}let Bt=[...new Set(y.map(h=>(h.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(h=>h&&h.length>1&&h.length<60&&h!==ne).filter(h=>$.has(h)))],se=document.body.textContent||"",Vt=/#OpenToWork\b/i.test(se)||/\bOpen to work\b/.test(se),Ht=/#Hiring\b/i.test(se)||/\bI'?m hiring\b/i.test(se)||/\bWe are hiring\b/i.test(se);return{name:ne,title:de,location:Se,currentCompany:Ve,currentSchool:He,connectionDegree:Je,hasVerifiedBadge:Pt,photoUrl:qt,connectionsLevel:Ye,mutualConnectionsCount:me,followers:et,openToWork:Vt,hiring:Ht,about:Qe,topSkills:Ze,availableSections:Bt}});console.log(`Viewed: ${m.name} - ${m.title}`);let d=null,p=null,v=null,b=null,E=null,W=null;if(o||r||s||l||i||a){let $=await Promise.resolve().then(()=>(pt(),mt));o&&(d=await $.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),r&&(p=await $.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),s&&(v=await $.extractEducationFromDetails(e,t),console.log(` + Education: ${v.length} entries`)),l&&(b=await $.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),i&&(E=await $.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${E.length} entries`)),a&&(W=await $.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${W.length} entries`))}return{...m,profileUrl:t,...d!==null&&{experience:d},...p!==null&&{featured:p},...v!==null&&{education:v},...b!==null&&{skillsFull:b},...E!==null&&{recommendations:E},...W!==null&&{certifications:W}}}catch(f){console.error(`Error viewing profile ${t}:`,f.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(f.message||""))throw f;return null}}import"dotenv/config";import*as O from"fs";import*as R from"path";import{fileURLToPath as _n}from"url";var In=_n(import.meta.url),Tn=R.dirname(R.dirname(In)),Q=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"market-research"):R.join(Tn,"market-research"),kr=R.join(Q,"scouted-jobs.json"),Cr=R.join(Q,"discovered-people.json"),gt=R.join(Q,"visit-log.json"),xr=R.join(Q,"companies.json"),$r=R.join(Q,"job-decisions.json");function Dn(){O.existsSync(Q)||O.mkdirSync(Q,{recursive:!0})}function Rn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let r=0;r<3;r++)try{O.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function On(e){try{if(O.existsSync(e))return JSON.parse(O.readFileSync(e,"utf-8"))}catch{}return null}function yt(){jn=null,Nn=null,Fn=null,Ln=null,z=null}var jn=null;var Nn=null;var Fn=null;var Ln=null;var z=null;function Te(){return z||(z=On(gt)||{visits:[]},Array.isArray(z.visits)||(z.visits=[]),z)}function wt(e,t={}){if(!e)return;Dn();let n=Te();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{Rn(gt,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function bt(e){let t=Te();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}ie();async function St(e,t,n={}){let{maxVisits:o=50,delayBetween:r=4e3,skipRecentDays:s=7,verbose:l=!1,extractExperience:i=!1}=n,a={visited:0,skipped:0,errors:0},f=Date.now()-s*24*60*60*1e3;for(let c of t){if(a.visited>=o)break;if(!c.profileUrl)continue;let m=bt(c.profileUrl);if(m&&new Date(m).getTime()>f){a.skipped++;continue}try{let d=await ht(e,c.profileUrl,{extractExperience:i}),p=c.source||"visit";if(d){let b={...d,source:p};i&&Array.isArray(d.experience)&&d.experience.length>0&&(b._lastEnrichedAt=new Date().toISOString()),Ie(c.profileUrl,b)}wt(c.profileUrl,{name:d?.name||c.name||null,source:p}),a.visited++,l?console.log(` [${a.visited}] ${d?.name||c.profileUrl} \u2014 ${d?.title?.slice(0,40)||"?"}`):a.visited%10===0&&console.log(` Visited: ${a.visited}`);let v=Math.random()*4e3;await k(r+v)}catch(d){a.errors++,l&&console.error(` Error visiting ${c.name||c.profileUrl}: ${d.message?.slice(0,60)}`);let p=(d.message||"").toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("session expired")||p.includes("bounced to")||p.includes("authwall")||p.includes("checkpoint")||p.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return a}import"dotenv/config";import*as j from"fs";import*as V from"path";import{fileURLToPath as Vn}from"url";import"dotenv/config";import{createGraphClient as Mn,resolveToken as Pn}from"@ilivemylife/graph-sdk";import{config as qn}from"dotenv";qn();var vt=Pn()||process.env.TOKEN;vt||(console.error(`
8
217
  [FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
9
218
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
10
219
  `),console.error(` Or add ILML_TOKEN=... to .env
11
- `),process.exit(1));var ut=bo({token:ct});function ko(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),n=t%60;return n?`${o}m ${n}s`:`${o}m`}function Co({scriptName:e,mode:t,status:o,error:n,duration:s}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),i=s?` ${ko(s)}`:"",a=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",f=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${f} \u2014 ${a} \u2014 ${l}${i}`}async function dt({scriptName:e,mode:t,status:o,summaryLines:n,error:s,duration:r}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(n)||n.length===0)return;let a=`**${Co({scriptName:e,mode:t,status:o,error:s,duration:r})}**
220
+ `),process.exit(1));var kt=Mn({token:vt});function Un(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Bn({scriptName:e,mode:t,status:n,error:o,duration:r}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),i=r?` ${Un(r)}`:"",a=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",f=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${f} \u2014 ${a} \u2014 ${l}${i}`}async function Ct({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(o)||o.length===0)return;let a=`**${Bn({scriptName:e,mode:t,status:n,error:r,duration:s})}**
12
221
 
13
- ${n.join(`
14
- `)}`;try{await ut.addMessage(l,a)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var xo=$o(import.meta.url),Ao=q.dirname(q.dirname(xo)),xe=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"collected-profiles"):q.join(Ao,"collected-profiles"),Ae=q.join(xe,"run-log.json");function Eo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";D.writeFileSync(n,o);for(let s=0;s<3;s++)try{D.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw r}}function ft(){try{if(!D.existsSync(Ae))return{runs:[]};let e=JSON.parse(D.readFileSync(Ae,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function mt(e){D.existsSync(xe)||D.mkdirSync(xe,{recursive:!0});try{Eo(Ae,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function pt(e,t="default"){let o=ft();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let n=new Date,s={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>r),mt(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function Ee(e,t,o=null,n=null){if(!e)return;let s=null;try{let l=ft(),i=l.runs[e.runIndex];if(i&&i.status==="running"&&i.script===e.script)i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=o,i.error=n,s=i.duration;else{let a=l.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=n,s=a.duration)}mt(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";dt({scriptName:e.script,mode:e.mode,status:l,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(i=>console.error(`[runLog] postRunReport failed: ${i.message}`))}}import"dotenv/config";import*as d from"fs";import*as je from"os";import*as S from"path";import{fileURLToPath as Wo}from"url";var Te={};de(Te,{NAME:()=>Io,VERSION:()=>_o,up:()=>Do});import*as O from"fs";import*as fe from"path";var _o=1,Io="normalize-jobs-and-questions",To=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ro=50;function _e(e){return O.existsSync(e)?JSON.parse(O.readFileSync(e,"utf-8")):null}function Ie(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{O.writeFileSync(n,o)}catch(s){try{O.unlinkSync(n)}catch{}throw s}try{O.renameSync(n,e)}catch(s){try{O.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Do(e,t){let o=fe.join(e,"jobs.json"),n=fe.join(t,"scouted-jobs.json"),s=fe.join(e,"application-questions.json"),r=_e(o)||{},l=_e(n)||{},i=0,a=[];for(let c of Object.keys(r)){if(!l[c])continue;let m=l[c],u=r[c];for(let h of To)m[h]!=null&&u[h]==null&&(u[h]=m[h]);a.push(c),i++}i>0?(Ie(o,r),console.log(` Phase 1: Merged ${i} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=_e(s);if(f&&Array.isArray(f.applications)){let c={},m=0;for(let u of f.applications){let h=u.jobId||"unknown";c[h]||(c[h]={applications:[]});let v=(u.questions||[]).map(w=>{let x={type:w.type||"input",question:w.question||"",answer:w.answer||""};return w.options&&(w.options.length<=Ro?x.options=w.options:(x.optionsOmitted=!0,m++)),w.page&&(x.page=w.page),w.wasPreFilled&&(x.wasPreFilled=!0),w.wasRetry&&(x.wasRetry=!0),x});c[h].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||v.length,questions:v})}Ie(s,c),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} 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(a.length>0){for(let c of a)delete l[c];Ie(n,l),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Re={};de(Re,{NAME:()=>jo,VERSION:()=>Oo,up:()=>Mo});import*as j from"fs";import*as ht from"path";var Oo=2,jo="reset-unread-flags";function No(e){return j.existsSync(e)?JSON.parse(j.readFileSync(e,"utf-8")):null}function Lo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{j.writeFileSync(n,o)}catch(s){try{j.unlinkSync(n)}catch{}throw s}try{j.renameSync(n,e)}catch(s){try{j.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Mo(e){let t=ht.join(e,"conversations.json"),o=No(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Lo(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var De={};de(De,{NAME:()=>Po,VERSION:()=>Fo,up:()=>Vo});import*as N from"fs";import*as gt from"path";var Fo=3,Po="recompute-last-message-by",qo=new Set(["draft","confirmed","rejected","needs_review"]);function Uo(e){return N.existsSync(e)?JSON.parse(N.readFileSync(e,"utf-8")):null}function Bo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{N.writeFileSync(n,o)}catch(s){try{N.unlinkSync(n)}catch{}throw s}try{N.renameSync(n,e)}catch(s){try{N.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function Ho(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!qo.has(r.status));if(o.length===0)return"them";let n=o.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,l)=>l.t-r.t).map(r=>r.m),s=n.length>0?n:[...o].reverse();for(let r of s){let l=r.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Vo(e){let t=gt.join(e,"conversations.json"),o=Uo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.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 s=0,r=0,l=0;for(let i of Object.keys(o)){let a=o[i];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,r++);let f=Array.isArray(a.messages)?a.messages:[],c=Ho(f,n),m=c==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==c&&l++,a.lastMessageBy=c,a.conversationStatus=m,s++}if(s===0){console.log(" No conversations to recompute.");return}Bo(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Jo=Wo(import.meta.url),Go=S.dirname(Jo),Yo=S.dirname(S.dirname(Go));function zo(e){return e&&(e==="~"?je.homedir():e.startsWith("~/")||e.startsWith("~\\")?S.join(je.homedir(),e.slice(2)):e)}var L=process.env.DATA_DIR?S.resolve(zo(process.env.DATA_DIR)):Yo,z=S.join(L,"collected-profiles"),K=S.join(L,"market-research"),I=S.join(L,".schema-version"),yt=[S.join(z,".schema-version"),S.join(K,".schema-version")],U=3,F=[{version:1,module:Te},{version:2,module:Re},{version:3,module:De}];(function(){F.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of F){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let s=n.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=F.length?F[F.length-1].version:0;if(o!==U)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${U}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<F.length;n++){let s=n+1;if(F[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${F[n].version}`)}})();function vt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
222
+ ${o.join(`
223
+ `)}`;try{await kt.addMessage(l,a)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Hn=Vn(import.meta.url),Jn=V.dirname(V.dirname(Hn)),De=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(Jn,"collected-profiles"),Re=V.join(De,"run-log.json");function Wn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";j.writeFileSync(o,n);for(let r=0;r<3;r++)try{j.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw s}}function xt(){try{if(!j.existsSync(Re))return{runs:[]};let e=JSON.parse(j.readFileSync(Re,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function $t(e){j.existsSync(De)||j.mkdirSync(De,{recursive:!0});try{Wn(Re,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Et(e,t="default"){let n=xt();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>s),$t(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Oe(e,t,n=null,o=null){if(!e)return;let r=null;try{let l=xt(),i=l.runs[e.runIndex];if(i&&i.status==="running"&&i.script===e.script)i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=n,i.error=o,r=i.duration;else{let a=l.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,r=a.duration)}$t(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Ct({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(i=>console.error(`[runLog] postRunReport failed: ${i.message}`))}}import"dotenv/config";import*as u from"fs";import*as qe from"os";import*as S from"path";import{fileURLToPath as uo}from"url";var Fe={};pe(Fe,{NAME:()=>Gn,VERSION:()=>Yn,up:()=>Qn});import*as N from"fs";import*as he from"path";var Yn=1,Gn="normalize-jobs-and-questions",Kn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],zn=50;function je(e){return N.existsSync(e)?JSON.parse(N.readFileSync(e,"utf-8")):null}function Ne(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{N.writeFileSync(o,n)}catch(r){try{N.unlinkSync(o)}catch{}throw r}try{N.renameSync(o,e)}catch(r){try{N.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Qn(e,t){let n=he.join(e,"jobs.json"),o=he.join(t,"scouted-jobs.json"),r=he.join(e,"application-questions.json"),s=je(n)||{},l=je(o)||{},i=0,a=[];for(let c of Object.keys(s)){if(!l[c])continue;let m=l[c],d=s[c];for(let p of Kn)m[p]!=null&&d[p]==null&&(d[p]=m[p]);a.push(c),i++}i>0?(Ne(n,s),console.log(` Phase 1: Merged ${i} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=je(r);if(f&&Array.isArray(f.applications)){let c={},m=0;for(let d of f.applications){let p=d.jobId||"unknown";c[p]||(c[p]={applications:[]});let v=(d.questions||[]).map(b=>{let E={type:b.type||"input",question:b.question||"",answer:b.answer||""};return b.options&&(b.options.length<=zn?E.options=b.options:(E.optionsOmitted=!0,m++)),b.page&&(E.page=b.page),b.wasPreFilled&&(E.wasPreFilled=!0),b.wasRetry&&(E.wasRetry=!0),E});c[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||v.length,questions:v})}Ne(r,c),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} 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(a.length>0){for(let c of a)delete l[c];Ne(o,l),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Le={};pe(Le,{NAME:()=>Xn,VERSION:()=>Zn,up:()=>no});import*as F from"fs";import*as At from"path";var Zn=2,Xn="reset-unread-flags";function eo(e){return F.existsSync(e)?JSON.parse(F.readFileSync(e,"utf-8")):null}function to(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{F.writeFileSync(o,n)}catch(r){try{F.unlinkSync(o)}catch{}throw r}try{F.renameSync(o,e)}catch(r){try{F.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function no(e){let t=At.join(e,"conversations.json"),n=eo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}to(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Me={};pe(Me,{NAME:()=>ro,VERSION:()=>oo,up:()=>co});import*as L from"fs";import*as _t from"path";var oo=3,ro="recompute-last-message-by",so=new Set(["draft","confirmed","rejected","needs_review"]);function io(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function lo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{L.writeFileSync(o,n)}catch(r){try{L.unlinkSync(o)}catch{}throw r}try{L.renameSync(o,e)}catch(r){try{L.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function ao(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!so.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,l)=>l.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let l=s.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function co(e){let t=_t.join(e,"conversations.json"),n=io(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.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 r=0,s=0,l=0;for(let i of Object.keys(n)){let a=n[i];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,s++);let f=Array.isArray(a.messages)?a.messages:[],c=ao(f,o),m=c==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==c&&l++,a.lastMessageBy=c,a.conversationStatus=m,r++}if(r===0){console.log(" No conversations to recompute.");return}lo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var fo=uo(import.meta.url),mo=S.dirname(fo),po=S.dirname(S.dirname(mo));function ho(e){return e&&(e==="~"?qe.homedir():e.startsWith("~/")||e.startsWith("~\\")?S.join(qe.homedir(),e.slice(2)):e)}var M=process.env.DATA_DIR?S.resolve(ho(process.env.DATA_DIR)):po,X=S.join(M,"collected-profiles"),ee=S.join(M,"market-research"),D=S.join(M,".schema-version"),It=[S.join(X,".schema-version"),S.join(ee,".schema-version")],H=3,U=[{version:1,module:Fe},{version:2,module:Le},{version:3,module:Me}];(function(){U.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of U){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=U.length?U[U.length-1].version:0;if(n!==H)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${H}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<U.length;o++){let r=o+1;if(U[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${U[o].version}`)}})();function Ot(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
15
224
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
16
- `),process.exit(1));try{d.mkdirSync(L,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
17
- [FATAL] Cannot create DATA_DIR (${L}): ${t.message}`),console.error(` Fix the path or permissions and try again.
18
- `),process.exit(1))}let e;try{e=d.statSync(L)}catch(t){console.error(`
19
- [FATAL] DATA_DIR (${L}) is not accessible: ${t.message}
225
+ `),process.exit(1));try{u.mkdirSync(M,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
226
+ [FATAL] Cannot create DATA_DIR (${M}): ${t.message}`),console.error(` Fix the path or permissions and try again.
227
+ `),process.exit(1))}let e;try{e=u.statSync(M)}catch(t){console.error(`
228
+ [FATAL] DATA_DIR (${M}) is not accessible: ${t.message}
20
229
  `),process.exit(1)}e.isDirectory()||(console.error(`
21
- [FATAL] DATA_DIR (${L}) 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.
22
- `),process.exit(1));for(let t of[z,K]){let o;try{o=d.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
230
+ [FATAL] DATA_DIR (${M}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
231
+ `),process.exit(1));for(let t of[X,ee]){let n;try{n=u.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
23
232
  [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.
24
- `),process.exit(1))}}var Y=S.join(L,".migration-lock");function Ko(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return d.writeFileSync(Y,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(d.readFileSync(Y,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let n=!1;try{process.kill(t.pid,0),n=!0}catch(l){l.code==="EPERM"&&(n=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(r=Date.now()-l)}n&&r<s&&(console.error(`
25
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Y}
233
+ `),process.exit(1))}}var Z=S.join(M,".migration-lock");function go(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return u.writeFileSync(Z,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(u.readFileSync(Z,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(l){l.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,s=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(s=Date.now()-l)}o&&s<r&&(console.error(`
234
+ [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}
26
235
  `),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.
27
- `),process.exit(1)),n&&r>=s&&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=Y+".tmp";try{return d.writeFileSync(o,e),d.renameSync(o,Y),!0}catch(n){try{d.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function Ne(){try{if(JSON.parse(d.readFileSync(Y,"utf-8")).pid!==process.pid)return;d.unlinkSync(Y)}catch{}}var wt=!1;function Qo(){if(wt)return;wt=!0;let e=()=>{try{Ne()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Zo(){if(d.existsSync(I))return;let e=[],t=[];for(let r of yt)if(d.existsSync(r))try{e.push({file:r,schema:me(r)})}catch(l){t.push({file:r,err:l.message})}if(t.length>0){console.error(`
28
- [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of t)console.error(` ${r.file}: ${r.err}`);console.error(`
236
+ `),process.exit(1)),o&&s>=r&&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 n=Z+".tmp";try{return u.writeFileSync(n,e),u.renameSync(n,Z),!0}catch(o){try{u.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Ue(){try{if(JSON.parse(u.readFileSync(Z,"utf-8")).pid!==process.pid)return;u.unlinkSync(Z)}catch{}}var Tt=!1;function yo(){if(Tt)return;Tt=!0;let e=()=>{try{Ue()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function wo(){if(u.existsSync(D))return;let e=[],t=[];for(let s of It)if(u.existsSync(s))try{e.push({file:s,schema:ge(s)})}catch(l){t.push({file:s,err:l.message})}if(t.length>0){console.error(`
237
+ [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
29
238
  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.
30
- `),process.exit(1)}if(e.length===0)return;let o=e.map(r=>r.schema.version);if(new Set(o).size>1){console.error(`
31
- [FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.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.
32
- `),process.exit(1)}let n=e[0].schema,s=I+".tmp";try{d.writeFileSync(s,JSON.stringify(n,null,2)),d.renameSync(s,I)}catch(r){try{d.unlinkSync(s)}catch{}throw r}for(let r of yt)if(d.existsSync(r))try{d.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${I}`)}function Xo(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 me(e){let t=d.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function bt(){if(Zo(),!d.existsSync(I))return{version:0,migrations:[]};let e;try{e=me(I)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
33
- [FATAL] ${I} 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.
34
- `),process.exit(1)}let t=Xo(e);return t===null&&(console.error(`
35
- [FATAL] ${I} 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.
36
- `),process.exit(1)),t}function kt(e){try{d.chmodSync(e,384)}catch{}}function en(e){if(vt(),d.existsSync(I))try{if(d.lstatSync(I).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${I}. 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=I+".tmp";try{d.writeFileSync(t,JSON.stringify(e,null,2)),kt(t),d.renameSync(t,I)}catch(o){try{d.unlinkSync(t)}catch{}throw o}}function St(e,t){if(!d.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=d.readdirSync(e).filter(i=>{let a=i.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return d.statSync(S.join(e,i)).isFile()}catch{return!1}}),s=0,r=0,l=[];for(let i of n){let a=S.join(e,i),f=S.join(e,i+o);if(d.existsSync(f)){r++;continue}try{$t(a,f),s++}catch(c){l.push({file:i,err:c.message})}}if(l.length>0){let i=new Error(`Failed to back up ${l.length} file(s) in ${S.basename(e)}/: `+l.map(a=>`${a.file} (${a.err})`).join(", "));throw i.code="BACKUP_INCOMPLETE",i}if(s>0||r>0){let i=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${S.basename(e)}/ (${o})${i}`)}}var Oe=!1;async function Ct(){if(Oe)return;vt(),rn();let t=bt().version;if(t===U){Oe=!0;return}Qo(),Ko(),process.on("exit",Ne),t>U&&(console.error(`
37
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${U}.`),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.
38
- `),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${U}.
239
+ `),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
240
+ [FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
241
+ `),process.exit(1)}let o=e[0].schema,r=D+".tmp";try{u.writeFileSync(r,JSON.stringify(o,null,2)),u.renameSync(r,D)}catch(s){try{u.unlinkSync(r)}catch{}throw s}for(let s of It)if(u.existsSync(s))try{u.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${D}`)}function bo(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 ge(e){let t=u.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Dt(){if(wo(),!u.existsSync(D))return{version:0,migrations:[]};let e;try{e=ge(D)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
242
+ [FATAL] ${D} is not valid JSON: ${n.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.
243
+ `),process.exit(1)}let t=bo(e);return t===null&&(console.error(`
244
+ [FATAL] ${D} 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.
245
+ `),process.exit(1)),t}function jt(e){try{u.chmodSync(e,384)}catch{}}function So(e){if(Ot(),u.existsSync(D))try{if(u.lstatSync(D).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${D}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=D+".tmp";try{u.writeFileSync(t,JSON.stringify(e,null,2)),jt(t),u.renameSync(t,D)}catch(n){try{u.unlinkSync(t)}catch{}throw n}}function Rt(e,t){if(!u.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=u.readdirSync(e).filter(i=>{let a=i.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return u.statSync(S.join(e,i)).isFile()}catch{return!1}}),r=0,s=0,l=[];for(let i of o){let a=S.join(e,i),f=S.join(e,i+n);if(u.existsSync(f)){s++;continue}try{Ft(a,f),r++}catch(c){l.push({file:i,err:c.message})}}if(l.length>0){let i=new Error(`Failed to back up ${l.length} file(s) in ${S.basename(e)}/: `+l.map(a=>`${a.file} (${a.err})`).join(", "));throw i.code="BACKUP_INCOMPLETE",i}if(r>0||s>0){let i=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${S.basename(e)}/ (${n})${i}`)}}var Pe=!1;async function Nt(){if(Pe)return;Ot(),$o();let t=Dt().version;if(t===H){Pe=!0;return}yo(),go(),process.on("exit",Ue),t>H&&(console.error(`
246
+ [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.
247
+ `),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}.
39
248
  `),process.exit(1)),console.log(`
40
- \u{1F4E6} Schema migration: v${t} \u2192 v${U}`);let o=ln();if(!o.ok){console.error(`
41
- [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of o.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
249
+ \u{1F4E6} Schema migration: v${t} \u2192 v${H}`);let n=Eo();if(!n.ok){console.error(`
250
+ [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
42
251
  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'.
43
- `),process.exit(1)}let n=F.filter(s=>s.version>t);for(let s of n){console.log(`
44
- Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,l=`.pre-${r}.backup`;try{St(z,s.version),St(K,s.version)}catch(a){console.error(`
45
- [FATAL] Pre-migration backup failed for ${r}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
46
- `),process.exit(1)}let i=s.module;try{await i.up(z,K)}catch(a){console.error(`
47
- [FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let f=an(l);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.
252
+ `),process.exit(1)}let o=U.filter(r=>r.version>t);for(let r of o){console.log(`
253
+ Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${s}.backup`;try{Rt(X,r.version),Rt(ee,r.version)}catch(a){console.error(`
254
+ [FATAL] Pre-migration backup failed for ${s}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
255
+ `),process.exit(1)}let i=r.module;try{await i.up(X,ee)}catch(a){console.error(`
256
+ [FATAL] Migration ${s} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let f=Ao(l);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.
48
257
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${f.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
49
258
  `))}catch(f){console.error(` [!] Auto-rollback CRASHED while restoring: ${f.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
50
- `)}process.exit(1)}try{let a=new Date().toISOString(),f={version:s.version,name:i.NAME||r,appliedAt:a},c=bt();c.version=s.version,c.migratedAt=a,c.migrations=c.migrations||[],c.migrations.push(f),en(c)}catch(a){console.error(`
51
- [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
52
- `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{Xe()}catch{}try{rt()}catch{}Oe=!0,Ne(),console.log(`
53
- \u2713 Schema is now at v${U}
54
- `)}var tn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function on(e){let t=e.toLowerCase();return tn.some(o=>o.test(t))}var nn=6e4;function sn(){let e=Date.now(),t=[];for(let o of[L,z,K]){if(!d.existsSync(o))continue;let n;try{n=d.readdirSync(o)}catch{continue}for(let s of n){if(!on(s))continue;let r=S.join(o,s);try{let l=d.statSync(r);if(!l.isFile()||e-l.mtimeMs<nn)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function rn({verbose:e=!1}={}){let t=sn();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let n of t)try{d.unlinkSync(n.fullPath),o++,e&&console.log(` Removed orphan: ${S.basename(n.dir)}/${n.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${s.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function ln(){let e=[];for(let t of[z,K]){if(!d.existsSync(t))continue;let o=d.readdirSync(t).filter(n=>{let s=n.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let n of o){let s=S.join(t,n);try{me(s)}catch(r){e.push({dir:S.basename(t),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function an(e){let t=[],o=[];for(let r of[z,K]){if(!d.existsSync(r))continue;let l=d.readdirSync(r).filter(i=>i.endsWith(e));for(let i of l){let a=S.join(r,i),f=i.slice(0,-e.length),c=S.join(r,f);try{f.toLowerCase().endsWith(".json")?me(a):d.accessSync(a,d.constants.R_OK),t.push({backupPath:a,originalPath:c,fileName:i,dir:r})}catch(m){o.push(`${S.basename(r)}/${i}: ${m.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let n=0,s=[];for(let{backupPath:r,originalPath:l,fileName:i,dir:a}of t)try{$t(r,l),n++}catch(f){s.push(`${S.basename(a)}/${i}: ${f.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function $t(e,t){let o=t+".tmp";try{d.copyFileSync(e,o),kt(o)}catch(n){try{d.unlinkSync(o)}catch{}throw n}try{d.renameSync(o,t)}catch(n){try{d.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${t} (${n.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 s.code=n.code,s}throw n}}await Ct();var B=process.argv.slice(2),pe=parseInt(B.find(e=>e.startsWith("--max="))?.split("=")[1]||"10"),re=B.includes("--connections"),xt=B.find(e=>e.startsWith("--match-title="))?.split("=").slice(1).join("=")||null,_=xt?fn(xt):null,cn=B.includes("--list"),un=B.includes("--verbose"),Le=B.includes("--with-experience"),dn=B.includes("--help")||B.includes("-h");dn&&(console.log(`
259
+ `)}process.exit(1)}try{let a=new Date().toISOString(),f={version:r.version,name:i.NAME||s,appliedAt:a},c=Dt();c.version=r.version,c.migratedAt=a,c.migrations=c.migrations||[],c.migrations.push(f),So(c)}catch(a){console.error(`
260
+ [FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
261
+ `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{dt()}catch{}try{yt()}catch{}Pe=!0,Ue(),console.log(`
262
+ \u2713 Schema is now at v${H}
263
+ `)}var vo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ko(e){let t=e.toLowerCase();return vo.some(n=>n.test(t))}var Co=6e4;function xo(){let e=Date.now(),t=[];for(let n of[M,X,ee]){if(!u.existsSync(n))continue;let o;try{o=u.readdirSync(n)}catch{continue}for(let r of o){if(!ko(r))continue;let s=S.join(n,r);try{let l=u.statSync(s);if(!l.isFile()||e-l.mtimeMs<Co)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function $o({verbose:e=!1}={}){let t=xo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{u.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${S.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Eo(){let e=[];for(let t of[X,ee]){if(!u.existsSync(t))continue;let n=u.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=S.join(t,o);try{ge(r)}catch(s){e.push({dir:S.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ao(e){let t=[],n=[];for(let s of[X,ee]){if(!u.existsSync(s))continue;let l=u.readdirSync(s).filter(i=>i.endsWith(e));for(let i of l){let a=S.join(s,i),f=i.slice(0,-e.length),c=S.join(s,f);try{f.toLowerCase().endsWith(".json")?ge(a):u.accessSync(a,u.constants.R_OK),t.push({backupPath:a,originalPath:c,fileName:i,dir:s})}catch(m){n.push(`${S.basename(s)}/${i}: ${m.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:l,fileName:i,dir:a}of t)try{Ft(s,l),o++}catch(f){r.push(`${S.basename(a)}/${i}: ${f.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Ft(e,t){let n=t+".tmp";try{u.copyFileSync(e,n),jt(n)}catch(o){try{u.unlinkSync(n)}catch{}throw o}try{u.renameSync(n,t)}catch(o){try{u.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.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 r.code=o.code,r}throw o}}await Nt();var J=process.argv.slice(2),ye=parseInt(J.find(e=>e.startsWith("--max="))?.split("=")[1]||"10"),ue=J.includes("--connections"),Lt=J.find(e=>e.startsWith("--match-title="))?.split("=").slice(1).join("=")||null,_=Lt?Do(Lt):null,_o=J.includes("--list"),Io=J.includes("--verbose"),Be=J.includes("--with-experience"),To=J.includes("--help")||J.includes("-h");To&&(console.log(`
55
264
  enrich-profiles \u2014 batch-visit contacts in people.json missing About text
56
265
 
57
266
  USAGE
@@ -94,12 +303,12 @@ WHEN TO USE
94
303
  - You want to backfill in a controlled batch (\u2264 10 per day) before reaching
95
304
  out, so AI drafting has full context.
96
305
  - Use --connections to keep ban risk low.
97
- `),process.exit(0));function fn(e){try{return new RegExp(e,"i")}catch(t){console.error(`Invalid regex for --match-title: ${t.message}`),process.exit(1)}}var mn=new Set(["pending","sent_with_note","sent_without_note"]);function pn(e){return!e.about||!e.about.trim()}function hn(e){return!mn.has(e.connectionStatus)}function At(){let e=W(),t=ke(),o=new Set,n=new Set;for(let i of Object.values(t))i.profileUrl&&o.add(i.profileUrl),(i.unread===!0||i.actionNeeded==="reply"||i.situation==="needs_our_reply"||i.conversationStatus==="unanswered_by_us")&&i.profileUrl&&n.add(i.profileUrl);let r=Object.entries(e).filter(([i,a])=>i&&i.startsWith("http")).filter(([,i])=>pn(i)).filter(([,i])=>hn(i)).filter(([i])=>!n.has(i)).map(([i,a])=>({profileUrl:i,name:a.name,person:a,hasConversation:o.has(i)}));re&&(r=r.filter(i=>i.person.connectionStatus==="connected")),_&&(r=r.filter(i=>_.test(i.person.title||"")));function l(i){let a=i.person.connectionStatus==="connected";return a&&i.hasConversation?1:a?2:_&&_.test(i.person.title||"")?3:i.hasConversation?4:5}return r.sort((i,a)=>{let f=l(i),c=l(a);if(f!==c)return f-c;let m=i.person.lastFullVisitAt||"",u=a.person.lastFullVisitAt||"";return m.localeCompare(u)}),r.map(i=>({profileUrl:i.profileUrl,name:i.name,source:"enrich-profile"}))}function gn(){let e=W(),t=Object.keys(e).length,o=Object.values(e).filter(m=>m.about&&m.about.trim()).length,n=t-o,s=At(),r={connWithConv:0,conn:0,titleMatch:0,withConv:0,other:0},l=e,i=ke(),a=new Set(Object.values(i).map(m=>m.profileUrl).filter(Boolean)),f=Object.values(i).filter(m=>m.profileUrl&&(m.unread===!0||m.actionNeeded==="reply"||m.situation==="needs_our_reply"||m.conversationStatus==="unanswered_by_us")).length,c=0;for(let m of s){let u=l[m.profileUrl],h=u.connectionStatus==="connected",v=_&&_.test(u.title||""),w=a.has(m.profileUrl);u.lastFullVisitAt||c++,h&&w?r.connWithConv++:h?r.conn++:v?r.titleMatch++:w?r.withConv++:r.other++}console.log(`
98
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" PROFILE ENRICHMENT QUEUE"),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(` Total people: ${t}`),console.log(` With "about": ${o} (${(o/t*100).toFixed(1)}%)`),console.log(` Missing "about": ${n}`),console.log(` Skipped (needs reply): ${f}`),console.log(` Visitable (queue): ${s.length}`),console.log(` Never fully visited: ${c} (gone first)`),_&&console.log(` Title-match filter: /${_.source}/i`),re&&console.log(" Connections-only: yes"),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Tier 1 (conn+conv): ${r.connWithConv}`),console.log(` Tier 2 (connection): ${r.conn}`),console.log(` Tier 3 (title match): ${r.titleMatch}${_?"":" (no --match-title set)"}`),console.log(` Tier 4 (conversation): ${r.withConv}`),console.log(` Tier 5 (other): ${r.other}`),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(` At ${pe}/day \u2192 ~${Math.ceil(s.length/pe)} days to clear queue
99
- `)}function yn(){console.log(""),console.log(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log(" \u2551 \u26A0 BAN-RISK WARNING \u2014 please read \u2551"),console.log(" \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(" \u2551 This script visits LinkedIn profiles WITHOUT performing any \u2551"),console.log(" \u2551 follow-up action (no message, no connect request, no like). \u2551"),console.log(" \u2551 LinkedIn has previously flagged accounts for exactly this \u2551"),console.log(' \u2551 pattern with a "we noticed unusual activity" warning. \u2551'),console.log(" \u2551 \u2551"),console.log(" \u2551 Safer alternative: let data accumulate organically through \u2551"),console.log(" \u2551 apply / outreach / funnel / visit \u2014 those visits HAVE a \u2551"),console.log(" \u2551 purpose and don't trip the same heuristic. \u2551"),console.log(" \u2551 \u2551"),console.log(" \u2551 If you proceed, keep --max small (\u226410) and run at most once \u2551"),console.log(" \u2551 per day. Your account, your call. \u2551"),console.log(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log("")}async function wn(){if(console.log(`
306
+ `),process.exit(0));function Do(e){try{return new RegExp(e,"i")}catch(t){console.error(`Invalid regex for --match-title: ${t.message}`),process.exit(1)}}var Ro=new Set(["pending","sent_with_note","sent_without_note"]);function Oo(e){return!e.about||!e.about.trim()}function jo(e){return!Ro.has(e.connectionStatus)}function Mt(){let e=K(),t=_e(),n=new Set,o=new Set;for(let i of Object.values(t))i.profileUrl&&n.add(i.profileUrl),(i.unread===!0||i.actionNeeded==="reply"||i.situation==="needs_our_reply"||i.conversationStatus==="unanswered_by_us")&&i.profileUrl&&o.add(i.profileUrl);let s=Object.entries(e).filter(([i,a])=>i&&i.startsWith("http")).filter(([,i])=>Oo(i)).filter(([,i])=>jo(i)).filter(([i])=>!o.has(i)).map(([i,a])=>({profileUrl:i,name:a.name,person:a,hasConversation:n.has(i)}));ue&&(s=s.filter(i=>i.person.connectionStatus==="connected")),_&&(s=s.filter(i=>_.test(i.person.title||"")));function l(i){let a=i.person.connectionStatus==="connected";return a&&i.hasConversation?1:a?2:_&&_.test(i.person.title||"")?3:i.hasConversation?4:5}return s.sort((i,a)=>{let f=l(i),c=l(a);if(f!==c)return f-c;let m=i.person.lastFullVisitAt||"",d=a.person.lastFullVisitAt||"";return m.localeCompare(d)}),s.map(i=>({profileUrl:i.profileUrl,name:i.name,source:"enrich-profile"}))}function No(){let e=K(),t=Object.keys(e).length,n=Object.values(e).filter(m=>m.about&&m.about.trim()).length,o=t-n,r=Mt(),s={connWithConv:0,conn:0,titleMatch:0,withConv:0,other:0},l=e,i=_e(),a=new Set(Object.values(i).map(m=>m.profileUrl).filter(Boolean)),f=Object.values(i).filter(m=>m.profileUrl&&(m.unread===!0||m.actionNeeded==="reply"||m.situation==="needs_our_reply"||m.conversationStatus==="unanswered_by_us")).length,c=0;for(let m of r){let d=l[m.profileUrl],p=d.connectionStatus==="connected",v=_&&_.test(d.title||""),b=a.has(m.profileUrl);d.lastFullVisitAt||c++,p&&b?s.connWithConv++:p?s.conn++:v?s.titleMatch++:b?s.withConv++:s.other++}console.log(`
307
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" PROFILE ENRICHMENT QUEUE"),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(` Total people: ${t}`),console.log(` With "about": ${n} (${(n/t*100).toFixed(1)}%)`),console.log(` Missing "about": ${o}`),console.log(` Skipped (needs reply): ${f}`),console.log(` Visitable (queue): ${r.length}`),console.log(` Never fully visited: ${c} (gone first)`),_&&console.log(` Title-match filter: /${_.source}/i`),ue&&console.log(" Connections-only: yes"),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Tier 1 (conn+conv): ${s.connWithConv}`),console.log(` Tier 2 (connection): ${s.conn}`),console.log(` Tier 3 (title match): ${s.titleMatch}${_?"":" (no --match-title set)"}`),console.log(` Tier 4 (conversation): ${s.withConv}`),console.log(` Tier 5 (other): ${s.other}`),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(` At ${ye}/day \u2192 ~${Math.ceil(r.length/ye)} days to clear queue
308
+ `)}function Fo(){console.log(""),console.log(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log(" \u2551 \u26A0 BAN-RISK WARNING \u2014 please read \u2551"),console.log(" \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(" \u2551 This script visits LinkedIn profiles WITHOUT performing any \u2551"),console.log(" \u2551 follow-up action (no message, no connect request, no like). \u2551"),console.log(" \u2551 LinkedIn has previously flagged accounts for exactly this \u2551"),console.log(' \u2551 pattern with a "we noticed unusual activity" warning. \u2551'),console.log(" \u2551 \u2551"),console.log(" \u2551 Safer alternative: let data accumulate organically through \u2551"),console.log(" \u2551 apply / outreach / funnel / visit \u2014 those visits HAVE a \u2551"),console.log(" \u2551 purpose and don't trip the same heuristic. \u2551"),console.log(" \u2551 \u2551"),console.log(" \u2551 If you proceed, keep --max small (\u226410) and run at most once \u2551"),console.log(" \u2551 per day. Your account, your call. \u2551"),console.log(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log("")}async function Lo(){if(console.log(`
100
309
  LinkedIn Profile Enricher
101
- `),cn){gn();return}yn(),Le&&(console.log(""),console.log(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log(" \u2551 \u26A0 --with-experience: extra ban-risk warning \u2551"),console.log(" \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(" \u2551 Each visit now does TWO page loads (main + /details/ \u2551"),console.log(" \u2551 experience/). That doubles LinkedIn's view-counter signal \u2551"),console.log(" \u2551 per profile. Keep --max low (\u226410) and run rarely. \u2551"),console.log(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(""));let e=At();if(console.log(` Queue size: ${e.length}`),console.log(` Max visits this session: ${pe}`),_&&console.log(` Title filter: /${_.source}/i`),re&&console.log(" Connections only: yes"),Le&&console.log(" With experience: yes (2\xD7 page loads per profile)"),console.log(""),e.length===0){console.log(` Nothing to enrich \u2014 every visitable profile already has "about".
102
- `);return}let t=re&&_?"connections+title":re?"connections":_?`title=${_.source}`:"all",o=pt("enrich-profiles",t),{browser:n,page:s}=await ze();try{let r=await at(s,e,{maxVisits:pe,verbose:un,skipRecentDays:7,extractExperience:Le}),l=W(),i=0;for(let a of e.slice(0,r.visited+r.skipped))l[a.profileUrl]?.about?.trim()&&i++;console.log(`
103
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" Enrichment 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(` Visited: ${r.visited}`),console.log(` Skipped (recent): ${r.skipped}`),console.log(` Errors: ${r.errors}`),console.log(` Have "about" now: ${i} / ${r.visited+r.skipped}`),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
104
- `),Ee(o,"success",r)}catch(r){console.error(`
105
- Error:`,r.message),Ee(o,"error",null,r.message)}finally{await n.close().catch(()=>{})}}wn().catch(e=>{console.error("Enrich-profiles failed:",e),process.exit(1)});
310
+ `),_o){No();return}Fo(),Be&&(console.log(""),console.log(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log(" \u2551 \u26A0 --with-experience: extra ban-risk warning \u2551"),console.log(" \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(" \u2551 Each visit now does TWO page loads (main + /details/ \u2551"),console.log(" \u2551 experience/). That doubles LinkedIn's view-counter signal \u2551"),console.log(" \u2551 per profile. Keep --max low (\u226410) and run rarely. \u2551"),console.log(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(""));let e=Mt();if(console.log(` Queue size: ${e.length}`),console.log(` Max visits this session: ${ye}`),_&&console.log(` Title filter: /${_.source}/i`),ue&&console.log(" Connections only: yes"),Be&&console.log(" With experience: yes (2\xD7 page loads per profile)"),console.log(""),e.length===0){console.log(` Nothing to enrich \u2014 every visitable profile already has "about".
311
+ `);return}let t=ue&&_?"connections+title":ue?"connections":_?`title=${_.source}`:"all",n=Et("enrich-profiles",t),{browser:o,page:r}=await lt();try{let s=await St(r,e,{maxVisits:ye,verbose:Io,skipRecentDays:7,extractExperience:Be}),l=K(),i=0;for(let a of e.slice(0,s.visited+s.skipped))l[a.profileUrl]?.about?.trim()&&i++;console.log(`
312
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" Enrichment 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(` Visited: ${s.visited}`),console.log(` Skipped (recent): ${s.skipped}`),console.log(` Errors: ${s.errors}`),console.log(` Have "about" now: ${i} / ${s.visited+s.skipped}`),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
313
+ `),Oe(n,"success",s)}catch(s){console.error(`
314
+ Error:`,s.message),Oe(n,"error",null,s.message)}finally{await o.close().catch(()=>{})}}Lo().catch(e=>{console.error("Enrich-profiles failed:",e),process.exit(1)});