ilml-plugin-linkedin 1.11.7 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/visit.mjs CHANGED
@@ -1,60 +1,63 @@
1
- var _t=Object.defineProperty;var ae=(e,t)=>{for(var o in t)_t(e,o,{get:t[o],enumerable:!0})};import Lt from"puppeteer";import{addExtra as Mt}from"puppeteer-extra";import Ft from"puppeteer-extra-plugin-stealth";async function j(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}async function Fe(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"),i=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),l=s.includes("Get hired faster")||s.includes("Get hired 2x");if(r||i||l){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 c=n.querySelectorAll("button");for(let f of c){let g=f.innerText?.trim().toLowerCase()||"",d=f.getAttribute("aria-label")?.toLowerCase()||"";if(g==="not now"||g==="no thanks"||g==="dismiss"||d.includes("dismiss"))return f.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})}import{getPluginConfig as It}from"@ilivemylife/graph-sdk";var Tt=await It();for(let[e,t]of Object.entries(Tt))process.env[e]===void 0&&(process.env[e]=t);var Dt=process.env.LINKEDIN_NAME,U=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),dn=Object.freeze(new Set([U.DRAFT,U.CONFIRMED,U.NEEDS_REVIEW])),Rt=Object.freeze(new Set([U.DRAFT,U.CONFIRMED,U.REJECTED,U.NEEDS_REVIEW]));import Pe from"fs";import jt from"path";var Ot="cookies.json";function Nt(){let e=process.env.ILML_SCOPE_DIR;return e?jt.join(e,"plugins-state","linkedin","cookies.json"):Ot}function qe(){let e=Nt();if(!Pe.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Pe.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 Ue=Mt(Lt);Ue.use(Ft());async function Be(){let e=await Ue.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
2
- 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=qe();await o.setCookie(...n),console.log(" Browser launched, cookies loaded.")}catch(n){console.error(`
1
+ var Nt=Object.defineProperty;var He=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{for(var o in t)Nt(e,o,{get:t[o],enumerable:!0})};async function A(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}async function Je(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"),i=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),u=s.includes("Get hired faster")||s.includes("Get hired 2x");if(r||i||u){let l=n.querySelector('button[aria-label="Dismiss"]')||n.querySelector("button.artdeco-modal__dismiss")||n.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:s.substring(0,80)};let m=n.querySelectorAll("button");for(let a of m){let y=a.innerText?.trim().toLowerCase()||"",c=a.getAttribute("aria-label")?.toLowerCase()||"";if(y==="not now"||y==="no thanks"||y==="dismiss"||c.includes("dismiss"))return a.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 oe=He(()=>{});var nt={};fe(nt,{extractExperienceFromDetails:()=>co});async function co(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await A(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 A(900);await A(1e3);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 A(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await A(700);return await e.evaluate(()=>{let r=document.querySelector("main");if(!r)return[];function i(a){let y=[];for(let c of a.querySelectorAll("div")){let f=Array.from(c.children).filter(S=>S.tagName==="DIV");if(f.length<3)continue;let C=f.filter(S=>(S.textContent||"").trim().length>50);C.length<3||(c.textContent||"").length<500||y.push({el:c,count:C.length,totalText:(c.textContent||"").length})}return y.sort((c,f)=>f.count-c.count||c.totalText-f.totalText),y[0]?.el}let u=i(r);if(!u)return[];let l=Array.from(u.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function m(a){let y=a[0]||null,c=null,f=null;if(a[1]){let v=a[1].split("\xB7").map(_=>_.trim());c=v[0]||null,v[1]&&(f=v[1])}let C=a.findIndex(v=>/(\d{4}|present)/i.test(v)&&/(-|–|—)/i.test(v)&&v.length<80),S=null,E=null;if(C>=0){let v=a[C].split("\xB7").map(_=>_.trim());S=v[0]||null,v[1]&&(E=v[1])}let p=null,g=-1;if(C>=0&&a[C+1]){let v=a[C+1],_=/^[>*\-•]|^&gt;/.test(v),ue=/https?:\/\//.test(v),de=/\d{4}/.test(v),Q=/,/.test(v)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(v);!_&&!ue&&!de&&v.length<100&&Q&&(p=v,g=C+1)}let D=null,ee=-1,V=a[a.length-1];if(V&&/and\s+\+\d+\s+skills?$/i.test(V)){ee=a.length-1;let v=V.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);v&&(D={listed:v[1].split(",").map(_=>_.trim()),additional:parseInt(v[2],10)})}let le=new Set([0,1,C,g,ee].filter(v=>v>=0)),ae=a.filter((v,_)=>!le.has(_)),ce=ae.length>0?ae.join(`
2
+
3
+ `):null;return{title:y,company:c,employmentType:f,dates:S,duration:E,location:p,description:ce,skills:D,_raw:a}}return l.map(a=>{let c=(a.innerText||"").trim().split(`
4
+ `).map(f=>f.trim()).filter(f=>f&&f.length<5e3);return m(c)}).filter(a=>a.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 st=He(()=>{oe()});import Vt from"puppeteer";import{addExtra as Ht}from"puppeteer-extra";import Jt from"puppeteer-extra-plugin-stealth";oe();import{getPluginConfig as Lt}from"@ilivemylife/graph-sdk";var Mt=await Lt();for(let[e,t]of Object.entries(Mt))process.env[e]===void 0&&(process.env[e]=t);var Ft=process.env.LINKEDIN_NAME,H=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),bn=Object.freeze(new Set([H.DRAFT,H.CONFIRMED,H.NEEDS_REVIEW])),Pt=Object.freeze(new Set([H.DRAFT,H.CONFIRMED,H.REJECTED,H.NEEDS_REVIEW]));import We from"fs";import qt from"path";var Ut="cookies.json";function Bt(){let e=process.env.ILML_SCOPE_DIR;return e?qt.join(e,"plugins-state","linkedin","cookies.json"):Ut}function Ge(){let e=Bt();if(!We.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=We.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=Ht(Vt);Ye.use(Jt());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(`
3
6
  [!] ${n.message}
4
- `),await e.close(),process.exit(1)}return{browser:e,page:o}}import"dotenv/config";import*as v from"fs";import*as C from"path";import{fileURLToPath as Pt}from"url";var qt=Pt(import.meta.url),Ut=C.dirname(C.dirname(qt)),N=process.env.DATA_DIR?C.resolve(process.env.DATA_DIR,"collected-profiles"):C.join(Ut,"collected-profiles"),ce=C.join(N,"people.json"),In=C.join(N,"jobs.json"),Tn=C.join(N,"quota.json"),Dn=C.join(N,"conversations.json"),Rn=C.join(N,"sync-state.json"),jn=C.join(N,"application-questions.json"),ue=C.join(N,"profile-history");var Y=null,Bt=null,Vt=null,Ht=null,Jt=null,Wt=null;function Je(){Y=null,Bt=null,Vt=null,Ht=null,Jt=null,Wt=null}function We(){v.existsSync(N)||v.mkdirSync(N,{recursive:!0})}function Ge(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";v.writeFileSync(n,o);for(let s=0;s<3;s++)try{v.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function Ye(e,t){if(!v.existsSync(e))return null;try{let o=JSON.parse(v.readFileSync(e,"utf-8"));try{v.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(v.existsSync(n))try{let s=JSON.parse(v.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{v.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{v.copyFileSync(e,e+".corrupted")}catch{}return null}}function Gt(){return new Date().toISOString().split("T")[0]}var Yt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections"],zt=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function de(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Kt(){v.existsSync(ue)||v.mkdirSync(ue,{recursive:!0})}function ze(e){let t=de(e);return t?C.join(ue,`${t}.json`):null}function Qt(e){let t=ze(e);return t?Ye(t,`profile-history/${de(e)}.json`)||[]:[]}function Zt(e,t){let o=ze(e);if(!o)return;Kt();let n=Qt(e);n.unshift(t);try{Ge(o,n)}catch(s){console.error(`[!] Failed to append profile-history for ${de(e)}: ${s.message}`)}}function Ve(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function He(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Xt(e,t){if(!e)return[];let o=[];for(let n of zt){let s=e[n],r=t[n];Ve(s)||Ve(r)||He(s)!==He(r)&&o.push(n)}return o}function eo(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 Q(){return Y||(We(),Y=Ye(ce,"people.json")||{},Y)}function to(e){We(),Y=e;try{Ge(ce,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${C.resolve(ce)}`)}}function fe(e,t={}){if(!e)return null;let o=Q(),n=Gt(),s=new Date().toISOString(),r=o[e];if(r){let i=Xt(r,t);i.length>0&&(Zt(e,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:i,snapshot:eo(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 l of Yt)t[l]!=null&&(r[l]=t[l]);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,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 to(o),o[e]}async function oo(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 j(3e3);let n=e.url();return n.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${n.slice(0,80)}`),!0}async function Ke(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3),await Fe(e)&&(console.log(" Dismissed Premium overlay"),await j(1500),await oo(e,t));let n=0;for(let r=0;r<2;r++){let i=await e.evaluate(()=>document.body.scrollHeight);for(let a=1;a<=6;a++)await e.evaluate(c=>window.scrollTo(0,c),i*a/6),await j(900);let l=await e.evaluate(()=>document.body.scrollHeight);if(l===n)break;n=l}await j(800);let s=await e.evaluate(()=>{let r=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"]),i=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"]),l=m=>{let h=(m||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(h)},a={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:[]},c=document.querySelector("main");if(!c)return a;let f=[...Array.from(c.querySelectorAll("h1")),...Array.from(c.querySelectorAll("h2"))],g=Array.from(c.querySelectorAll("h2")),d=f.find(m=>{let h=m.textContent&&m.textContent.trim(),b=(h||"").replace(/\s*\(\d+\)$/,"").trim();return h&&h.length>1&&h.length<100&&!r.has(b)&&!i.has(b)}),w=d?d.textContent.trim():null,k=d?d.parentElement:null;for(;k&&k!==c&&!Array.from(k.children).filter(h=>h.tagName==="P").some(h=>{let b=h.textContent&&h.textContent.trim();return b&&b.length>5&&!l(b)});)k=k.parentElement;let $=null,R=null,y=null,p=null;if(k&&k!==c){let m=Array.from(k.children).filter(b=>b.tagName==="P").filter(b=>{let F=b.textContent&&b.textContent.trim();return F&&F.length>5&&!l(F)});if(m[0]&&($=m[0].textContent.trim()),m[1]){let b=m[1].textContent.trim().split(/\s*[·•]\s*/);R=b[0]||null,b.length>1&&(y=b.slice(1).join(" \xB7 "))}let h=Array.from(k.children).filter(b=>b.tagName==="DIV");for(let b=h.length-1;b>=0;b--){let F=h[b].textContent&&h[b].textContent.trim();if(F&&!(w&&F.startsWith(w))&&(p=F.split(/[·•]/)[0].trim(),p))break}}let M=null;if(k){let m=k.querySelectorAll("p, span, div");for(let h of m){let b=(h.textContent||"").trim().replace(/^[·•]\s*/,"");if(b==="1st"||b==="2nd"||b==="3rd"){M=b;break}}}let vt=!!c.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),_e=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),kt=_e&&_e.src||null,te=c.textContent||"",Ie=null,Te=te.match(/(\d+\+?)\s+connections\b/i);Te&&(Ie=Te[1]+" connections");let oe=null,De=te.match(/(\d+)\s+mutual connection/i),Re=te.match(/and\s+(\d+)\s+other mutual/i),Ct=te.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);De?oe=parseInt(De[1],10):Re?oe=2+parseInt(Re[1],10):Ct&&(oe=2);let je=null,Oe=null,Ne=g.find(m=>m.textContent&&m.textContent.trim()==="About");if(Ne){let m=Ne.parentElement;for(;m&&m.tagName!=="SECTION";)m=m.parentElement;if(m){let h=(m.textContent||"").trim();h=h.replace(/^About\s*/,"").trim();let b=h.match(/Top skills\s*(.+?)$/i);if(b){let le=b[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(xt=>xt.trim()).filter(Boolean);le.length>0&&le.length<10&&(Oe=le)}h=h.split(/\n?…\s*more/i)[0].trim(),h=h.split(/\n?\.\.\.\s*more/i)[0].trim(),h=h.split(/\bTop skills\b/i)[0].trim(),h=h.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),je=h||null}}let Le=null,Me=g.find(m=>m.textContent&&m.textContent.trim()==="Activity");if(Me){let m=Me.parentElement;for(;m&&m.tagName!=="SECTION";)m=m.parentElement;if(m){let h=(m.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);h&&(Le=parseInt(h[1].replace(/,/g,""),10))}}let $t=[...new Set(g.map(m=>(m.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(m=>m&&m.length>1&&m.length<60&&m!==w).filter(m=>r.has(m)))],K=document.body.textContent||"",At=/#OpenToWork\b/i.test(K)||/\bOpen to work\b/.test(K),Et=/#Hiring\b/i.test(K)||/\bI'?m hiring\b/i.test(K)||/\bWe are hiring\b/i.test(K);return{name:w,title:$,location:p,currentCompany:R,currentSchool:y,connectionDegree:M,hasVerifiedBadge:vt,photoUrl:kt,connectionsLevel:Ie,mutualConnectionsCount:oe,followers:Le,openToWork:At,hiring:Et,about:je,topSkills:Oe,availableSections:$t}});return console.log(`Viewed: ${s.name} - ${s.title}`),{...s,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await j(1e3)}catch{}return null}}import"dotenv/config";import*as x from"fs";import*as E from"path";import{fileURLToPath as no}from"url";var so=no(import.meta.url),ro=E.dirname(E.dirname(so)),V=process.env.DATA_DIR?E.resolve(process.env.DATA_DIR,"market-research"):E.join(ro,"market-research"),io=E.join(V,"scouted-jobs.json"),lo=E.join(V,"discovered-people.json"),Qe=E.join(V,"visit-log.json"),Wn=E.join(V,"companies.json"),Gn=E.join(V,"job-decisions.json");function ao(){x.existsSync(V)||x.mkdirSync(V,{recursive:!0})}function co(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";x.writeFileSync(n,o);for(let s=0;s<3;s++)try{x.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function me(e){try{if(x.existsSync(e))return JSON.parse(x.readFileSync(e,"utf-8"))}catch{}return null}function Ze(){Z=null,fo=null,X=null,mo=null,B=null}var Z=null;function uo(){return Z||(Z=me(io)||{},Z)}var fo=null;var X=null;function ne(){return X||(X=me(lo)||{},X)}var mo=null;var B=null;function z(){return B||(B=me(Qe)||{visits:[]},Array.isArray(B.visits)||(B.visits=[]),B)}function Xe(e,t={}){if(!e)return;ao();let o=z();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{co(Qe,o)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function et(e){let t=z();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function tt(){let e=uo(),t=ne(),o=Object.values(e),n=Object.values(t),s={};for(let d of o)d.company&&(s[d.company]=(s[d.company]||0)+1);let r=Object.entries(s).sort((d,w)=>w[1]-d[1]).slice(0,5).map(([d,w])=>`${d} (${w})`),i={};for(let d of o)for(let w of d.techStack||[])i[w]=(i[w]||0)+1;let l=Object.entries(i).sort((d,w)=>w[1]-d[1]).slice(0,8).map(([d,w])=>`${d} (${w})`),a=z(),c=new Date().toISOString().slice(0,10),f=a.visits.filter(d=>d.date.startsWith(c)).length,g=new Set(a.visits.map(d=>d.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:n.length,topCompanies:r,topTech:l,totalVisited:g,todayVisited:f,lastScoutDate:o.length>0?o.sort((d,w)=>(w.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}async function ot(e,t,o={}){let{maxVisits:n=50,delayBetween:s=4e3,skipRecentDays:r=7,verbose:i=!1}=o,l={visited:0,skipped:0,errors:0},a=Date.now()-r*24*60*60*1e3;for(let c of t){if(l.visited>=n)break;if(!c.profileUrl)continue;let f=et(c.profileUrl);if(f&&new Date(f).getTime()>a){l.skipped++;continue}try{let g=await Ke(e,c.profileUrl),d=c.source||"visit";g&&fe(c.profileUrl,{...g,source:d}),Xe(c.profileUrl,{name:g?.name||c.name||null,source:d}),l.visited++,i?console.log(` [${l.visited}] ${g?.name||c.profileUrl} \u2014 ${g?.title?.slice(0,40)||"?"}`):l.visited%10===0&&console.log(` Visited: ${l.visited}`);let w=Math.random()*4e3;await j(s+w)}catch(g){l.errors++,i&&console.error(` Error visiting ${c.name||c.profileUrl}: ${g.message?.slice(0,60)}`);let d=(g.message||"").toLowerCase();if(d.includes("detached")||d.includes("session closed")||d.includes("target closed")){console.log(" Fatal browser error \u2014 stopping visits");break}}}return l}function nt(e={}){let{limit:t=150,revisitDays:o=14}=e,n=z(),s=new Set(n.visits?.map(y=>y.profileUrl)||[]),r=new Map;for(let y of n.visits||[]){let p=r.get(y.profileUrl);(!p||y.date>p)&&r.set(y.profileUrl,y.date)}let i=Date.now()-7*24*60*60*1e3,l=Date.now()-o*24*60*60*1e3;function a(y){let p=r.get(y);return p&&new Date(p).getTime()>i}let c=ne(),f=Object.entries(c).filter(([y])=>!s.has(y)).map(([y,p])=>({profileUrl:y,name:p.name,source:"new-discovered",priority:1,jobCount:p.jobIds?.length||0})),g=Q(),d=Object.entries(g).filter(([y,p])=>p.connectionStatus==="connected"||a(y)?!1:(p.jobCount||p.jobIds?.length||0)>=2).map(([y,p])=>({profileUrl:y,name:p.name,source:"active-recruiter",priority:2,jobCount:p.jobCount||p.jobIds?.length||0})),w=Object.entries(g).filter(([y,p])=>{let M=p.connectionStatus;return!(!M||M==="connected"||M==="pending"||M==="sent_without_note"||M==="sent_with_note"||a(y)||(p.jobCount||p.jobIds?.length||0)>=2)}).map(([y,p])=>({profileUrl:y,name:p.name,source:"unconnected",priority:3,jobCount:p.jobCount||p.jobIds?.length||0})),k=[...r.entries()].filter(([y,p])=>new Date(p).getTime()<l).map(([y,p])=>({profileUrl:y,name:null,source:"revisit",priority:4,lastVisit:p})),$=y=>y.sort(()=>Math.random()-.5);return f.sort((y,p)=>p.jobCount-y.jobCount),d.sort((y,p)=>p.jobCount-y.jobCount),$(w),$(k),[...f,...d,...w,...k].slice(0,t)}function st(){let e=ne();return Object.entries(e).map(([t,o])=>({profileUrl:t,name:o.name,source:"discovered"}))}function pe(){let e=Q();return Object.entries(e).filter(([,t])=>{let o=t.connectionStatus;return o&&o!=="connected"&&o!=="pending"&&o!=="sent_without_note"&&o!=="sent_with_note"}).map(([t,o])=>({profileUrl:t,name:o.name,source:"unconnected"}))}function he(e=14){let t=z(),o=Date.now()-e*24*60*60*1e3,n=new Map;for(let s of t.visits){let r=n.get(s.profileUrl);(!r||s.date>r.date)&&n.set(s.profileUrl,s)}return[...n.entries()].filter(([,s])=>new Date(s.date).getTime()<o).map(([s,r])=>({profileUrl:s,name:r.name,source:"revisit"}))}import"dotenv/config";import*as _ from"fs";import*as P from"path";import{fileURLToPath as bo}from"url";import"dotenv/config";import{createGraphClient as po,resolveToken as ho}from"@ilivemylife/graph-sdk";import{config as go}from"dotenv";go();var rt=ho()||process.env.TOKEN;rt||(console.error(`
7
+ `),await e.close(),process.exit(1)}return{browser:e,page:o}}oe();import"dotenv/config";import*as $ from"fs";import*as x from"path";import{fileURLToPath as Wt}from"url";var Gt=Wt(import.meta.url),Yt=x.dirname(x.dirname(Gt)),F=process.env.DATA_DIR?x.resolve(process.env.DATA_DIR,"collected-profiles"):x.join(Yt,"collected-profiles"),we=x.join(F,"people.json"),Mn=x.join(F,"jobs.json"),Fn=x.join(F,"quota.json"),Pn=x.join(F,"conversations.json"),qn=x.join(F,"sync-state.json"),Un=x.join(F,"application-questions.json"),be=x.join(F,"profile-history");var Z=null,zt=null,Kt=null,Qt=null,Zt=null,Xt=null;function Ze(){Z=null,zt=null,Kt=null,Qt=null,Zt=null,Xt=null}function Xe(){$.existsSync(F)||$.mkdirSync(F,{recursive:!0})}function et(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";$.writeFileSync(n,o);for(let s=0;s<3;s++)try{$.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function tt(e,t){if(!$.existsSync(e))return null;try{let o=JSON.parse($.readFileSync(e,"utf-8"));try{$.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${x.resolve(e)}`);let n=e+".backup";if($.existsSync(n))try{let s=JSON.parse($.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{$.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{$.copyFileSync(e,e+".corrupted")}catch{}return null}}function eo(){return new Date().toISOString().split("T")[0]}var to=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt"],oo=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function Se(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function no(){$.existsSync(be)||$.mkdirSync(be,{recursive:!0})}function ot(e){let t=Se(e);return t?x.join(be,`${t}.json`):null}function so(e){let t=ot(e);return t?tt(t,`profile-history/${Se(e)}.json`)||[]:[]}function ro(e,t){let o=ot(e);if(!o)return;no();let n=so(e);n.unshift(t);try{et(o,n)}catch(s){console.error(`[!] Failed to append profile-history for ${Se(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 io(e,t){if(!e)return[];let o=[];for(let n of oo){let s=e[n],r=t[n];Ke(s)||Ke(r)||Qe(s)!==Qe(r)&&o.push(n)}return o}function lo(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 ne(){return Z||(Xe(),Z=tt(we,"people.json")||{},Z)}function ao(e){Xe(),Z=e;try{et(we,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${x.resolve(we)}`)}}function ve(e,t={}){if(!e)return null;let o=ne(),n=eo(),s=new Date().toISOString(),r=o[e];if(r){let i=io(r,t);i.length>0&&(ro(e,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:i,snapshot:lo(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 u of to)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(r[u])&&r[u].length>0)continue;r[u]=t[u]}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 ao(o),o[e]}async function uo(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3);let n=e.url();return n.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${n.slice(0,80)}`),!0}async function rt(e,t,o={}){let{extractExperience:n=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3),await Je(e)&&(console.log(" Dismissed Premium overlay"),await A(1500),await uo(e,t));let r=0;for(let l=0;l<2;l++){let m=await e.evaluate(()=>document.body.scrollHeight);for(let y=1;y<=6;y++)await e.evaluate(c=>window.scrollTo(0,c),m*y/6),await A(900);let a=await e.evaluate(()=>document.body.scrollHeight);if(a===r)break;r=a}await A(800);let i=await e.evaluate(()=>{let l=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"]),m=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"]),a=h=>{let w=(h||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(w)},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:[]},c=document.querySelector("main");if(!c)return y;let f=[...Array.from(c.querySelectorAll("h1")),...Array.from(c.querySelectorAll("h2"))],C=Array.from(c.querySelectorAll("h2")),S=f.find(h=>{let w=h.textContent&&h.textContent.trim(),b=(w||"").replace(/\s*\(\d+\)$/,"").trim();return w&&w.length>1&&w.length<100&&!l.has(b)&&!m.has(b)}),E=S?S.textContent.trim():null,p=S?S.parentElement:null;for(;p&&p!==c&&!Array.from(p.children).filter(w=>w.tagName==="P").some(w=>{let b=w.textContent&&w.textContent.trim();return b&&b.length>5&&!a(b)});)p=p.parentElement;let g=null,D=null,ee=null,V=null;if(p&&p!==c){let h=Array.from(p.children).filter(b=>b.tagName==="P").filter(b=>{let q=b.textContent&&b.textContent.trim();return q&&q.length>5&&!a(q)});if(h[0]&&(g=h[0].textContent.trim()),h[1]){let b=h[1].textContent.trim().split(/\s*[·•]\s*/);D=b[0]||null,b.length>1&&(ee=b.slice(1).join(" \xB7 "))}let w=Array.from(p.children).filter(b=>b.tagName==="DIV");for(let b=w.length-1;b>=0;b--){let q=w[b].textContent&&w[b].textContent.trim();if(q&&!(E&&q.startsWith(E))&&(V=q.split(/[·•]/)[0].trim(),V))break}}let le=null;if(p){let h=p.querySelectorAll("p, span, div");for(let w of h){let b=(w.textContent||"").trim().replace(/^[·•]\s*/,"");if(b==="1st"||b==="2nd"||b==="3rd"){le=b;break}}}let ae=!!c.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),ce=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),v=ce&&ce.src||null,_=c.textContent||"",ue=null,de=_.match(/(\d+\+?)\s+connections\b/i);de&&(ue=de[1]+" connections");let Q=null,Me=_.match(/(\d+)\s+mutual connection/i),Fe=_.match(/and\s+(\d+)\s+other mutual/i),Tt=_.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):Tt&&(Q=2);let Pe=null,qe=null,Ue=C.find(h=>h.textContent&&h.textContent.trim()==="About");if(Ue){let h=Ue.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let w=(h.textContent||"").trim();w=w.replace(/^About\s*/,"").trim();let b=w.match(/Top skills\s*(.+?)$/i);if(b){let ye=b[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ot=>Ot.trim()).filter(Boolean);ye.length>0&&ye.length<10&&(qe=ye)}w=w.split(/\n?…\s*more/i)[0].trim(),w=w.split(/\n?\.\.\.\s*more/i)[0].trim(),w=w.split(/\bTop skills\b/i)[0].trim(),w=w.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Pe=w||null}}let Be=null,Ve=C.find(h=>h.textContent&&h.textContent.trim()==="Activity");if(Ve){let h=Ve.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let w=(h.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);w&&(Be=parseInt(w[1].replace(/,/g,""),10))}}let Dt=[...new Set(C.map(h=>(h.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(h=>h&&h.length>1&&h.length<60&&h!==E).filter(h=>l.has(h)))],te=document.body.textContent||"",Rt=/#OpenToWork\b/i.test(te)||/\bOpen to work\b/.test(te),jt=/#Hiring\b/i.test(te)||/\bI'?m hiring\b/i.test(te)||/\bWe are hiring\b/i.test(te);return{name:E,title:g,location:V,currentCompany:D,currentSchool:ee,connectionDegree:le,hasVerifiedBadge:ae,photoUrl:v,connectionsLevel:ue,mutualConnectionsCount:Q,followers:Be,openToWork:Rt,hiring:jt,about:Pe,topSkills:qe,availableSections:Dt}});console.log(`Viewed: ${i.name} - ${i.title}`);let u=null;if(n){let{extractExperienceFromDetails:l}=await Promise.resolve().then(()=>(st(),nt));u=await l(e,t),console.log(` + Experience: ${u.length} entries`)}return{...i,profileUrl:t,...u!==null&&{experience:u}}}catch(s){console.error(`Error viewing profile ${t}:`,s.message);try{await e.goto("about:blank",{timeout:1e4}),await A(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 fo}from"url";var mo=fo(import.meta.url),po=T.dirname(T.dirname(mo)),W=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"market-research"):T.join(po,"market-research"),ho=T.join(W,"scouted-jobs.json"),go=T.join(W,"discovered-people.json"),it=T.join(W,"visit-log.json"),ts=T.join(W,"companies.json"),os=T.join(W,"job-decisions.json");function yo(){R.existsSync(W)||R.mkdirSync(W,{recursive:!0})}function wo(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 i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function ke(e){try{if(R.existsSync(e))return JSON.parse(R.readFileSync(e,"utf-8"))}catch{}return null}function lt(){se=null,So=null,re=null,vo=null,J=null}var se=null;function bo(){return se||(se=ke(ho)||{},se)}var So=null;var re=null;function me(){return re||(re=ke(go)||{},re)}var vo=null;var J=null;function X(){return J||(J=ke(it)||{visits:[]},Array.isArray(J.visits)||(J.visits=[]),J)}function at(e,t={}){if(!e)return;yo();let o=X();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{wo(it,o)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function ct(e){let t=X();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function ut(){let e=bo(),t=me(),o=Object.values(e),n=Object.values(t),s={};for(let c of o)c.company&&(s[c.company]=(s[c.company]||0)+1);let r=Object.entries(s).sort((c,f)=>f[1]-c[1]).slice(0,5).map(([c,f])=>`${c} (${f})`),i={};for(let c of o)for(let f of c.techStack||[])i[f]=(i[f]||0)+1;let u=Object.entries(i).sort((c,f)=>f[1]-c[1]).slice(0,8).map(([c,f])=>`${c} (${f})`),l=X(),m=new Date().toISOString().slice(0,10),a=l.visits.filter(c=>c.date.startsWith(m)).length,y=new Set(l.visits.map(c=>c.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:n.length,topCompanies:r,topTech:u,totalVisited:y,todayVisited:a,lastScoutDate:o.length>0?o.sort((c,f)=>(f.scoutedAt||"").localeCompare(c.scoutedAt||""))[0]?.scoutedAt:null}}oe();async function dt(e,t,o={}){let{maxVisits:n=50,delayBetween:s=4e3,skipRecentDays:r=7,verbose:i=!1,extractExperience:u=!1}=o,l={visited:0,skipped:0,errors:0},m=Date.now()-r*24*60*60*1e3;for(let a of t){if(l.visited>=n)break;if(!a.profileUrl)continue;let y=ct(a.profileUrl);if(y&&new Date(y).getTime()>m){l.skipped++;continue}try{let c=await rt(e,a.profileUrl,{extractExperience:u}),f=a.source||"visit";if(c){let S={...c,source:f};u&&Array.isArray(c.experience)&&c.experience.length>0&&(S._lastEnrichedAt=new Date().toISOString()),ve(a.profileUrl,S)}at(a.profileUrl,{name:c?.name||a.name||null,source:f}),l.visited++,i?console.log(` [${l.visited}] ${c?.name||a.profileUrl} \u2014 ${c?.title?.slice(0,40)||"?"}`):l.visited%10===0&&console.log(` Visited: ${l.visited}`);let C=Math.random()*4e3;await A(s+C)}catch(c){l.errors++,i&&console.error(` Error visiting ${a.name||a.profileUrl}: ${c.message?.slice(0,60)}`);let f=(c.message||"").toLowerCase();if(f.includes("detached")||f.includes("session closed")||f.includes("target closed")||f.includes("session expired")||f.includes("bounced to")||f.includes("authwall")||f.includes("checkpoint")||f.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return l}function ft(e={}){let{limit:t=150,revisitDays:o=14}=e,n=X(),s=new Set(n.visits?.map(p=>p.profileUrl)||[]),r=new Map;for(let p of n.visits||[]){let g=r.get(p.profileUrl);(!g||p.date>g)&&r.set(p.profileUrl,p.date)}let i=Date.now()-7*24*60*60*1e3,u=Date.now()-o*24*60*60*1e3;function l(p){let g=r.get(p);return g&&new Date(g).getTime()>i}let m=me(),a=Object.entries(m).filter(([p])=>!s.has(p)).map(([p,g])=>({profileUrl:p,name:g.name,source:"new-discovered",priority:1,jobCount:g.jobIds?.length||0})),y=ne(),c=Object.entries(y).filter(([p,g])=>g.connectionStatus==="connected"||l(p)?!1:(g.jobCount||g.jobIds?.length||0)>=2).map(([p,g])=>({profileUrl:p,name:g.name,source:"active-recruiter",priority:2,jobCount:g.jobCount||g.jobIds?.length||0})),f=Object.entries(y).filter(([p,g])=>{let D=g.connectionStatus;return!(!D||D==="connected"||D==="pending"||D==="sent_without_note"||D==="sent_with_note"||l(p)||(g.jobCount||g.jobIds?.length||0)>=2)}).map(([p,g])=>({profileUrl:p,name:g.name,source:"unconnected",priority:3,jobCount:g.jobCount||g.jobIds?.length||0})),C=[...r.entries()].filter(([p,g])=>new Date(g).getTime()<u).map(([p,g])=>({profileUrl:p,name:null,source:"revisit",priority:4,lastVisit:g})),S=p=>p.sort(()=>Math.random()-.5);return a.sort((p,g)=>g.jobCount-p.jobCount),c.sort((p,g)=>g.jobCount-p.jobCount),S(f),S(C),[...a,...c,...f,...C].slice(0,t)}function mt(){let e=me();return Object.entries(e).map(([t,o])=>({profileUrl:t,name:o.name,source:"discovered"}))}function Ce(){let e=ne();return Object.entries(e).filter(([,t])=>{let o=t.connectionStatus;return o&&o!=="connected"&&o!=="pending"&&o!=="sent_without_note"&&o!=="sent_with_note"}).map(([t,o])=>({profileUrl:t,name:o.name,source:"unconnected"}))}function $e(e=14){let t=X(),o=Date.now()-e*24*60*60*1e3,n=new Map;for(let s of t.visits){let r=n.get(s.profileUrl);(!r||s.date>r.date)&&n.set(s.profileUrl,s)}return[...n.entries()].filter(([,s])=>new Date(s.date).getTime()<o).map(([s,r])=>({profileUrl:s,name:r.name,source:"revisit"}))}import"dotenv/config";import*as j from"fs";import*as U from"path";import{fileURLToPath as Eo}from"url";import"dotenv/config";import{createGraphClient as ko,resolveToken as Co}from"@ilivemylife/graph-sdk";import{config as $o}from"dotenv";$o();var pt=Co()||process.env.TOKEN;pt||(console.error(`
5
8
  [FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
6
9
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
7
10
  `),console.error(` Or add ILML_TOKEN=... to .env
8
- `),process.exit(1));var it=po({token:rt});function yo(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 wo({scriptName:e,mode:t,status:o,error:n,duration:s}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${yo(s)}`:"",a=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${c} \u2014 ${a} \u2014 ${i}${l}`}async function lt({scriptName:e,mode:t,status:o,summaryLines:n,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let a=`**${wo({scriptName:e,mode:t,status:o,error:s,duration:r})}**
11
+ `),process.exit(1));var ht=ko({token:pt});function xo(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 Ao({scriptName:e,mode:t,status:o,error:n,duration:s}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),u=s?` ${xo(s)}`:"",l=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",m=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${m} \u2014 ${l} \u2014 ${i}${u}`}async function gt({scriptName:e,mode:t,status:o,summaryLines:n,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let l=`**${Ao({scriptName:e,mode:t,status:o,error:s,duration:r})}**
9
12
 
10
13
  ${n.join(`
11
- `)}`;try{await it.addMessage(i,a)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var So=bo(import.meta.url),vo=P.dirname(P.dirname(So)),ge=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"collected-profiles"):P.join(vo,"collected-profiles"),ye=P.join(ge,"run-log.json");function ko(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";_.writeFileSync(n,o);for(let s=0;s<3;s++)try{_.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function at(){try{if(!_.existsSync(ye))return{runs:[]};let e=JSON.parse(_.readFileSync(ye,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ct(e){_.existsSync(ge)||_.mkdirSync(ge,{recursive:!0});try{ko(ye,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ut(e,t="default"){let o=at();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.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(i=>new Date(i.timestamp).getTime()>r),ct(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function we(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=at(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=n,s=l.duration;else{let a=i.runs.find(c=>c.script===e.script&&c.status==="running"&&c.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)}ct(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";lt({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as u from"fs";import*as Ae from"os";import*as S from"path";import{fileURLToPath as qo}from"url";var ve={};ae(ve,{NAME:()=>$o,VERSION:()=>Co,up:()=>xo});import*as I from"fs";import*as se from"path";var Co=1,$o="normalize-jobs-and-questions",Ao=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Eo=50;function be(e){return I.existsSync(e)?JSON.parse(I.readFileSync(e,"utf-8")):null}function Se(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{I.writeFileSync(n,o)}catch(s){try{I.unlinkSync(n)}catch{}throw s}try{I.renameSync(n,e)}catch(s){try{I.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 xo(e,t){let o=se.join(e,"jobs.json"),n=se.join(t,"scouted-jobs.json"),s=se.join(e,"application-questions.json"),r=be(o)||{},i=be(n)||{},l=0,a=[];for(let f of Object.keys(r)){if(!i[f])continue;let g=i[f],d=r[f];for(let w of Ao)g[w]!=null&&d[w]==null&&(d[w]=g[w]);a.push(f),l++}l>0?(Se(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=be(s);if(c&&Array.isArray(c.applications)){let f={},g=0;for(let d of c.applications){let w=d.jobId||"unknown";f[w]||(f[w]={applications:[]});let k=(d.questions||[]).map($=>{let R={type:$.type||"input",question:$.question||"",answer:$.answer||""};return $.options&&($.options.length<=Eo?R.options=$.options:(R.optionsOmitted=!0,g++)),$.page&&(R.page=$.page),$.wasPreFilled&&(R.wasPreFilled=!0),$.wasRetry&&(R.wasRetry=!0),R});f[w].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||k.length,questions:k})}Se(s,f),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),g>0&&console.log(` Phase 2: Stripped bloated options from ${g} questions`)}else c&&!c.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 f of a)delete i[f];Se(n,i),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ke={};ae(ke,{NAME:()=>Io,VERSION:()=>_o,up:()=>Ro});import*as T from"fs";import*as dt from"path";var _o=2,Io="reset-unread-flags";function To(e){return T.existsSync(e)?JSON.parse(T.readFileSync(e,"utf-8")):null}function Do(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{T.writeFileSync(n,o)}catch(s){try{T.unlinkSync(n)}catch{}throw s}try{T.renameSync(n,e)}catch(s){try{T.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 Ro(e){let t=dt.join(e,"conversations.json"),o=To(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}Do(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ce={};ae(Ce,{NAME:()=>Oo,VERSION:()=>jo,up:()=>Po});import*as D from"fs";import*as ft from"path";var jo=3,Oo="recompute-last-message-by",No=new Set(["draft","confirmed","rejected","needs_review"]);function Lo(e){return D.existsSync(e)?JSON.parse(D.readFileSync(e,"utf-8")):null}function Mo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{D.writeFileSync(n,o)}catch(s){try{D.unlinkSync(n)}catch{}throw s}try{D.renameSync(n,e)}catch(s){try{D.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 Fo(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!No.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,i)=>i.t-r.t).map(r=>r.m),s=n.length>0?n:[...o].reverse();for(let r of s){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Po(e){let t=ft.join(e,"conversations.json"),o=Lo(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,i=0;for(let l of Object.keys(o)){let a=o[l];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,r++);let c=Array.isArray(a.messages)?a.messages:[],f=Fo(c,n),g=f==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==f&&i++,a.lastMessageBy=f,a.conversationStatus=g,s++}if(s===0){console.log(" No conversations to recompute.");return}Mo(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} 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 Uo=qo(import.meta.url),Bo=S.dirname(Uo),Vo=S.dirname(S.dirname(Bo));function Ho(e){return e&&(e==="~"?Ae.homedir():e.startsWith("~/")||e.startsWith("~\\")?S.join(Ae.homedir(),e.slice(2)):e)}var O=process.env.DATA_DIR?S.resolve(Ho(process.env.DATA_DIR)):Vo,J=S.join(O,"collected-profiles"),W=S.join(O,"market-research"),A=S.join(O,".schema-version"),mt=[S.join(J,".schema-version"),S.join(W,".schema-version")],q=3,L=[{version:1,module:ve},{version:2,module:ke},{version:3,module:Ce}];(function(){L.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of L){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=L.length?L[L.length-1].version:0;if(o!==q)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${q}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<L.length;n++){let s=n+1;if(L[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${L[n].version}`)}})();function yt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
14
+ `)}`;try{await ht.addMessage(i,l)}catch(m){console.error(`[runReport] Failed to post end-of-session message: ${m.message}`)}}var _o=Eo(import.meta.url),Io=U.dirname(U.dirname(_o)),xe=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"collected-profiles"):U.join(Io,"collected-profiles"),Ae=U.join(xe,"run-log.json");function To(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";j.writeFileSync(n,o);for(let s=0;s<3;s++)try{j.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function yt(){try{if(!j.existsSync(Ae))return{runs:[]};let e=JSON.parse(j.readFileSync(Ae,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function wt(e){j.existsSync(xe)||j.mkdirSync(xe,{recursive:!0});try{To(Ae,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function bt(e,t="default"){let o=yt();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.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(i=>new Date(i.timestamp).getTime()>r),wt(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 i=yt(),u=i.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=o,u.error=n,s=u.duration;else{let l=i.runs.find(m=>m.script===e.script&&m.status==="running"&&m.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=n,s=l.duration)}wt(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";gt({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}import"dotenv/config";import*as d from"fs";import*as Oe from"os";import*as k from"path";import{fileURLToPath as Yo}from"url";var Te={};fe(Te,{NAME:()=>Ro,VERSION:()=>Do,up:()=>No});import*as O from"fs";import*as pe from"path";var Do=1,Ro="normalize-jobs-and-questions",jo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Oo=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 No(e,t){let o=pe.join(e,"jobs.json"),n=pe.join(t,"scouted-jobs.json"),s=pe.join(e,"application-questions.json"),r=_e(o)||{},i=_e(n)||{},u=0,l=[];for(let a of Object.keys(r)){if(!i[a])continue;let y=i[a],c=r[a];for(let f of jo)y[f]!=null&&c[f]==null&&(c[f]=y[f]);l.push(a),u++}u>0?(Ie(o,r),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let m=_e(s);if(m&&Array.isArray(m.applications)){let a={},y=0;for(let c of m.applications){let f=c.jobId||"unknown";a[f]||(a[f]={applications:[]});let C=(c.questions||[]).map(S=>{let E={type:S.type||"input",question:S.question||"",answer:S.answer||""};return S.options&&(S.options.length<=Oo?E.options=S.options:(E.optionsOmitted=!0,y++)),S.page&&(E.page=S.page),S.wasPreFilled&&(E.wasPreFilled=!0),S.wasRetry&&(E.wasRetry=!0),E});a[f].applications.push({applicationId:c.applicationId,date:c.date,result:c.result||"submitted",formPages:c.formPages||null,duration:c.duration||null,retries:c.retries||0,failedField:c.failedField||null,questionCount:c.questionCount||C.length,questions:C})}Ie(s,a),console.log(` Phase 2: Rekeyed ${m.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),y>0&&console.log(` Phase 2: Stripped bloated options from ${y} questions`)}else m&&!m.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let a of l)delete i[a];Ie(n,i),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var De={};fe(De,{NAME:()=>Mo,VERSION:()=>Lo,up:()=>qo});import*as N from"fs";import*as St from"path";var Lo=2,Mo="reset-unread-flags";function Fo(e){return N.existsSync(e)?JSON.parse(N.readFileSync(e,"utf-8")):null}function Po(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}}async function qo(e){let t=St.join(e,"conversations.json"),o=Fo(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}Po(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Re={};fe(Re,{NAME:()=>Bo,VERSION:()=>Uo,up:()=>Go});import*as L from"fs";import*as vt from"path";var Uo=3,Bo="recompute-last-message-by",Vo=new Set(["draft","confirmed","rejected","needs_review"]);function Ho(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function Jo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{L.writeFileSync(n,o)}catch(s){try{L.unlinkSync(n)}catch{}throw s}try{L.renameSync(n,e)}catch(s){try{L.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 Wo(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!Vo.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,i)=>i.t-r.t).map(r=>r.m),s=n.length>0?n:[...o].reverse();for(let r of s){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Go(e){let t=vt.join(e,"conversations.json"),o=Ho(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,i=0;for(let u of Object.keys(o)){let l=o[u];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,r++);let m=Array.isArray(l.messages)?l.messages:[],a=Wo(m,n),y=a==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==a&&i++,l.lastMessageBy=a,l.conversationStatus=y,s++}if(s===0){console.log(" No conversations to recompute.");return}Jo(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} 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 zo=Yo(import.meta.url),Ko=k.dirname(zo),Qo=k.dirname(k.dirname(Ko));function Zo(e){return e&&(e==="~"?Oe.homedir():e.startsWith("~/")||e.startsWith("~\\")?k.join(Oe.homedir(),e.slice(2)):e)}var M=process.env.DATA_DIR?k.resolve(Zo(process.env.DATA_DIR)):Qo,Y=k.join(M,"collected-profiles"),z=k.join(M,"market-research"),I=k.join(M,".schema-version"),kt=[k.join(Y,".schema-version"),k.join(z,".schema-version")],B=3,P=[{version:1,module:Te},{version:2,module:De},{version:3,module:Re}];(function(){P.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of P){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=P.length?P[P.length-1].version:0;if(o!==B)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${B}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<P.length;n++){let s=n+1;if(P[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${P[n].version}`)}})();function At(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
12
15
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
13
- `),process.exit(1));try{u.mkdirSync(O,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
14
- [FATAL] Cannot create DATA_DIR (${O}): ${t.message}`),console.error(` Fix the path or permissions and try again.
15
- `),process.exit(1))}let e;try{e=u.statSync(O)}catch(t){console.error(`
16
- [FATAL] DATA_DIR (${O}) is not accessible: ${t.message}
16
+ `),process.exit(1));try{d.mkdirSync(M,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
17
+ [FATAL] Cannot create DATA_DIR (${M}): ${t.message}`),console.error(` Fix the path or permissions and try again.
18
+ `),process.exit(1))}let e;try{e=d.statSync(M)}catch(t){console.error(`
19
+ [FATAL] DATA_DIR (${M}) is not accessible: ${t.message}
17
20
  `),process.exit(1)}e.isDirectory()||(console.error(`
18
- [FATAL] DATA_DIR (${O}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
19
- `),process.exit(1));for(let t of[J,W]){let o;try{o=u.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
21
+ [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.
22
+ `),process.exit(1));for(let t of[Y,z]){let o;try{o=d.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
20
23
  [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.
21
- `),process.exit(1))}}var H=S.join(O,".migration-lock");function Jo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return u.writeFileSync(H,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(u.readFileSync(H,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let n=!1;try{process.kill(t.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(r=Date.now()-i)}n&&r<s&&(console.error(`
22
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${H}
24
+ `),process.exit(1))}}var G=k.join(M,".migration-lock");function Xo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return d.writeFileSync(G,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(d.readFileSync(G,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let n=!1;try{process.kill(t.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(r=Date.now()-i)}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: ${G}
23
26
  `),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
24
- `),process.exit(1)),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=H+".tmp";try{return u.writeFileSync(o,e),u.renameSync(o,H),!0}catch(n){try{u.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function Ee(){try{if(JSON.parse(u.readFileSync(H,"utf-8")).pid!==process.pid)return;u.unlinkSync(H)}catch{}}var pt=!1;function Wo(){if(pt)return;pt=!0;let e=()=>{try{Ee()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Go(){if(u.existsSync(A))return;let e=[],t=[];for(let r of mt)if(u.existsSync(r))try{e.push({file:r,schema:re(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
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=G+".tmp";try{return d.writeFileSync(o,e),d.renameSync(o,G),!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(G,"utf-8")).pid!==process.pid)return;d.unlinkSync(G)}catch{}}var Ct=!1;function en(){if(Ct)return;Ct=!0;let e=()=>{try{Ne()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function tn(){if(d.existsSync(I))return;let e=[],t=[];for(let r of kt)if(d.existsSync(r))try{e.push({file:r,schema:he(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
25
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(`
26
29
  Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
27
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(`
28
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.
29
- `),process.exit(1)}let n=e[0].schema,s=A+".tmp";try{u.writeFileSync(s,JSON.stringify(n,null,2)),u.renameSync(s,A)}catch(r){try{u.unlinkSync(s)}catch{}throw r}for(let r of mt)if(u.existsSync(r))try{u.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${A}`)}function Yo(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 re(e){let t=u.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ht(){if(Go(),!u.existsSync(A))return{version:0,migrations:[]};let e;try{e=re(A)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
30
- [FATAL] ${A} is not valid JSON: ${o.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
31
- `),process.exit(1)}let t=Yo(e);return t===null&&(console.error(`
32
- [FATAL] ${A} 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.
33
- `),process.exit(1)),t}function wt(e){try{u.chmodSync(e,384)}catch{}}function zo(e){if(yt(),u.existsSync(A))try{if(u.lstatSync(A).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${A}. 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=A+".tmp";try{u.writeFileSync(t,JSON.stringify(e,null,2)),wt(t),u.renameSync(t,A)}catch(o){try{u.unlinkSync(t)}catch{}throw o}}function gt(e,t){if(!u.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=u.readdirSync(e).filter(l=>{let a=l.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return u.statSync(S.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of n){let a=S.join(e,l),c=S.join(e,l+o);if(u.existsSync(c)){r++;continue}try{St(a,c),s++}catch(f){i.push({file:l,err:f.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${S.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(s>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${S.basename(e)}/ (${o})${l}`)}}var $e=!1;async function bt(){if($e)return;yt(),en();let t=ht().version;if(t===q){$e=!0;return}Wo(),Jo(),process.on("exit",Ee),t>q&&(console.error(`
34
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${q}.`),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.
35
- `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${q}.
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 kt)if(d.existsSync(r))try{d.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${I}`)}function on(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 he(e){let t=d.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function $t(){if(tn(),!d.existsSync(I))return{version:0,migrations:[]};let e;try{e=he(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=on(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 Et(e){try{d.chmodSync(e,384)}catch{}}function nn(e){if(At(),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)),Et(t),d.renameSync(t,I)}catch(o){try{d.unlinkSync(t)}catch{}throw o}}function xt(e,t){if(!d.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=d.readdirSync(e).filter(u=>{let l=u.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return d.statSync(k.join(e,u)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let u of n){let l=k.join(e,u),m=k.join(e,u+o);if(d.existsSync(m)){r++;continue}try{It(l,m),s++}catch(a){i.push({file:u,err:a.message})}}if(i.length>0){let u=new Error(`Failed to back up ${i.length} file(s) in ${k.basename(e)}/: `+i.map(l=>`${l.file} (${l.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(s>0||r>0){let u=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${k.basename(e)}/ (${o})${u}`)}}var je=!1;async function _t(){if(je)return;At(),cn();let t=$t().version;if(t===B){je=!0;return}en(),Xo(),process.on("exit",Ne),t>B&&(console.error(`
37
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${B}.`),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${B}.
36
39
  `),process.exit(1)),console.log(`
37
- \u{1F4E6} Schema migration: v${t} \u2192 v${q}`);let o=tn();if(!o.ok){console.error(`
40
+ \u{1F4E6} Schema migration: v${t} \u2192 v${B}`);let o=un();if(!o.ok){console.error(`
38
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(`
39
42
  Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
40
- `),process.exit(1)}let n=L.filter(s=>s.version>t);for(let s of n){console.log(`
41
- Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{gt(J,s.version),gt(W,s.version)}catch(a){console.error(`
42
- [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.
43
- `),process.exit(1)}let l=s.module;try{await l.up(J,W)}catch(a){console.error(`
44
- [FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let c=on(i);c.ok?(console.error(` \u2713 Auto-rollback restored ${c.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
45
- `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${c.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
46
- `))}catch(c){console.error(` [!] Auto-rollback CRASHED while restoring: ${c.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
47
- `)}process.exit(1)}try{let a=new Date().toISOString(),c={version:s.version,name:l.NAME||r,appliedAt:a},f=ht();f.version=s.version,f.migratedAt=a,f.migrations=f.migrations||[],f.migrations.push(c),zo(f)}catch(a){console.error(`
48
- [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.
49
- `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{Je()}catch{}try{Ze()}catch{}$e=!0,Ee(),console.log(`
50
- \u2713 Schema is now at v${q}
51
- `)}var Ko=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Qo(e){let t=e.toLowerCase();return Ko.some(o=>o.test(t))}var Zo=6e4;function Xo(){let e=Date.now(),t=[];for(let o of[O,J,W]){if(!u.existsSync(o))continue;let n;try{n=u.readdirSync(o)}catch{continue}for(let s of n){if(!Qo(s))continue;let r=S.join(o,s);try{let i=u.statSync(r);if(!i.isFile()||e-i.mtimeMs<Zo)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function en({verbose:e=!1}={}){let t=Xo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let n of t)try{u.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 tn(){let e=[];for(let t of[J,W]){if(!u.existsSync(t))continue;let o=u.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{re(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 on(e){let t=[],o=[];for(let r of[J,W]){if(!u.existsSync(r))continue;let i=u.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let a=S.join(r,l),c=l.slice(0,-e.length),f=S.join(r,c);try{c.toLowerCase().endsWith(".json")?re(a):u.accessSync(a,u.constants.R_OK),t.push({backupPath:a,originalPath:f,fileName:l,dir:r})}catch(g){o.push(`${S.basename(r)}/${l}: ${g.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let n=0,s=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:a}of t)try{St(r,i),n++}catch(c){s.push(`${S.basename(a)}/${l}: ${c.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function St(e,t){let o=t+".tmp";try{u.copyFileSync(e,o),wt(o)}catch(n){try{u.unlinkSync(o)}catch{}throw n}try{u.renameSync(o,t)}catch(n){try{u.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 bt();var ee=process.argv.slice(2),ie=ee.find(e=>e.startsWith("--source="))?.split("=")[1]||"scouted",xe=parseInt(ee.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),G=parseInt(ee.find(e=>e.startsWith("--revisit="))?.split("=")[1]||"0"),nn=ee.includes("--list"),sn=ee.includes("--verbose");function rn(){let e=tt();console.log(`
52
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PROFILE VISIT STATS"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Unique profiles visited: ${e.totalVisited}`),console.log(` Today: ${e.todayVisited}`),console.log(` Discovered recruiters: ${e.totalRecruiters} (potential visits)`);let t=pe();if(console.log(` Unconnected recruiters: ${t.length}`),G>0){let o=he(G);console.log(` Revisit (>${G}d ago): ${o.length}`)}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
53
- `)}async function ln(){if(console.log(`
43
+ `),process.exit(1)}let n=P.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")}`,i=`.pre-${r}.backup`;try{xt(Y,s.version),xt(z,s.version)}catch(l){console.error(`
45
+ [FATAL] Pre-migration backup failed for ${r}: ${l.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 u=s.module;try{await u.up(Y,z)}catch(l){console.error(`
47
+ [FATAL] Migration ${r} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let m=dn(i);m.ok?(console.error(` \u2713 Auto-rollback restored ${m.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
48
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${m.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
49
+ `))}catch(m){console.error(` [!] Auto-rollback CRASHED while restoring: ${m.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
50
+ `)}process.exit(1)}try{let l=new Date().toISOString(),m={version:s.version,name:u.NAME||r,appliedAt:l},a=$t();a.version=s.version,a.migratedAt=l,a.migrations=a.migrations||[],a.migrations.push(m),nn(a)}catch(l){console.error(`
51
+ [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${l.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{Ze()}catch{}try{lt()}catch{}je=!0,Ne(),console.log(`
53
+ \u2713 Schema is now at v${B}
54
+ `)}var sn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function rn(e){let t=e.toLowerCase();return sn.some(o=>o.test(t))}var ln=6e4;function an(){let e=Date.now(),t=[];for(let o of[M,Y,z]){if(!d.existsSync(o))continue;let n;try{n=d.readdirSync(o)}catch{continue}for(let s of n){if(!rn(s))continue;let r=k.join(o,s);try{let i=d.statSync(r);if(!i.isFile()||e-i.mtimeMs<ln)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function cn({verbose:e=!1}={}){let t=an();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let n of t)try{d.unlinkSync(n.fullPath),o++,e&&console.log(` Removed orphan: ${k.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 un(){let e=[];for(let t of[Y,z]){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=k.join(t,n);try{he(s)}catch(r){e.push({dir:k.basename(t),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function dn(e){let t=[],o=[];for(let r of[Y,z]){if(!d.existsSync(r))continue;let i=d.readdirSync(r).filter(u=>u.endsWith(e));for(let u of i){let l=k.join(r,u),m=u.slice(0,-e.length),a=k.join(r,m);try{m.toLowerCase().endsWith(".json")?he(l):d.accessSync(l,d.constants.R_OK),t.push({backupPath:l,originalPath:a,fileName:u,dir:r})}catch(y){o.push(`${k.basename(r)}/${u}: ${y.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let n=0,s=[];for(let{backupPath:r,originalPath:i,fileName:u,dir:l}of t)try{It(r,i),n++}catch(m){s.push(`${k.basename(l)}/${u}: ${m.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function It(e,t){let o=t+".tmp";try{d.copyFileSync(e,o),Et(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 _t();var ie=process.argv.slice(2),ge=ie.find(e=>e.startsWith("--source="))?.split("=")[1]||"scouted",Le=parseInt(ie.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),K=parseInt(ie.find(e=>e.startsWith("--revisit="))?.split("=")[1]||"0"),fn=ie.includes("--list"),mn=ie.includes("--verbose");function pn(){let e=ut();console.log(`
55
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 VISIT STATS"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Unique profiles visited: ${e.totalVisited}`),console.log(` Today: ${e.todayVisited}`),console.log(` Discovered recruiters: ${e.totalRecruiters} (potential visits)`);let t=Ce();if(console.log(` Unconnected recruiters: ${t.length}`),K>0){let o=$e(K);console.log(` Revisit (>${K}d ago): ${o.length}`)}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
56
+ `)}async function hn(){if(console.log(`
54
57
  LinkedIn Profile Visitor
55
- `),nn){rn();return}let e=[],t="";if(G>0?(e=he(G),t=`revisit (>${G} days)`):ie==="people"?(e=pe(),t="unconnected recruiters (people.json)"):ie==="scouted"||ie==="discovered"?(e=st(),t="discovered recruiters (market-research)"):(e=nt({limit:xe}),t="smart (new \u2192 active \u2192 unconnected \u2192 revisit)"),console.log(` Source: ${t}`),console.log(` Candidates: ${e.length}`),console.log(` Max visits: ${xe}
58
+ `),fn){pn();return}let e=[],t="";if(K>0?(e=$e(K),t=`revisit (>${K} days)`):ge==="people"?(e=Ce(),t="unconnected recruiters (people.json)"):ge==="scouted"||ge==="discovered"?(e=mt(),t="discovered recruiters (market-research)"):(e=ft({limit:Le}),t="smart (new \u2192 active \u2192 unconnected \u2192 revisit)"),console.log(` Source: ${t}`),console.log(` Candidates: ${e.length}`),console.log(` Max visits: ${Le}
56
59
  `),e.length===0){console.log(` No profiles to visit. Run npm run scout first.
57
- `);return}let o=ut("visit",ie),{browser:n,page:s}=await Be();try{let r=await ot(s,e,{maxVisits:xe,verbose:sn,skipRecentDays:G>0?0:7});console.log(`
60
+ `);return}let o=bt("visit",ge),{browser:n,page:s}=await ze();try{let r=await dt(s,e,{maxVisits:Le,verbose:mn,skipRecentDays:K>0?0:7});console.log(`
58
61
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" Visit 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: ${r.skipped} (visited recently)`),console.log(` Errors: ${r.errors}`),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
59
- `),we(o,"success",r)}catch(r){console.error(`
60
- Error:`,r.message),we(o,"error",null,r.message)}finally{await n.close().catch(()=>{})}}ln().catch(e=>{console.error("Visit failed:",e),process.exit(1)});
62
+ `),Ee(o,"success",r)}catch(r){console.error(`
63
+ Error:`,r.message),Ee(o,"error",null,r.message)}finally{await n.close().catch(()=>{})}}hn().catch(e=>{console.error("Visit failed:",e),process.exit(1)});
package/ilml-plugin.json CHANGED
@@ -1,37 +1,66 @@
1
1
  {
2
2
  "name": "linkedin",
3
- "version": "1.11.7",
3
+ "version": "1.12.0",
4
4
  "description": "Reference ilml plugin: keep a local mirror of your LinkedIn data with AI-assisted workflows",
5
5
  "commands": {
6
- "apply": { "run": "node dist/run.mjs" },
7
- "sync": { "run": "node dist/syncAll.mjs" },
8
- "sync-all": { "run": "node dist/syncAll.mjs" },
9
- "today": { "run": "node dist/syncAll.mjs --today" },
10
- "enrich": { "run": "node dist/syncAll.mjs --enrich" },
11
- "report": { "run": "node dist/syncAll.mjs --report" },
12
- "scout": { "run": "node dist/scout.mjs" },
13
- "messages": { "run": "node dist/messageBot.mjs" },
14
- "funnel": { "run": "node dist/funnelRunner.mjs" },
15
- "visit": { "run": "node dist/visit.mjs" },
16
- "viewers": { "run": "node dist/viewers.mjs" },
17
- "apply-queue": { "run": "node dist/applyQueue.mjs" },
18
- "warm-scan": { "run": "node dist/warmScan.mjs" },
19
- "daily": { "run": "node dist/daily.mjs" },
20
- "profile-history": { "run": "node dist/profileHistory.mjs" },
21
- "verify-about": { "run": "node dist/verifyAbout.mjs" },
22
- "login": { "run": "node dist/src/saveLoginState.mjs" },
23
- "migrate-status": { "run": "node dist/migrationCli.mjs status" },
24
- "data-cleanup": { "run": "node dist/migrationCli.mjs data-cleanup" },
25
- "rollback-data": { "run": "node dist/migrationCli.mjs rollback-data" }
6
+ "help": { "run": "node dist/help.mjs", "description": "List all commands with descriptions; or `help <cmd>` for detailed info on one command (usage, flags, ban-risk, when-to-use). Reads ilml-plugin.json directly." },
7
+ "apply": { "run": "node dist/run.mjs", "description": "Auto-apply to LinkedIn Easy Apply jobs from LINKEDIN_SEARCH_URL. Stops after MAX_APPLY_FOR_RUN. Browser flow.", "banRisk": "Medium. Each apply submission is a purposeful action; LinkedIn doesn't flag this as long as you respect MAX_APPLY_FOR_RUN (default 50/day)." },
8
+ "sync": { "run": "node dist/syncAll.mjs", "description": "Alias for sync-all." },
9
+ "sync-all": { "run": "node dist/syncAll.mjs", "description": "Pull LinkedIn inbox into local DB + graph. Preserves unread badges by default. Flags: --full (re-scan), --report (stats-only no browser), --read-unread (vacuums unread threads — loses badges)." },
10
+ "today": { "run": "node dist/syncAll.mjs --today", "description": "No-browser daily action plan: who to reply to, what to do, prioritised. Reads already-synced data." },
11
+ "enrich": { "run": "node dist/syncAll.mjs --enrich", "description": "Re-classify every conversation (recruiter / HM / founder / etc.) and rebuild summaries, priorities, suggested actions. Offline, no browser." },
12
+ "report": { "run": "node dist/syncAll.mjs --report", "description": "Print the summary of the latest session. Offline." },
13
+ "scout": { "run": "node dist/scout.mjs", "description": "Scan jobs from LINKEDIN_SCOUT_URLS and score them — WITHOUT applying. Builds queue for apply-queue. Browser flow." },
14
+ "messages": { "run": "node dist/messageBot.mjs", "description": "Batch messaging: draft → review → push. Nothing sends without explicit approval. Common flags: --review-drafts (interactive), --push-drafts (send approved)." },
15
+ "funnel": { "run": "node dist/funnelRunner.mjs", "description": "Recruiter / founder / investor connection-request queue. Browser flow.", "banRisk": "Medium. Each connection request is purposeful. Capped by FUNNEL_MAX_CONNECTIONS / weekly quota." },
16
+ "visit": { "run": "node dist/visit.mjs", "description": "Visit recruiter / target profiles so they see you in 'who viewed your profile'. Browser flow.", "banRisk": "Medium. Visits are purposeful (show-up signal). Up to 50/session by default." },
17
+ "viewers": { "run": "node dist/viewers.mjs", "description": "Pull the 'who viewed your profile' list from LinkedIn analytics. Browser flow." },
18
+ "apply-queue": { "run": "node dist/applyQueue.mjs", "description": "Apply to top-scored jobs from the latest scout run. Browser flow." },
19
+ "warm-scan": { "run": "node dist/warmScan.mjs", "description": "Find 1st-degree connections at target companies. Offline, no browser. Flags: --companies=\"X,Y\" or --group=<named-group>." },
20
+ "daily": { "run": "node dist/daily.mjs", "description": "Full pipeline: sync-all → apply → scout → funnel → visit → viewers → report. Browser flow." },
21
+ "profile-history": { "run": "node dist/profileHistory.mjs", "description": "Inspect saved snapshots of profile changes over time. Offline." },
22
+ "verify-about": { "run": "node dist/verifyAbout.mjs", "description": "Smoke test for the About-field selector — read-only diagnostic (visits own profile, prints what was scraped). Doesn't write to disk." },
23
+ "enrich-profile": {
24
+ "run": "node dist/enrichProfile.mjs",
25
+ "description": "Visit ONE LinkedIn profile by URL and save what we learn to people.json (the contacts DB). Self-profile is detected via MY_LINKEDIN_URL / LINKEDIN_NAME and printed to stdout instead of saved.",
26
+ "usage": "ilml linkedin enrich-profile <profile-url> [--with-experience] [--help]",
27
+ "flags": {
28
+ "<profile-url>": "Required. Full LinkedIn profile URL, e.g. https://www.linkedin.com/in/<slug>/",
29
+ "--with-experience": "Opt-in. Triggers a second navigation to /details/experience/ and adds a structured experience[] array (title/company/dates/location/description/skills per role). Costs 2 page loads instead of 1. Recommended for on-demand single-person enrichment.",
30
+ "--help": "Print this help and exit."
31
+ },
32
+ "banRisk": "Low. One profile per invocation = normal human profile-view behavior. With --with-experience the count is 2 loads per profile (still human-like 'click show all' pattern). Don't batch — this script intentionally takes a single URL.",
33
+ "useWhen": "You need full profile data on one specific person (audit own profile, deep-dive on a contact before reaching out, verify a recruiter)."
34
+ },
35
+ "enrich-profiles": {
36
+ "run": "node dist/enrichProfiles.mjs",
37
+ "description": "Batch-visit a queue of contacts in people.json that are missing About text, fill in basic fields. Optional --with-experience adds structured experience[] per visit. Capped at 10 visits/session by default — ban-risky pattern.",
38
+ "usage": "ilml linkedin enrich-profiles [--max=N] [--connections] [--match-title=regex] [--with-experience] [--list]",
39
+ "flags": {
40
+ "--max=N": "Max visits this session (default 10). Higher = more ban-risk.",
41
+ "--connections": "Filter queue to 1st-degree connections only (lower ban-risk than visiting strangers).",
42
+ "--match-title=re": "Regex to filter queue by current title, e.g. 'recruiter|sourcer' or 'founder|ceo'.",
43
+ "--with-experience": "Opt-in. Each visit does an extra /details/experience/ hop — DOUBLES the page-view footprint per profile. Extra ban-risk warning is printed.",
44
+ "--list": "Show queue stats only, no browser. Safe.",
45
+ "--verbose": "Per-visit logging."
46
+ },
47
+ "banRisk": "HIGH. Visits profiles without follow-up action (no message, no connect, no like) — LinkedIn has flagged accounts for exactly this pattern. Default cap 10/session, recommended run frequency at-most-once-per-day. --with-experience doubles the per-profile load count and compounds the risk.",
48
+ "useWhen": "You have many contacts in people.json with missing About text and want to backfill in a controlled batch. Prefer 'visit' or 'funnel' flows which visit profiles WITH a purpose (lower risk) when possible."
49
+ },
50
+ "login": { "run": "node dist/src/saveLoginState.mjs", "description": "Open a browser, let you log in to LinkedIn manually, then save the cookies for all other commands. Run when sync/apply errors with 'session expired'." },
51
+ "migrate-status": { "run": "node dist/migrationCli.mjs status", "description": "Show schema migration status of the local DB. Operational. Offline." },
52
+ "data-cleanup": { "run": "node dist/migrationCli.mjs data-cleanup", "description": "Clean up the local DB (de-duplicate, prune stale records). Operational. Offline." },
53
+ "rollback-data": { "run": "node dist/migrationCli.mjs rollback-data", "description": "Roll back the last schema migration. Use only if a migration broke something." }
26
54
  },
27
55
  "config": {
28
56
  "sections": [
29
57
  {
30
58
  "title": "LinkedIn account",
31
59
  "fields": [
32
- { "key": "LINKEDIN_NAME", "label": "Your full name on LinkedIn", "type": "text", "required": true, "hint": "Used to detect which messages were sent by you" },
33
- { "key": "LINKEDIN_LOGIN", "label": "LinkedIn email", "type": "text", "required": false, "hint": "Optional — auto-fill during login only" },
34
- { "key": "LINKEDIN_PASS", "label": "LinkedIn password", "type": "secret", "required": false, "hint": "Optional — auto-fill during login only. Never sent anywhere; stored locally (or wallet-encrypted node in graph)" }
60
+ { "key": "LINKEDIN_NAME", "label": "Your full name on LinkedIn", "type": "text", "required": true, "hint": "Used to detect which messages were sent by you, and to recognize your own profile during enrichment so it isn't accidentally saved to the contacts DB" },
61
+ { "key": "MY_LINKEDIN_URL", "label": "Your LinkedIn profile URL", "type": "url", "required": false, "hint": "Recommended for users of `enrich-profile`. Used to recognize your own profile by URL (more robust than name-match if someone in your network has the same name). Example: https://www.linkedin.com/in/<your-slug>" },
62
+ { "key": "LINKEDIN_LOGIN", "label": "LinkedIn email", "type": "text", "required": false, "hint": "Optional — auto-fill during login only" },
63
+ { "key": "LINKEDIN_PASS", "label": "LinkedIn password", "type": "secret", "required": false, "hint": "Optional — auto-fill during login only. Never sent anywhere; stored locally (or wallet-encrypted node in graph)" }
35
64
  ]
36
65
  },
37
66
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ilml-plugin-linkedin",
3
- "version": "1.11.7",
3
+ "version": "1.12.0",
4
4
  "description": "Reference ilml plugin: keep a local mirror of your LinkedIn data and run AI-assisted workflows under your direction.",
5
5
  "type": "module",
6
6
  "files": [
@@ -28,6 +28,8 @@
28
28
  "visit:list": "node visit.mjs --list",
29
29
  "enrich-profiles": "node enrichProfiles.mjs",
30
30
  "enrich-profiles:list": "node enrichProfiles.mjs --list",
31
+ "enrich-profile": "node enrichProfile.mjs",
32
+ "help": "node help.mjs",
31
33
  "verify-about": "node verifyAbout.mjs",
32
34
  "profile-history": "node profileHistory.mjs",
33
35
  "viewers": "node viewers.mjs --save",