ilml-plugin-linkedin 1.19.1 → 1.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- var kn=Object.defineProperty;var ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{for(var n in t)kn(e,n,{get:t[n],enumerable:!0})};async function S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ce(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",l=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(l||i||c){let s=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:r.substring(0,80)};let u=o.querySelectorAll("button");for(let a of u){let d=a.innerText?.trim().toLowerCase()||"",f=a.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return a.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Te=ht(()=>{});var Ft={};ke(Ft,{extractCertificationsFromDetails:()=>Xn,extractEducationFromDetails:()=>Qn,extractExperienceFromDetails:()=>Kn,extractFeaturedFromDetails:()=>zn,extractRecommendationsFromDetails:()=>eo,extractSkillsFromDetails:()=>Zn});async function Kn(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let l=0;l<5;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(1e3);let r=0;for(;r<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});)r++,await S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let l=document.querySelector("main");if(!l)return[];function i(a){let d=[];for(let f of a.querySelectorAll("div")){let m=Array.from(f.children).filter(y=>y.tagName==="DIV");if(m.length<3)continue;let g=m.filter(y=>(y.textContent||"").trim().length>50);g.length<3||(f.textContent||"").length<500||d.push({el:f,count:g.length,totalText:(f.textContent||"").length})}return d.sort((f,m)=>m.count-f.count||f.totalText-m.totalText),d[0]?.el}let c=i(l);if(!c)return[];let s=Array.from(c.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function u(a){let d=a[0]||null,f=null,m=null;if(a[1]){let C=a[1].split("\xB7").map(F=>F.trim());f=C[0]||null,C[1]&&(m=C[1])}let g=a.findIndex(C=>/(\d{4}|present)/i.test(C)&&/(-|–|—)/i.test(C)&&C.length<80),y=null,p=null;if(g>=0){let C=a[g].split("\xB7").map(F=>F.trim());y=C[0]||null,C[1]&&(p=C[1])}let h=null,k=-1;if(g>=0&&a[g+1]){let C=a[g+1],F=/^[>*\-•]|^&gt;/.test(C),Z=/https?:\/\//.test(C),G=/\d{4}/.test(C),L=/,/.test(C)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(C);!F&&!Z&&!G&&C.length<100&&L&&(h=C,k=g+1)}let x=null,b=-1,I=a[a.length-1];if(I&&/and\s+\+\d+\s+skills?$/i.test(I)){b=a.length-1;let C=I.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);C&&(x={listed:C[1].split(",").map(F=>F.trim()),additional:parseInt(C[2],10)})}let M=new Set([0,1,g,k,b].filter(C=>C>=0)),O=a.filter((C,F)=>!M.has(F)),T=O.length>0?O.join(`
1
+ var kn=Object.defineProperty;var ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{for(var n in t)kn(e,n,{get:t[n],enumerable:!0})};async function b(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ce(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",l=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(l||i||c){let s=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:r.substring(0,80)};let u=o.querySelectorAll("button");for(let a of u){let d=a.innerText?.trim().toLowerCase()||"",f=a.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return a.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Te=ht(()=>{});var Ft={};ke(Ft,{extractCertificationsFromDetails:()=>Xn,extractEducationFromDetails:()=>Qn,extractExperienceFromDetails:()=>Kn,extractFeaturedFromDetails:()=>zn,extractRecommendationsFromDetails:()=>eo,extractSkillsFromDetails:()=>Zn});async function Kn(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let l=0;l<5;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(900);await b(1e3);let r=0;for(;r<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});)r++,await b(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(700);return await e.evaluate(()=>{let l=document.querySelector("main");if(!l)return[];function i(a){let d=[];for(let f of a.querySelectorAll("div")){let m=Array.from(f.children).filter(y=>y.tagName==="DIV");if(m.length<3)continue;let g=m.filter(y=>(y.textContent||"").trim().length>50);g.length<3||(f.textContent||"").length<500||d.push({el:f,count:g.length,totalText:(f.textContent||"").length})}return d.sort((f,m)=>m.count-f.count||f.totalText-m.totalText),d[0]?.el}let c=i(l);if(!c)return[];let s=Array.from(c.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function u(a){let d=a[0]||null,f=null,m=null;if(a[1]){let C=a[1].split("\xB7").map(F=>F.trim());f=C[0]||null,C[1]&&(m=C[1])}let g=a.findIndex(C=>/(\d{4}|present)/i.test(C)&&/(-|–|—)/i.test(C)&&C.length<80),y=null,h=null;if(g>=0){let C=a[g].split("\xB7").map(F=>F.trim());y=C[0]||null,C[1]&&(h=C[1])}let p=null,v=-1;if(g>=0&&a[g+1]){let C=a[g+1],F=/^[>*\-•]|^&gt;/.test(C),Z=/https?:\/\//.test(C),G=/\d{4}/.test(C),L=/,/.test(C)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(C);!F&&!Z&&!G&&C.length<100&&L&&(p=C,v=g+1)}let $=null,S=-1,A=a[a.length-1];if(A&&/and\s+\+\d+\s+skills?$/i.test(A)){S=a.length-1;let C=A.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);C&&($={listed:C[1].split(",").map(F=>F.trim()),additional:parseInt(C[2],10)})}let M=new Set([0,1,g,v,S].filter(C=>C>=0)),O=a.filter((C,F)=>!M.has(F)),T=O.length>0?O.join(`
2
2
 
3
- `):null;return{title:d,company:f,employmentType:m,dates:y,duration:p,location:h,description:T,skills:x,_raw:a}}return s.map(a=>{let f=(a.innerText||"").trim().split(`
4
- `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return u(f)}).filter(a=>a.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Ae(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let i=0;i<4;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);await S(800);let l=0;for(;l<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)l++,await S(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(600)}async function Ie(e,t,n,o){try{return await o()}catch(r){let l=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(l))throw r;return/not available on profile/i.test(l)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${l.slice(0,120)}`),[])}}async function zn(e,t){return Ie(t,"featured","extractFeaturedFromDetails",async()=>(await Ae(e,t,"featured"),await e.evaluate(`(() => {
5
- ${Ee}
3
+ `):null;return{title:d,company:f,employmentType:m,dates:y,duration:h,location:p,description:T,skills:$,_raw:a}}return s.map(a=>{let f=(a.innerText||"").trim().split(`
4
+ `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return u(f)}).filter(a=>a.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Ee(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let i=0;i<4;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(700);await b(800);let l=0;for(;l<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)l++,await b(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(600)}async function Ie(e,t,n,o){try{return await o()}catch(r){let l=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(l))throw r;return/not available on profile/i.test(l)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${l.slice(0,120)}`),[])}}async function zn(e,t){return Ie(t,"featured","extractFeaturedFromDetails",async()=>(await Ee(e,t,"featured"),await e.evaluate(`(() => {
5
+ ${Ae}
6
6
 
7
7
  const main = document.querySelector('main');
8
8
  if (!main) return [];
@@ -42,8 +42,8 @@ var kn=Object.defineProperty;var ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{
42
42
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
43
43
  return true;
44
44
  });
45
- })()`)))}async function Qn(e,t){return Ie(t,"education","extractEducationFromDetails",async()=>(await Ae(e,t,"education"),await e.evaluate(`(() => {
46
- ${Ee}
45
+ })()`)))}async function Qn(e,t){return Ie(t,"education","extractEducationFromDetails",async()=>(await Ee(e,t,"education"),await e.evaluate(`(() => {
46
+ ${Ae}
47
47
 
48
48
  const main = document.querySelector('main');
49
49
  if (!main) return [];
@@ -79,8 +79,8 @@ var kn=Object.defineProperty;var ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{
79
79
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
80
80
  return true;
81
81
  });
82
- })()`)))}async function Zn(e,t){return Ie(t,"skills","extractSkillsFromDetails",async()=>(await Ae(e,t,"skills"),await e.evaluate(`(() => {
83
- ${Ee}
82
+ })()`)))}async function Zn(e,t){return Ie(t,"skills","extractSkillsFromDetails",async()=>(await Ee(e,t,"skills"),await e.evaluate(`(() => {
83
+ ${Ae}
84
84
 
85
85
  const main = document.querySelector('main');
86
86
  if (!main) return [];
@@ -111,8 +111,8 @@ var kn=Object.defineProperty;var ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{
111
111
  skills.push({ name, endorsements, _raw: lines });
112
112
  }
113
113
  return skills;
114
- })()`)))}async function Xn(e,t){return Ie(t,"certifications","extractCertificationsFromDetails",async()=>(await Ae(e,t,"certifications"),await e.evaluate(`(() => {
115
- ${Ee}
114
+ })()`)))}async function Xn(e,t){return Ie(t,"certifications","extractCertificationsFromDetails",async()=>(await Ee(e,t,"certifications"),await e.evaluate(`(() => {
115
+ ${Ae}
116
116
 
117
117
  const main = document.querySelector('main');
118
118
  if (!main) return [];
@@ -136,8 +136,8 @@ var kn=Object.defineProperty;var ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{
136
136
 
137
137
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
138
138
  }).filter(e => e.name);
139
- })()`)))}async function eo(e,t){return Ie(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Ae(e,t,"recommendations"),await e.evaluate(`(() => {
140
- ${Ee}
139
+ })()`)))}async function eo(e,t){return Ie(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Ee(e,t,"recommendations"),await e.evaluate(`(() => {
140
+ ${Ae}
141
141
 
142
142
  const main = document.querySelector('main');
143
143
  if (!main) return [];
@@ -172,7 +172,7 @@ var kn=Object.defineProperty;var ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{
172
172
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
173
173
  return true;
174
174
  });
175
- })()`)))}var Ee,Lt=ht(()=>{Te();Ee=`
175
+ })()`)))}var Ae,Lt=ht(()=>{Te();Ae=`
176
176
  function findEntryContainer(root) {
177
177
  const candidates = [];
178
178
  for (const div of root.querySelectorAll('div')) {
@@ -239,17 +239,17 @@ function findEntryContainer(root) {
239
239
  [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.
240
240
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
241
241
  `),console.error(` Or add ILML_TOKEN=... to .env
242
- `),process.exit(1));var yt=Cn({token:gt});function An(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function En({scriptName:e,mode:t,status:n,error:o,duration:r}){let l=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${An(r)}`:"",s=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${l} ${e}${u} \u2014 ${s} \u2014 ${i}${c}`}async function wt({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:l}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let s=`**${En({scriptName:e,mode:t,status:n,error:r,duration:l})}**
242
+ `),process.exit(1));var yt=Cn({token:gt});function En(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function An({scriptName:e,mode:t,status:n,error:o,duration:r}){let l=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${En(r)}`:"",s=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${l} ${e}${u} \u2014 ${s} \u2014 ${i}${c}`}async function wt({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:l}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let s=`**${An({scriptName:e,mode:t,status:n,error:r,duration:l})}**
243
243
 
244
244
  ${o.join(`
245
- `)}`;try{await yt.addMessage(i,s)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Dn=In(import.meta.url),_n=ie.dirname(ie.dirname(Dn)),Ue=process.env.DATA_DIR?ie.resolve(process.env.DATA_DIR,"collected-profiles"):ie.join(_n,"collected-profiles"),Be=ie.join(Ue,"run-log.json");function Rn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";J.writeFileSync(o,n);for(let r=0;r<3;r++)try{J.renameSync(o,e);return}catch(l){if(r<2&&(l.code==="EPERM"||l.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw l}}function St(){try{if(!J.existsSync(Be))return{runs:[]};let e=JSON.parse(J.readFileSync(Be,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function bt(e){J.existsSync(Ue)||J.mkdirSync(Ue,{recursive:!0});try{Rn(Be,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function vt(e,t="default"){let n=St();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let l=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>l),bt(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Je(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=St(),c=i.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let s=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=o,r=s.duration)}bt(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let l=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(l&&l.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";wt({scriptName:e.script,mode:e.mode,status:i,summaryLines:l,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Te();Te();import{getPluginConfig as On}from"@ilivemylife/graph-sdk";var Tn=await On();for(let[e,t]of Object.entries(Tn))process.env[e]===void 0&&(process.env[e]=t);var xr=process.env.LINKEDIN_NAME,ue=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Ar=Object.freeze(new Set([ue.DRAFT,ue.CONFIRMED,ue.NEEDS_REVIEW])),Er=Object.freeze(new Set([ue.DRAFT,ue.CONFIRMED,ue.REJECTED,ue.NEEDS_REVIEW]));import"dotenv/config";import*as R from"fs";import*as j from"path";import{fileURLToPath as Nn}from"url";var jn=Nn(import.meta.url),Fn=j.dirname(j.dirname(jn)),ee=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"collected-profiles"):j.join(Fn,"collected-profiles"),Ve=j.join(ee,"people.json"),Or=j.join(ee,"jobs.json"),xt=j.join(ee,"quota.json"),Tr=j.join(ee,"conversations.json"),Nr=j.join(ee,"sync-state.json"),jr=j.join(ee,"application-questions.json"),He=j.join(ee,"profile-history"),At=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ce=At(process.env.CONNECT_MAX_DAILY,20),$e=At(process.env.CONNECT_MAX_WEEKLY,100),he=null,Ln=null,X=null,Mn=null,Pn=null,qn=null;function Et(){he=null,Ln=null,X=null,Mn=null,Pn=null,qn=null}function Fe(){R.existsSync(ee)||R.mkdirSync(ee,{recursive:!0})}function We(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";R.writeFileSync(o,n);for(let r=0;r<3;r++)try{R.renameSync(o,e);return}catch(l){if(r<2&&(l.code==="EPERM"||l.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw l}}function Ye(e,t){if(!R.existsSync(e))return null;try{let n=JSON.parse(R.readFileSync(e,"utf-8"));try{R.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${j.resolve(e)}`);let o=e+".backup";if(R.existsSync(o))try{let r=JSON.parse(R.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{R.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{R.copyFileSync(e,e+".corrupted")}catch{}return null}}function xe(){return new Date().toISOString().split("T")[0]}var Un=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],Bn=["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(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Ne(e,t,n=null){if(!t||e[t])return t;let o=de(t);if(!o)return t;let r=null;for(let[l,i]of Object.entries(e)){if(de(i.profileUrl||l)===o)return l;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=l)}if(r){let l=kt(n),i=kt(e[r].name);if(l&&i&&l===i)return r}return t}function Jn(){R.existsSync(He)||R.mkdirSync(He,{recursive:!0})}function It(e){let t=de(e);return t?j.join(He,`${t}.json`):null}function Vn(e){let t=It(e);return t?Ye(t,`profile-history/${de(e)}.json`)||[]:[]}function Hn(e,t){let n=It(e);if(!n)return;Jn();let o=Vn(e);o.unshift(t);try{We(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${de(e)}: ${r.message}`)}}function Ct(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function $t(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Wn(e,t){if(!e)return[];let n=[];for(let o of Bn){let r=e[o],l=t[o];Ct(r)||Ct(l)||$t(r)!==$t(l)&&n.push(o)}return n}function Yn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function te(){return he||(Fe(),he=Ye(Ve,"people.json")||{},he)}function Le(e){Fe(),he=e;try{We(Ve,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${j.resolve(Ve)}`)}}function je(e,t={}){if(!e)return null;let n=te(),o=xe(),r=new Date().toISOString(),l=Ne(n,e,t.name),i=n[l];if(i){let c=Wn(i,t);c.length>0&&(Hn(l,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:Yn(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let s of Un)if(t[s]!=null){if(Array.isArray(t[s])&&t[s].length===0&&Array.isArray(i[s])&&i[s].length>0)continue;i[s]=t[s]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[l]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return Le(n),n[l]}function Dt(e,t){if(!e||!t)return;let n=te(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let l={date:xe(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(l.jobId=String(t.jobId)),t.jobTitle&&(l.jobTitle=t.jobTitle),t.jobCompany&&(l.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===l.date&&c.source===l.source&&c.action===l.action&&(c.jobId||"")===(l.jobId||""))&&(o.encounters.push(l),o.lastUpdated=new Date().toISOString(),Le(n))}function _t(e){return e&&te()[e]?.connectionStatus||null}function Rt(e,t,n={}){if(!e)return;if(n.profileInfo)je(e,n.profileInfo);else{let c=te(),s=Ne(c,e,n.profileInfo?.name);c[s]||je(e,{})}let o=te(),r=Ne(o,e,n.profileInfo?.name),l=o[r];if(!l)return;let i=xe();l.connectionStatus=t,t==="connected"?l.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(l.requestedConnectionAt||(l.requestedConnectionAt=i)),l.connectionMethod=n.method||l.connectionMethod,l.messageSent=n.messageSent||l.messageSent,l.lastUpdated=new Date().toISOString(),Le(o)}function Ot(e,t,n={}){if(n.dryRun||!e||!t)return;let o=de(t);if(!o)return;let r=te(),l=Ne(r,e),i=r[l];if(!i)return;let c=de(i.profileUrl||l);o!==c&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),Le(r)))}function Tt(){return X||(Fe(),X=Ye(xt,"quota.json"),(!X||!X.connections)&&(X={connections:[]}),X)}function Gn(e){Fe(),X=e;try{We(xt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Nt(e,t="unknown"){let n=Tt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Gn(n)}function jt(){let e=Tt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Ge(){let e=jt(),t=xe(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Ce,l=o>=$e,i=!r&&!l,c={allowed:i,daily:{sent:n,max:Ce},weekly:{sent:o,max:$e}};return i||(c.reason=r?`Daily limit reached (${n}/${Ce})`:`Weekly limit reached (${o}/${$e})`),c}function Ke(){let e=jt(),t=xe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Ce,remaining:Ce-n},weekly:{sent:o,max:$e,remaining:$e-o}}}async function Pt(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Mt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function to(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:l=!1,extractSkills:i=!1,extractRecommendations:c=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await ce(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await Pt(e,t));let a=0;for(let b=0;b<2;b++){let I=await e.evaluate(()=>document.body.scrollHeight);for(let O=1;O<=6;O++)await e.evaluate(T=>window.scrollTo(0,T),I*O/6),await S(900);let M=await e.evaluate(()=>document.body.scrollHeight);if(M===a)break;a=M}await S(800);let d=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(d=b.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let b=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"]),M=v=>{let $=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test($)},O={name:null,title:null,location:null,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:[]},T=document.querySelector("main");if(!T)return O;let C=[...Array.from(T.querySelectorAll("h1")),...Array.from(T.querySelectorAll("h2"))],F=Array.from(T.querySelectorAll("h2")),Z=C.find(v=>{let $=v.textContent&&v.textContent.trim(),A=($||"").replace(/\s*\(\d+\)$/,"").trim();return $&&$.length>1&&$.length<100&&!b.has(A)&&!I.has(A)}),G=Z?Z.textContent.trim():null,L=Z?Z.parentElement:null;for(;L&&L!==T&&!Array.from(L.children).filter($=>$.tagName==="P").some($=>{let A=$.textContent&&$.textContent.trim();return A&&A.length>5&&!M(A)});)L=L.parentElement;let re=null,we=null,Se=null,be=null;if(L&&L!==T){let v=Array.from(L.children).filter(A=>A.tagName==="P").filter(A=>{let se=A.textContent&&A.textContent.trim();return se&&se.length>5&&!M(se)});if(v[0]&&(re=v[0].textContent.trim()),v[1]){let A=v[1].textContent.trim().split(/\s*[·•]\s*/);we=A[0]||null,A.length>1&&(Se=A.slice(1).join(" \xB7 "))}let $=Array.from(L.children).filter(A=>A.tagName==="DIV");for(let A=$.length-1;A>=0;A--){let se=$[A].textContent&&$[A].textContent.trim();if(se&&!(G&&se.startsWith(G))&&(be=se.split(/[·•]/)[0].trim(),be))break}}let Re=null;if(L){let v=L.querySelectorAll("p, span, div");for(let $ of v){let A=($.textContent||"").trim().replace(/^[·•]\s*/,"");if(A==="1st"||A==="2nd"||A==="3rd"){Re=A;break}}}let D=!!T.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),N=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=N&&N.src||null,_=T.textContent||"",K=null,lt=_.match(/(\d+\+?)\s+connections\b/i);lt&&(K=lt[1]+" connections");let Oe=null,at=_.match(/(\d+)\s+mutual connection/i),ct=_.match(/and\s+(\d+)\s+other mutual/i),yn=_.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);at?Oe=parseInt(at[1],10):ct?Oe=2+parseInt(ct[1],10):yn&&(Oe=2);let ut=null,dt=null,ft=F.find(v=>v.textContent&&v.textContent.trim()==="About");if(ft){let v=ft.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let $=(v.textContent||"").trim();$=$.replace(/^About\s*/,"").trim();let A=$.match(/Top skills\s*(.+?)$/i);if(A){let qe=A[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(vn=>vn.trim()).filter(Boolean);qe.length>0&&qe.length<10&&(dt=qe)}$=$.split(/\n?…\s*more/i)[0].trim(),$=$.split(/\n?\.\.\.\s*more/i)[0].trim(),$=$.split(/\bTop skills\b/i)[0].trim(),$=$.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),ut=$||null}}let mt=null,pt=F.find(v=>v.textContent&&v.textContent.trim()==="Activity");if(pt){let v=pt.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let $=(v.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);$&&(mt=parseInt($[1].replace(/,/g,""),10))}}let wn=[...new Set(F.map(v=>(v.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(v=>v&&v.length>1&&v.length<60&&v!==G).filter(v=>b.has(v)))],ve=document.body.textContent||"",Sn=/#OpenToWork\b/i.test(ve)||/\bOpen to work\b/.test(ve),bn=/#Hiring\b/i.test(ve)||/\bI'?m hiring\b/i.test(ve)||/\bWe are hiring\b/i.test(ve);return{name:G,title:re,location:be,currentCompany:we,currentSchool:Se,connectionDegree:Re,hasVerifiedBadge:D,photoUrl:P,connectionsLevel:K,mutualConnectionsCount:Oe,followers:mt,openToWork:Sn,hiring:bn,about:ut,topSkills:dt,availableSections:wn}});console.log(`Viewed: ${f.name} - ${f.title}`);let m=null,g=null,y=null,p=null,h=null,k=null;if(o||r||l||i||c||s){let b=await Promise.resolve().then(()=>(Lt(),Ft));o&&(m=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&(g=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${g.length} entries`)),l&&(y=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),i&&(p=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),c&&(h=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${h.length} entries`)),s&&(k=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${k.length} entries`))}return{...f,profileUrl:t,resolvedUrl:d,...m!==null&&{experience:m},...g!==null&&{featured:g},...y!==null&&{education:y},...p!==null&&{skillsFull:p},...h!==null&&{recommendations:h},...k!==null&&{certifications:k}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function ge(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',l=d=>d&&!d.closest(r),i=d=>Array.from(document.querySelectorAll(d)).filter(l),c=i('button[aria-label*="Pending"], a[aria-label*="Pending"]'),s=i('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,u=i('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,a={pendingCount:c.length,pendingLabels:c.map(d=>d.getAttribute("aria-label")),hasMessageBtn:!!s,hasConnectBtn:!!u};return c.length>0?{status:"pending",debug:a}:s&&!u?{status:"connected",debug:a}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:a}:{status:"not_connected",debug:a}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await S(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function ze(e){let t=null,n=await e.evaluate(()=>{let u=document.querySelector("h1")?.textContent?.trim();if(u&&!u.includes("notification"))return u;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(u=a.textContent?.trim(),u&&!u.includes("notification")))return u;let d=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(d)return d.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let u=await e.evaluate(()=>{let d=document.querySelectorAll('a[href*="custom-invite"]');return{count:d.length,labels:Array.from(d).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});u.count>0&&console.log(` S0: ${u.count} custom-invite links: ${JSON.stringify(u.labels)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),m=d.toLowerCase().split(" ")[0],g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of f){let p=y.getBoundingClientRect();if(p.width===0||p.height===0||y.closest(g))continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(m))return y}return null},n);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:a,method:"connect_link"}}if(n){let u=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${u}"`);let a=await e.evaluate(f=>{let m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),g=document.querySelectorAll("button[aria-label]");return Array.from(g).filter(p=>{let h=p.getAttribute("aria-label")||"";return(h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&m.test(h)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},u);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),t=await e.evaluateHandle(f=>{let m=document.querySelectorAll("button[aria-label]"),g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',y=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let p of m){if(p.closest(g))continue;let h=p.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(h)&&(h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&y.test(h))return p}return null},u);let d=t?.asElement?.()||null;if(d||await t?.dispose?.().catch(()=>{}),d)return console.log(" Found: button matching profile name"),{button:d,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let u=await e.evaluate(d=>(d.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();u.includes("invite")&&!u.includes(a)&&(console.log(` Skipping primary button: wrong person (${u})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",l=null;for(let u of o){let a=await e.evaluate((d,f)=>{let m=d.className.includes("muted"),g=d.className.includes("sticky-header")||d.className.includes("sticky"),y=d.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(d.getAttribute("aria-label")||"").toLowerCase(),h=p.includes("invite"),k=f?p.includes(f):!0;return{isMuted:m,isStickyHeader:g,inRecommendations:y,hasInvite:h,matchesName:k,ariaLabel:p}},u,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}l=u;break}}for(let u of o)u!==l&&await u.dispose().catch(()=>{});if(l)return console.log(" Found: secondary button"),{button:l,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let i=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let u of c){let a=await e.evaluate(d=>{let f=d.getBoundingClientRect(),m=f.width>0&&f.height>0,g=d.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:g,top:f.top}},u);if(a.isVisible&&!a.isInStickyHeader){i=u,console.log(" Found More button by ID pattern (main)");break}}for(let u of c)u!==i&&await u.dispose().catch(()=>{});if(!i&&c.length>0&&(i=c[c.length-1],console.log(" Found More button by ID pattern (last)")),i||(i=await e.$('button[aria-label="More actions"]'),i&&console.log(" Found More button by aria-label")),!i){let u=await e.evaluateHandle(()=>{let d=Array.from(document.querySelectorAll("button, a")).find(m=>{let g=m.innerText?.trim(),y=m.getAttribute("aria-label")||"",p=m.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:g==="Follow"||g==="Message"||g==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!d)return null;let f=d.parentElement;for(let m=0;m<8&&f;m++){for(let g of f.querySelectorAll("button"))if(g.innerText?.trim()==="More"&&g!==d)return g;f=f.parentElement}return null});i=u?.asElement?.()||null,i||await u?.dispose?.().catch(()=>{}),i&&console.log(" Found More button by text (near profile actions)")}if(i)try{if(await e.evaluate(f=>f.scrollIntoView({behavior:"smooth",block:"center"}),i),await S(500),await e.evaluate(f=>f.click(),i),await S(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let a=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(a||(a=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),a||(a=await e.$('div[role="button"][aria-label*="Invite"]')),a||(a=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!a){let f=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let g of m){let y=g.querySelector('a[href*="custom-invite"]');if(y)return y;for(let p of g.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(p.innerText?.trim()==="Connect")return p}return null});a=f?.asElement?.()||null,a||await f?.dispose?.().catch(()=>{})}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};let d=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let g of f)for(let y of g.querySelectorAll('[role="menuitem"], a, div')){let p=y.innerText?.trim();p&&p.length<40&&m.push(p)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(d)}`),await e.keyboard.press("Escape"),d.some(f=>/remove (your )?connection/i.test(f)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(u){console.log(" More dropdown click failed:",u.message),await e.keyboard.press("Escape")}let s=await e.evaluateHandle(u=>{let a='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',d=(u||"").split(" ")[0].toLowerCase();for(let f of document.querySelectorAll("button[aria-label]")){if(f.closest(a))continue;let m=(f.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let g=f.getBoundingClientRect();if(!(g.width===0||g.height===0)){if(m.includes("invite")){if(d&&m.includes(d))return f;continue}if(m==="connect")return f}}return null},n||"");return t=s?.asElement?.()||null,t||await s?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function no(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let n=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),l=n.tag==="DIV",i=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(i))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(i.includes("invite")){let a=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(a&&!i.includes(a))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${a})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await S(2e3);let a=e.url();if(a.includes("premium")||a.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await S(2e3),"premium_redirect"}else l?(await e.evaluate(a=>a.click(),t),await S(3e3)):(await e.evaluate(a=>a.click(),t),await S(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function oo(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await S(1500);let n=await ze(e);if(n){await e.evaluate(r=>r.click(),n),await S(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await ye(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function ye(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(i=>{let c=s=>!!(s&&s.querySelector(i));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let i of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(i.innerText||""))return!0;return!1}),l=async()=>{let i=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(i)return i;let c=await e.evaluateHandle(s=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(s)||null,n);return i=c?.asElement?.()||null,i||await c?.dispose?.().catch(()=>{}),i};for(let i=0;i<2;i++){try{await t.evaluate(c=>c.click())}catch{}if(await S(3e3),await r())return!1;if(await o())return!0;if(i===0){let c=await l();if(!c)return await o();t=c,await S(600)}}return await o()}async function ro(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:l=!1}=n;if(!r){let c=Ge();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let i=await so(e,t,n);return i.connectionSent&&!l&&Nt(t,o),i}async function so(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:l=!0,skipIfConnected:i=!0,excludeLocations:c=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
- --- Connecting: ${u} ---`),c.length>0){let h=te()[t]?.location;if(Mt(h,c))return console.log(` \u26A0 Excluded location (stored): ${h}`),s.reason="excluded_location",s.profileInfo={location:h},s}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),await ce(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await Pt(e,t),await S(2e3)),s.profileInfo=await e.evaluate(()=>{let h=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=D=>{let N=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(N)},x={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return x;let I=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],M=Array.from(b.querySelectorAll("h2")),O=I.find(D=>{let N=D.textContent&&D.textContent.trim();return N&&N.length>1&&N.length<100&&!h.has(N)&&N!=="0 notifications"}),T=O?O.textContent.trim():null,C=O?O.parentElement:null;for(;C&&C!==b&&!Array.from(C.children).filter(P=>P.tagName==="P").some(P=>{let _=P.textContent&&P.textContent.trim();return _&&_.length>5&&!k(_)});)C=C.parentElement;let F=null,Z=null,G=null;if(C&&C!==b){let D=Array.from(C.children),N=D.filter(_=>_.tagName==="P").filter(_=>{let K=_.textContent&&_.textContent.trim();return K&&K.length>5&&!k(K)});N[0]&&(F=N[0].textContent.trim()),N[1]&&(Z=N[1].textContent.trim());let P=D.filter(_=>_.tagName==="DIV");for(let _=P.length-1;_>=0;_--){let K=P[_].textContent&&P[_].textContent.trim();if(K&&!(T&&K.startsWith(T))&&(G=K.split(/[·•]/)[0].trim(),G))break}}let L=null;if(C){let D=C.querySelectorAll("p, span, div");for(let N of D){let P=(N.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){L=P;break}}}let re=null,we=M.find(D=>D.textContent&&D.textContent.trim()==="About");if(we){let D=we.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;D&&(re=(D.textContent||"").trim().replace(/^About\s*/,"").trim()||null,re&&(re=re.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Se=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),be=Se&&Se.src||null,Re=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:T,title:F,location:G,about:re,company:Z,connectionDegree:L,connectionsCount:null,mutualConnections:null,photoUrl:be,hasVerifiedBadge:Re}});try{let h=e.url();h&&/\/in\/[^/?#]/.test(h)&&(s.resolvedUrl=h.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let h=s.profileInfo?.location,k=te()[t]?.location,x=h||k;if(Mt(x,c))return console.log(` \u26A0 Excluded location (${h?"live":"stored"}): ${x}`),s.reason="excluded_location",s;!h&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await ge(e,{detail:!0})).status==="pending"&&l)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;await ce(e);let f=await ze(e);if(f||await ce(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),f=await ze(e)),f&&f.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),s.reason="connected",s;if(!f){let h=await ge(e,{detail:!0});return i&&(h.status==="connected"||h.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),s.reason="connected",s):(console.log(" \u2717 Connect not found"),s.reason="button_not_found",s)}s.method=f.method;let m=await no(e,f.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let h=await ge(e);if(h==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${h} \u2014 trying More dropdown...`),await ce(e),await S(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),k),await S(500),await k.click().catch(()=>e.evaluate(b=>b.click(),k)),await S(2e3);let x=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(x){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(M=>M.click(),x),await S(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),s.reason="premium_required",s;if(await ge(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await S(500),s.reason="premium_required",s}catch(x){return console.log(" More dropdown failed:",x.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let h=await e.$('button[aria-label="Dismiss"]');return h&&await h.click(),await S(500),s.reason="email_required",s}let y=await e.$('button[aria-label="Add a note"]'),p=await e.$('button[aria-label="Send without a note"]');if(!y&&!p){let h=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let x=k.querySelector('button[aria-label="Add a note"]'),b=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!b}});if(h.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=k?.asElement?.()||null,y||await k.dispose().catch(()=>{})}if(h.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));p=k?.asElement?.()||null,p||await k.dispose().catch(()=>{})}}if(r)if(y&&o){if(console.log(" Adding personalized note..."),await y.click(),await S(1500),await e.$("div.modal-upsell")){let x=await oo(e);return s.success=x,s.connectionSent=x,s.reason=x?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=o.replace("{name}",x);await k.type(b,{delay:20}),await S(500);let I=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(I)return await ye(e,I)?(console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=b,s):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),s.reason="modal_failed",s)}}else{if(p)return console.log(" Sending without note..."),await ye(e,p)?(console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),s.reason="modal_failed",s);if(y&&!o){console.log(" No message provided, sending without note...");let h=await e.$('button[aria-label="Send without a note"]');if(h)return await ye(e,h)?(console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),s.reason="modal_failed",s)}}else{console.log(" Sending without note (custom messages disabled)...");let h=p;if(h)return await ye(e,h)?(console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),s.reason="modal_failed",s)}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3)),await ce(e),await S(500);let k=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let b of k){let I=await e.evaluate(M=>{let O=M.getBoundingClientRect();return{visible:O.width>0&&O.height>0,inSticky:!!M.closest('.sticky-header, [class*="sticky"]')}},b);if(I.visible&&!I.inSticky){x=b;break}}!x&&k.length>0&&(x=k[k.length-1]);for(let b of k)b!==x&&await b.dispose().catch(()=>{});if(x)try{await e.evaluate(I=>I.scrollIntoView({behavior:"smooth",block:"center"}),x),await S(500),await x.click().catch(()=>e.evaluate(I=>I.click(),x)),await S(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(b){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(T=>T.click(),b),await S(3e3);let I=e.url();if(I.includes("/premium/")||I.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await ge(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await ge(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let O=await e.$('button[aria-label="Send without a note"]');if(O)return console.log(" Modal appeared via More dropdown, sending without note..."),await ye(e,O)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),s.reason="modal_failed",s);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(u){console.error(` \u2717 Error: ${u.message}`),s.reason="error",s.error=u.message;let a=u.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{s.fatal=!0}return s}}async function qt(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:l=20,viewOnly:i=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:s=null,excludeLocations:u=[],source:a="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
245
+ `)}`;try{await yt.addMessage(i,s)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Dn=In(import.meta.url),_n=ie.dirname(ie.dirname(Dn)),Be=process.env.DATA_DIR?ie.resolve(process.env.DATA_DIR,"collected-profiles"):ie.join(_n,"collected-profiles"),Ue=ie.join(Be,"run-log.json");function Rn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";J.writeFileSync(o,n);for(let r=0;r<3;r++)try{J.renameSync(o,e);return}catch(l){if(r<2&&(l.code==="EPERM"||l.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw l}}function St(){try{if(!J.existsSync(Ue))return{runs:[]};let e=JSON.parse(J.readFileSync(Ue,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function bt(e){J.existsSync(Be)||J.mkdirSync(Be,{recursive:!0});try{Rn(Ue,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function vt(e,t="default"){let n=St();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let l=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>l),bt(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Je(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=St(),c=i.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let s=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=o,r=s.duration)}bt(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let l=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(l&&l.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";wt({scriptName:e.script,mode:e.mode,status:i,summaryLines:l,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Te();Te();import{getPluginConfig as On}from"@ilivemylife/graph-sdk";var Tn=await On();for(let[e,t]of Object.entries(Tn))process.env[e]===void 0&&(process.env[e]=t);var xr=process.env.LINKEDIN_NAME,ue=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Er=Object.freeze(new Set([ue.DRAFT,ue.CONFIRMED,ue.NEEDS_REVIEW])),Ar=Object.freeze(new Set([ue.DRAFT,ue.CONFIRMED,ue.REJECTED,ue.NEEDS_REVIEW]));import"dotenv/config";import*as R from"fs";import*as j from"path";import{fileURLToPath as Nn}from"url";var jn=Nn(import.meta.url),Fn=j.dirname(j.dirname(jn)),ee=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"collected-profiles"):j.join(Fn,"collected-profiles"),Ve=j.join(ee,"people.json"),Or=j.join(ee,"jobs.json"),xt=j.join(ee,"quota.json"),Tr=j.join(ee,"conversations.json"),Nr=j.join(ee,"sync-state.json"),jr=j.join(ee,"application-questions.json"),He=j.join(ee,"profile-history"),Et=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ce=Et(process.env.CONNECT_MAX_DAILY,20),$e=Et(process.env.CONNECT_MAX_WEEKLY,100),he=null,Ln=null,X=null,Mn=null,Pn=null,qn=null;function At(){he=null,Ln=null,X=null,Mn=null,Pn=null,qn=null}function Fe(){R.existsSync(ee)||R.mkdirSync(ee,{recursive:!0})}function We(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";R.writeFileSync(o,n);for(let r=0;r<3;r++)try{R.renameSync(o,e);return}catch(l){if(r<2&&(l.code==="EPERM"||l.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw l}}function Ye(e,t){if(!R.existsSync(e))return null;try{let n=JSON.parse(R.readFileSync(e,"utf-8"));try{R.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${j.resolve(e)}`);let o=e+".backup";if(R.existsSync(o))try{let r=JSON.parse(R.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{R.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{R.copyFileSync(e,e+".corrupted")}catch{}return null}}function xe(){return new Date().toISOString().split("T")[0]}var Bn=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],Un=["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(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Ne(e,t,n=null){if(!t||e[t])return t;let o=de(t);if(!o)return t;let r=null;for(let[l,i]of Object.entries(e)){if(de(i.profileUrl||l)===o)return l;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=l)}if(r){let l=kt(n),i=kt(e[r].name);if(l&&i&&l===i)return r}return t}function Jn(){R.existsSync(He)||R.mkdirSync(He,{recursive:!0})}function It(e){let t=de(e);return t?j.join(He,`${t}.json`):null}function Vn(e){let t=It(e);return t?Ye(t,`profile-history/${de(e)}.json`)||[]:[]}function Hn(e,t){let n=It(e);if(!n)return;Jn();let o=Vn(e);o.unshift(t);try{We(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${de(e)}: ${r.message}`)}}function Ct(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function $t(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Wn(e,t){if(!e)return[];let n=[];for(let o of Un){let r=e[o],l=t[o];Ct(r)||Ct(l)||$t(r)!==$t(l)&&n.push(o)}return n}function Yn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function te(){return he||(Fe(),he=Ye(Ve,"people.json")||{},he)}function Le(e){Fe(),he=e;try{We(Ve,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${j.resolve(Ve)}`)}}function je(e,t={}){if(!e)return null;let n=te(),o=xe(),r=new Date().toISOString(),l=Ne(n,e,t.name),i=n[l];if(i){let c=Wn(i,t);c.length>0&&(Hn(l,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:Yn(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let s of Bn)if(t[s]!=null){if(Array.isArray(t[s])&&t[s].length===0&&Array.isArray(i[s])&&i[s].length>0)continue;i[s]=t[s]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[l]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return Le(n),n[l]}function Dt(e,t){if(!e||!t)return;let n=te(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let l={date:xe(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(l.jobId=String(t.jobId)),t.jobTitle&&(l.jobTitle=t.jobTitle),t.jobCompany&&(l.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===l.date&&c.source===l.source&&c.action===l.action&&(c.jobId||"")===(l.jobId||""))&&(o.encounters.push(l),o.lastUpdated=new Date().toISOString(),Le(n))}function _t(e){return e&&te()[e]?.connectionStatus||null}function Rt(e,t,n={}){if(!e)return;if(n.profileInfo)je(e,n.profileInfo);else{let c=te(),s=Ne(c,e,n.profileInfo?.name);c[s]||je(e,{})}let o=te(),r=Ne(o,e,n.profileInfo?.name),l=o[r];if(!l)return;let i=xe();l.connectionStatus=t,t==="connected"?l.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(l.requestedConnectionAt||(l.requestedConnectionAt=i)),l.connectionMethod=n.method||l.connectionMethod,l.messageSent=n.messageSent||l.messageSent,l.lastUpdated=new Date().toISOString(),Le(o)}function Ot(e,t,n={}){if(n.dryRun||!e||!t)return;let o=de(t);if(!o)return;let r=te(),l=Ne(r,e),i=r[l];if(!i)return;let c=de(i.profileUrl||l);o!==c&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),Le(r)))}function Tt(){return X||(Fe(),X=Ye(xt,"quota.json"),(!X||!X.connections)&&(X={connections:[]}),X)}function Gn(e){Fe(),X=e;try{We(xt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Nt(e,t="unknown"){let n=Tt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Gn(n)}function jt(){let e=Tt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Ge(){let e=jt(),t=xe(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Ce,l=o>=$e,i=!r&&!l,c={allowed:i,daily:{sent:n,max:Ce},weekly:{sent:o,max:$e}};return i||(c.reason=r?`Daily limit reached (${n}/${Ce})`:`Weekly limit reached (${o}/${$e})`),c}function Ke(){let e=jt(),t=xe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Ce,remaining:Ce-n},weekly:{sent:o,max:$e,remaining:$e-o}}}async function Pt(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Mt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function to(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:l=!1,extractSkills:i=!1,extractRecommendations:c=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await ce(e)&&(console.log(" Dismissed Premium overlay"),await b(1500),await Pt(e,t));let a=0;for(let S=0;S<2;S++){let A=await e.evaluate(()=>document.body.scrollHeight);for(let O=1;O<=6;O++)await e.evaluate(T=>window.scrollTo(0,T),A*O/6),await b(900);let M=await e.evaluate(()=>document.body.scrollHeight);if(M===a)break;a=M}await b(800);let d=null;try{let S=e.url();S&&/\/in\/[^/?#]/.test(S)&&(d=S.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let S=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"]),A=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"]),M=k=>{let x=(k||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(x)},O={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:[]},T=document.querySelector("main");if(!T)return O;let C=[...Array.from(T.querySelectorAll("h1")),...Array.from(T.querySelectorAll("h2"))],F=Array.from(T.querySelectorAll("h2")),Z=C.find(k=>{let x=k.textContent&&k.textContent.trim(),E=(x||"").replace(/\s*\(\d+\)$/,"").trim();return x&&x.length>1&&x.length<100&&!S.has(E)&&!A.has(E)}),G=Z?Z.textContent.trim():null,L=Z?Z.parentElement:null;for(;L&&L!==T&&!Array.from(L.children).filter(x=>x.tagName==="P").some(x=>{let E=x.textContent&&x.textContent.trim();return E&&E.length>5&&!M(E)});)L=L.parentElement;let re=null,we=null,Se=null,be=null;if(L&&L!==T){let k=Array.from(L.children).filter(E=>E.tagName==="P").filter(E=>{let se=E.textContent&&E.textContent.trim();return se&&se.length>5&&!M(se)});if(k[0]&&(re=k[0].textContent.trim()),k[1]){let E=k[1].textContent.trim().split(/\s*[·•]\s*/);we=E[0]||null,E.length>1&&(Se=E.slice(1).join(" \xB7 "))}let x=Array.from(L.children).filter(E=>E.tagName==="DIV");for(let E=x.length-1;E>=0;E--){let se=x[E].textContent&&x[E].textContent.trim();if(se&&!(G&&se.startsWith(G))&&(be=se.split(/[·•]/)[0].trim(),be))break}}let Re=null;if(L){let k=L.querySelectorAll("p, span, div");for(let x of k){let E=(x.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){Re=E;break}}}let D=!!T.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),N=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=N&&N.src||null,_=T.textContent||"",K=null,lt=_.match(/(\d+\+?)\s+connections\b/i);lt&&(K=lt[1]+" connections");let Oe=null,at=_.match(/(\d+)\s+mutual connection/i),ct=_.match(/and\s+(\d+)\s+other mutual/i),yn=_.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);at?Oe=parseInt(at[1],10):ct?Oe=2+parseInt(ct[1],10):yn&&(Oe=2);let ut=null,dt=null,ft=F.find(k=>k.textContent&&k.textContent.trim()==="About");if(ft){let k=ft.parentElement;for(;k&&k.tagName!=="SECTION";)k=k.parentElement;if(k){let x=(k.textContent||"").trim();x=x.replace(/^About\s*/,"").trim();let E=x.match(/Top skills\s*(.+?)$/i);if(E){let qe=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(vn=>vn.trim()).filter(Boolean);qe.length>0&&qe.length<10&&(dt=qe)}x=x.split(/\n?…\s*more/i)[0].trim(),x=x.split(/\n?\.\.\.\s*more/i)[0].trim(),x=x.split(/\bTop skills\b/i)[0].trim(),x=x.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),ut=x||null}}let mt=null,pt=F.find(k=>k.textContent&&k.textContent.trim()==="Activity");if(pt){let k=pt.parentElement;for(;k&&k.tagName!=="SECTION";)k=k.parentElement;if(k){let x=(k.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);x&&(mt=parseInt(x[1].replace(/,/g,""),10))}}let wn=[...new Set(F.map(k=>(k.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(k=>k&&k.length>1&&k.length<60&&k!==G).filter(k=>S.has(k)))],ve=document.body.textContent||"",Sn=/#OpenToWork\b/i.test(ve)||/\bOpen to work\b/.test(ve),bn=/#Hiring\b/i.test(ve)||/\bI'?m hiring\b/i.test(ve)||/\bWe are hiring\b/i.test(ve);return{name:G,title:re,location:be,currentCompany:we,currentSchool:Se,connectionDegree:Re,hasVerifiedBadge:D,photoUrl:P,connectionsLevel:K,mutualConnectionsCount:Oe,followers:mt,openToWork:Sn,hiring:bn,about:ut,topSkills:dt,availableSections:wn}});console.log(`Viewed: ${f.name} - ${f.title}`);let m=null,g=null,y=null,h=null,p=null,v=null;if(o||r||l||i||c||s){let S=await Promise.resolve().then(()=>(Lt(),Ft));o&&(m=await S.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&(g=await S.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${g.length} entries`)),l&&(y=await S.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),i&&(h=await S.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),c&&(p=await S.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${p.length} entries`)),s&&(v=await S.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...f,profileUrl:t,resolvedUrl:d,...m!==null&&{experience:m},...g!==null&&{featured:g},...y!==null&&{education:y},...h!==null&&{skillsFull:h},...p!==null&&{recommendations:p},...v!==null&&{certifications:v}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function ge(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',l=d=>d&&!d.closest(r),i=d=>Array.from(document.querySelectorAll(d)).filter(l),c=i('button[aria-label*="Pending"], a[aria-label*="Pending"]'),s=i('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,u=i('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,a={pendingCount:c.length,pendingLabels:c.map(d=>d.getAttribute("aria-label")),hasMessageBtn:!!s,hasConnectBtn:!!u};return c.length>0?{status:"pending",debug:a}:s&&!u?{status:"connected",debug:a}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:a}:{status:"not_connected",debug:a}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await b(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function ze(e){let t=null,n=await e.evaluate(()=>{let u=document.querySelector("h1")?.textContent?.trim();if(u&&!u.includes("notification"))return u;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(u=a.textContent?.trim(),u&&!u.includes("notification")))return u;let d=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(d)return d.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let u=await e.evaluate(()=>{let d=document.querySelectorAll('a[href*="custom-invite"]');return{count:d.length,labels:Array.from(d).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});u.count>0&&console.log(` S0: ${u.count} custom-invite links: ${JSON.stringify(u.labels)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),m=d.toLowerCase().split(" ")[0],g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of f){let h=y.getBoundingClientRect();if(h.width===0||h.height===0||y.closest(g))continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(m))return y}return null},n);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:a,method:"connect_link"}}if(n){let u=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${u}"`);let a=await e.evaluate(f=>{let m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),g=document.querySelectorAll("button[aria-label]");return Array.from(g).filter(h=>{let p=h.getAttribute("aria-label")||"";return(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p)}).map(h=>h.getAttribute("aria-label")?.slice(0,50))},u);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),t=await e.evaluateHandle(f=>{let m=document.querySelectorAll("button[aria-label]"),g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',y=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of m){if(h.closest(g))continue;let p=h.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(p)&&(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&y.test(p))return h}return null},u);let d=t?.asElement?.()||null;if(d||await t?.dispose?.().catch(()=>{}),d)return console.log(" Found: button matching profile name"),{button:d,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let u=await e.evaluate(d=>(d.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();u.includes("invite")&&!u.includes(a)&&(console.log(` Skipping primary button: wrong person (${u})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",l=null;for(let u of o){let a=await e.evaluate((d,f)=>{let m=d.className.includes("muted"),g=d.className.includes("sticky-header")||d.className.includes("sticky"),y=d.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(d.getAttribute("aria-label")||"").toLowerCase(),p=h.includes("invite"),v=f?h.includes(f):!0;return{isMuted:m,isStickyHeader:g,inRecommendations:y,hasInvite:p,matchesName:v,ariaLabel:h}},u,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}l=u;break}}for(let u of o)u!==l&&await u.dispose().catch(()=>{});if(l)return console.log(" Found: secondary button"),{button:l,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let i=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let u of c){let a=await e.evaluate(d=>{let f=d.getBoundingClientRect(),m=f.width>0&&f.height>0,g=d.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:g,top:f.top}},u);if(a.isVisible&&!a.isInStickyHeader){i=u,console.log(" Found More button by ID pattern (main)");break}}for(let u of c)u!==i&&await u.dispose().catch(()=>{});if(!i&&c.length>0&&(i=c[c.length-1],console.log(" Found More button by ID pattern (last)")),i||(i=await e.$('button[aria-label="More actions"]'),i&&console.log(" Found More button by aria-label")),!i){let u=await e.evaluateHandle(()=>{let d=Array.from(document.querySelectorAll("button, a")).find(m=>{let g=m.innerText?.trim(),y=m.getAttribute("aria-label")||"",h=m.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:g==="Follow"||g==="Message"||g==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!d)return null;let f=d.parentElement;for(let m=0;m<8&&f;m++){for(let g of f.querySelectorAll("button"))if(g.innerText?.trim()==="More"&&g!==d)return g;f=f.parentElement}return null});i=u?.asElement?.()||null,i||await u?.dispose?.().catch(()=>{}),i&&console.log(" Found More button by text (near profile actions)")}if(i)try{if(await e.evaluate(f=>f.scrollIntoView({behavior:"smooth",block:"center"}),i),await b(500),await e.evaluate(f=>f.click(),i),await b(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let a=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(a||(a=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),a||(a=await e.$('div[role="button"][aria-label*="Invite"]')),a||(a=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!a){let f=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let g of m){let y=g.querySelector('a[href*="custom-invite"]');if(y)return y;for(let h of g.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});a=f?.asElement?.()||null,a||await f?.dispose?.().catch(()=>{})}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};let d=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let g of f)for(let y of g.querySelectorAll('[role="menuitem"], a, div')){let h=y.innerText?.trim();h&&h.length<40&&m.push(h)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(d)}`),await e.keyboard.press("Escape"),d.some(f=>/remove (your )?connection/i.test(f)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(u){console.log(" More dropdown click failed:",u.message),await e.keyboard.press("Escape")}let s=await e.evaluateHandle(u=>{let a='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',d=(u||"").split(" ")[0].toLowerCase();for(let f of document.querySelectorAll("button[aria-label]")){if(f.closest(a))continue;let m=(f.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let g=f.getBoundingClientRect();if(!(g.width===0||g.height===0)){if(m.includes("invite")){if(d&&m.includes(d))return f;continue}if(m==="connect")return f}}return null},n||"");return t=s?.asElement?.()||null,t||await s?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function no(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await b(500);let n=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),l=n.tag==="DIV",i=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(i))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(i.includes("invite")){let a=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(a&&!i.includes(a))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${a})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await b(2e3);let a=e.url();if(a.includes("premium")||a.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await b(2e3),"premium_redirect"}else l?(await e.evaluate(a=>a.click(),t),await b(3e3)):(await e.evaluate(a=>a.click(),t),await b(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function oo(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await b(1500);let n=await ze(e);if(n){await e.evaluate(r=>r.click(),n),await b(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await ye(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function ye(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(i=>{let c=s=>!!(s&&s.querySelector(i));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let i of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(i.innerText||""))return!0;return!1}),l=async()=>{let i=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(i)return i;let c=await e.evaluateHandle(s=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(s)||null,n);return i=c?.asElement?.()||null,i||await c?.dispose?.().catch(()=>{}),i};for(let i=0;i<2;i++){try{await t.evaluate(c=>c.click())}catch{}if(await b(3e3),await r())return!1;if(await o())return!0;if(i===0){let c=await l();if(!c)return await o();t=c,await b(600)}}return await o()}async function ro(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:l=!1}=n;if(!r){let c=Ge();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let i=await so(e,t,n);return i.connectionSent&&!l&&Nt(t,o),i}async function so(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:l=!0,skipIfConnected:i=!0,excludeLocations:c=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
+ --- Connecting: ${u} ---`),c.length>0){let p=te()[t]?.location;if(Mt(p,c))return console.log(` \u26A0 Excluded location (stored): ${p}`),s.reason="excluded_location",s.profileInfo={location:p},s}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(5e3),await ce(e)&&(console.log(" Dismissed Premium overlay"),await b(2e3),await Pt(e,t),await b(2e3)),s.profileInfo=await e.evaluate(()=>{let p=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),v=D=>{let N=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(N)},$={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},S=document.querySelector("main");if(!S)return $;let A=[...Array.from(S.querySelectorAll("h1")),...Array.from(S.querySelectorAll("h2"))],M=Array.from(S.querySelectorAll("h2")),O=A.find(D=>{let N=D.textContent&&D.textContent.trim();return N&&N.length>1&&N.length<100&&!p.has(N)&&N!=="0 notifications"}),T=O?O.textContent.trim():null,C=O?O.parentElement:null;for(;C&&C!==S&&!Array.from(C.children).filter(P=>P.tagName==="P").some(P=>{let _=P.textContent&&P.textContent.trim();return _&&_.length>5&&!v(_)});)C=C.parentElement;let F=null,Z=null,G=null;if(C&&C!==S){let D=Array.from(C.children),N=D.filter(_=>_.tagName==="P").filter(_=>{let K=_.textContent&&_.textContent.trim();return K&&K.length>5&&!v(K)});N[0]&&(F=N[0].textContent.trim()),N[1]&&(Z=N[1].textContent.trim());let P=D.filter(_=>_.tagName==="DIV");for(let _=P.length-1;_>=0;_--){let K=P[_].textContent&&P[_].textContent.trim();if(K&&!(T&&K.startsWith(T))&&(G=K.split(/[·•]/)[0].trim(),G))break}}let L=null;if(C){let D=C.querySelectorAll("p, span, div");for(let N of D){let P=(N.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){L=P;break}}}let re=null,we=M.find(D=>D.textContent&&D.textContent.trim()==="About");if(we){let D=we.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;D&&(re=(D.textContent||"").trim().replace(/^About\s*/,"").trim()||null,re&&(re=re.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Se=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),be=Se&&Se.src||null,Re=!!S.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:T,title:F,location:G,about:re,company:Z,connectionDegree:L,connectionsCount:null,mutualConnections:null,photoUrl:be,hasVerifiedBadge:Re}});try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(s.resolvedUrl=p.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let p=s.profileInfo?.location,v=te()[t]?.location,$=p||v;if(Mt($,c))return console.log(` \u26A0 Excluded location (${p?"live":"stored"}): ${$}`),s.reason="excluded_location",s;!p&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await ge(e,{detail:!0})).status==="pending"&&l)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;await ce(e);let f=await ze(e);if(f||await ce(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await b(2e3),f=await ze(e)),f&&f.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),s.reason="connected",s;if(!f){let p=await ge(e,{detail:!0});return i&&(p.status==="connected"||p.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),s.reason="connected",s):(console.log(" \u2717 Connect not found"),s.reason="button_not_found",s)}s.method=f.method;let m=await no(e,f.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(4e3);let p=await ge(e);if(p==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${p} \u2014 trying More dropdown...`),await ce(e),await b(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(S=>S.scrollIntoView({behavior:"smooth",block:"center"}),v),await b(500),await v.click().catch(()=>e.evaluate(S=>S.click(),v)),await b(2e3);let $=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if($){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(M=>M.click(),$),await b(3e3);let S=e.url();if(S.includes("/premium/")||S.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),s.reason="premium_required",s;if(await ge(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await b(500),s.reason="premium_required",s}catch($){return console.log(" More dropdown failed:",$.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let v of p){let $=v.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!$)continue;let S=($.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(S)||$.querySelector('input[type="email"], input[name="email"]'))return!0;let A=$.querySelector('button[aria-label="Send without a note"]');if(A&&(A.disabled||A.getAttribute("aria-disabled")==="true"||(A.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let p=await e.$('button[aria-label="Dismiss"]');if(p)try{await p.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await b(500),s.reason="email_required",s}let y=await e.$('button[aria-label="Add a note"]'),h=await e.$('button[aria-label="Send without a note"]');if(!y&&!h){let p=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let $=v.querySelector('button[aria-label="Add a note"]'),S=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!$,sendWithout:!!S}});if(p.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=v?.asElement?.()||null,y||await v.dispose().catch(()=>{})}if(p.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));h=v?.asElement?.()||null,h||await v.dispose().catch(()=>{})}}if(r)if(y&&o){if(console.log(" Adding personalized note..."),await y.click(),await b(1500),await e.$("div.modal-upsell")){let $=await oo(e);return s.success=$,s.connectionSent=$,s.reason=$?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let $=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),S=o.replace("{name}",$);await v.type(S,{delay:20}),await b(500);let A=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(A)return await ye(e,A)?(console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=S,s):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),s.reason="modal_failed",s)}}else{if(h)return console.log(" Sending without note..."),await ye(e,h)?(console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),s.reason="modal_failed",s);if(y&&!o){console.log(" No message provided, sending without note...");let p=await e.$('button[aria-label="Send without a note"]');if(p)return await ye(e,p)?(console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),s.reason="modal_failed",s)}}else{console.log(" Sending without note (custom messages disabled)...");let p=h;if(p)return await ye(e,p)?(console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),s.reason="modal_failed",s)}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(4e3)),await ce(e),await b(500);let v=await e.$$('button[id*="profile-overflow-action"]'),$=null;for(let S of v){let A=await e.evaluate(M=>{let O=M.getBoundingClientRect();return{visible:O.width>0&&O.height>0,inSticky:!!M.closest('.sticky-header, [class*="sticky"]')}},S);if(A.visible&&!A.inSticky){$=S;break}}!$&&v.length>0&&($=v[v.length-1]);for(let S of v)S!==$&&await S.dispose().catch(()=>{});if($)try{await e.evaluate(A=>A.scrollIntoView({behavior:"smooth",block:"center"}),$),await b(500),await $.click().catch(()=>e.evaluate(A=>A.click(),$)),await b(2e3);let S=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(S){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(T=>T.click(),S),await b(3e3);let A=e.url();if(A.includes("/premium/")||A.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await ge(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await ge(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let O=await e.$('button[aria-label="Send without a note"]');if(O)return console.log(" Modal appeared via More dropdown, sending without note..."),await ye(e,O)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),s.reason="modal_failed",s);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(S){console.log(" More dropdown fallback failed:",S.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(u){console.error(` \u2717 Error: ${u.message}`),s.reason="error",s.error=u.message;let a=u.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{s.fatal=!0}return s}}async function qt(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:l=20,viewOnly:i=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:s=null,excludeLocations:u=[],source:a="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
247
247
  === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${i?"View Only":`Connect (max ${l})`}`),i||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!i){let m=Ke();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let f=0;for(let m=0;m<t.length;m++){let g=t[m];try{if(e.isClosed()){console.log(`
248
248
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
249
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let y=_t(g.profileUrl);if(y==="pending"||y==="connected"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${y})`),y==="pending"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,s&&await s(g,d,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl}`);let p=null;if(i){let h=await to(e,g.profileUrl);h?(je(g.profileUrl,{...h,source:a}),d.viewed++,p={success:!0,reason:"viewed",connectionSent:!1,profileInfo:h,resolvedUrl:h.resolvedUrl}):(d.errors++,p={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=l){console.log(` Max connections per session (${l}) reached`);break}let h=Ge();if(!h.allowed){console.log(` \u26A0 Global quota exhausted: ${h.reason}`);break}if(p=await ro(e,g.profileUrl,{message:o,useCustomMessage:r,excludeLocations:u,source:a,skipQuotaGate:!0}),p.success)d.connectionsSent++;else switch(p.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(p?.fatal){console.log(`
250
- \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(p?.reason==="error"){if(f++,f>=3){console.log(`
251
- \u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(p&&p.reason&&(Rt(g.profileUrl,p.reason,{method:p.method,messageSent:p.messageSent,profileInfo:p.profileInfo}),p.resolvedUrl&&Ot(g.profileUrl,p.resolvedUrl),Dt(g.profileUrl,{source:a||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:p.reason})),s&&await s(g,d,p),m<t.length-1){let h=c+Math.random()*2e3;await S(h)}}if(console.log(`
252
- === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!i){let m=Ke();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return d}import"dotenv/config";import*as q from"fs";import*as ne from"path";import{fileURLToPath as io}from"url";var lo=io(import.meta.url),ao=ne.dirname(ne.dirname(lo)),De=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(ao,"collected-profiles");function Qe(){q.existsSync(De)||q.mkdirSync(De,{recursive:!0})}function co(){return new Date().toISOString().split("T")[0]}function Ut(e,t=null){let n=t||co();return ne.join(De,`${e}-${n}.json`)}function Bt(e,t=null){Qe();let n=Ut(e,t);try{if(q.existsSync(n)){let o=q.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function Jt(e,t=null){return Bt(e,t).filter(o=>!o.processed)}function Vt(e,t,n,o=null){Qe();let r=Ut(e,o);try{if(!q.existsSync(r))return;let l=JSON.parse(q.readFileSync(r,"utf-8")),i=l.profiles.find(c=>c.profileUrl===t);if(i){if(i.processed=!0,i.processedAt=new Date().toISOString(),typeof n=="string")i.status=n;else if(typeof n=="object"){if(i.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(i.name=c.name),c.title&&(i.title=c.title),c.location&&(i.location=c.location),c.company&&(i.company=c.company),c.connectionDegree&&(i.connectionDegree=c.connectionDegree),c.connectionsCount&&(i.connectionsCount=c.connectionsCount),c.mutualConnections&&(i.mutualConnections=c.mutualConnections),c.photoUrl&&(i.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(i.hasVerifiedBadge=c.hasVerifiedBadge)}i.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}l.lastUpdated=new Date().toISOString(),q.writeFileSync(r,JSON.stringify(l,null,2))}}catch(l){console.error("Error marking profile processed:",l.message)}}function Ht(e){let t=Bt(e),n=t.filter(r=>r.processed),o=t.filter(r=>!r.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((r,l)=>(r[l.status]=(r[l.status]||0)+1,r),{})}}function Wt(){Qe();try{return q.readdirSync(De).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(q.readFileSync(ne.join(De,t),"utf-8"));return{file:t,source:n,date:o,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(l=>!l.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as w from"fs";import*as st from"os";import*as E from"path";import{fileURLToPath as Bo}from"url";var et={};ke(et,{NAME:()=>fo,VERSION:()=>uo,up:()=>ho});import*as V from"fs";import*as Me from"path";var uo=1,fo="normalize-jobs-and-questions",mo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],po=50;function Ze(e){return V.existsSync(e)?JSON.parse(V.readFileSync(e,"utf-8")):null}function Xe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{V.writeFileSync(o,n)}catch(r){try{V.unlinkSync(o)}catch{}throw r}try{V.renameSync(o,e)}catch(r){try{V.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function ho(e,t){let n=Me.join(e,"jobs.json"),o=Me.join(t,"scouted-jobs.json"),r=Me.join(e,"application-questions.json"),l=Ze(n)||{},i=Ze(o)||{},c=0,s=[];for(let a of Object.keys(l)){if(!i[a])continue;let d=i[a],f=l[a];for(let m of mo)d[m]!=null&&f[m]==null&&(f[m]=d[m]);s.push(a),c++}c>0?(Xe(n,l),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Ze(r);if(u&&Array.isArray(u.applications)){let a={},d=0;for(let f of u.applications){let m=f.jobId||"unknown";a[m]||(a[m]={applications:[]});let g=(f.questions||[]).map(y=>{let p={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=po?p.options=y.options:(p.optionsOmitted=!0,d++)),y.page&&(p.page=y.page),y.wasPreFilled&&(p.wasPreFilled=!0),y.wasRetry&&(p.wasRetry=!0),p});a[m].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||g.length,questions:g})}Xe(r,a),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(s.length>0){for(let a of s)delete i[a];Xe(o,i),console.log(` Phase 3: Removed ${s.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 tt={};ke(tt,{NAME:()=>yo,VERSION:()=>go,up:()=>bo});import*as H from"fs";import*as Yt from"path";var go=2,yo="reset-unread-flags";function wo(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function So(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(r){try{H.unlinkSync(o)}catch{}throw r}try{H.renameSync(o,e)}catch(r){try{H.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function bo(e){let t=Yt.join(e,"conversations.json"),n=wo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}So(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var nt={};ke(nt,{NAME:()=>ko,VERSION:()=>vo,up:()=>Eo});import*as W from"fs";import*as Gt from"path";var vo=3,ko="recompute-last-message-by",Co=new Set(["draft","confirmed","rejected","needs_review"]);function $o(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function xo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(r){try{W.unlinkSync(o)}catch{}throw r}try{W.renameSync(o,e)}catch(r){try{W.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}function Ao(e,t){if(!e||e.length===0)return"them";let n=e.filter(l=>!Co.has(l.status));if(n.length===0)return"them";let o=n.map(l=>({m:l,t:Date.parse(l.time)})).filter(l=>Number.isFinite(l.t)).sort((l,i)=>i.t-l.t).map(l=>l.m),r=o.length>0?o:[...n].reverse();for(let l of r){let i=l.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Eo(e){let t=Gt.join(e,"conversations.json"),n=$o(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,l=0,i=0;for(let c of Object.keys(n)){let s=n[c];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,l++);let u=Array.isArray(s.messages)?s.messages:[],a=Ao(u,o),d=a==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==a&&i++,s.lastMessageBy=a,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}xo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),l>0&&console.log(` Cleaned ${l} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var ot={};ke(ot,{NAME:()=>Do,VERSION:()=>Io,up:()=>To});import*as Y from"fs";import*as Kt from"path";var Io=4,Do="split-connection-timestamps",_o=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ro(e){if(!Y.existsSync(e))return null;let t=Y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Oo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function To(e){let t=Kt.join(e,"people.json"),n=Ro(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let l of Object.keys(n)){let i=n[l];!i||typeof i!="object"||(r++,_o.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Oo(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as B from"path";import{fileURLToPath as No}from"url";var jo=No(import.meta.url),Fo=B.dirname(B.dirname(jo)),_e=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"market-research"):B.join(Fo,"market-research"),Wr=B.join(_e,"scouted-jobs.json"),Yr=B.join(_e,"discovered-people.json"),Gr=B.join(_e,"visit-log.json"),Kr=B.join(_e,"companies.json"),zr=B.join(_e,"job-decisions.json");function zt(){Lo=null,Mo=null,Po=null,qo=null,Uo=null}var Lo=null;var Mo=null;var Po=null;var qo=null;var Uo=null;var Jo=Bo(import.meta.url),Vo=E.dirname(Jo),Ho=E.dirname(E.dirname(Vo));function Wo(e){return e&&(e==="~"?st.homedir():e.startsWith("~/")||e.startsWith("~\\")?E.join(st.homedir(),e.slice(2)):e)}var z=process.env.DATA_DIR?E.resolve(Wo(process.env.DATA_DIR)):Ho,me=E.join(z,"collected-profiles"),pe=E.join(z,"market-research"),U=E.join(z,".schema-version"),Qt=[E.join(me,".schema-version"),E.join(pe,".schema-version")],le=4,oe=[{version:1,module:et},{version:2,module:tt},{version:3,module:nt},{version:4,module:ot}];(function(){oe.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of oe){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=oe.length?oe[oe.length-1].version:0;if(n!==le)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${le}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<oe.length;o++){let r=o+1;if(oe[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${oe[o].version}`)}})();function tn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
249
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let y=_t(g.profileUrl);if(y==="pending"||y==="connected"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${y})`),y==="pending"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,s&&await s(g,d,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl}`);let h=null;if(i){let p=await to(e,g.profileUrl);p?(je(g.profileUrl,{...p,source:a}),d.viewed++,h={success:!0,reason:"viewed",connectionSent:!1,profileInfo:p,resolvedUrl:p.resolvedUrl}):(d.errors++,h={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=l){console.log(` Max connections per session (${l}) reached`);break}let p=Ge();if(!p.allowed){console.log(` \u26A0 Global quota exhausted: ${p.reason}`);break}if(h=await ro(e,g.profileUrl,{message:o,useCustomMessage:r,excludeLocations:u,source:a,skipQuotaGate:!0}),h.success)d.connectionsSent++;else switch(h.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(h?.fatal){console.log(`
250
+ \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(h?.reason==="error"){if(f++,f>=3){console.log(`
251
+ \u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(h&&h.reason&&(Rt(g.profileUrl,h.reason,{method:h.method,messageSent:h.messageSent,profileInfo:h.profileInfo}),h.resolvedUrl&&Ot(g.profileUrl,h.resolvedUrl),Dt(g.profileUrl,{source:a||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:h.reason})),s&&await s(g,d,h),m<t.length-1){let p=c+Math.random()*2e3;await b(p)}}if(console.log(`
252
+ === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!i){let m=Ke();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return d}import"dotenv/config";import*as q from"fs";import*as ne from"path";import{fileURLToPath as io}from"url";var lo=io(import.meta.url),ao=ne.dirname(ne.dirname(lo)),De=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(ao,"collected-profiles");function Qe(){q.existsSync(De)||q.mkdirSync(De,{recursive:!0})}function co(){return new Date().toISOString().split("T")[0]}function Bt(e,t=null){let n=t||co();return ne.join(De,`${e}-${n}.json`)}function Ut(e,t=null){Qe();let n=Bt(e,t);try{if(q.existsSync(n)){let o=q.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function Jt(e,t=null){return Ut(e,t).filter(o=>!o.processed)}function Vt(e,t,n,o=null){Qe();let r=Bt(e,o);try{if(!q.existsSync(r))return;let l=JSON.parse(q.readFileSync(r,"utf-8")),i=l.profiles.find(c=>c.profileUrl===t);if(i){if(i.processed=!0,i.processedAt=new Date().toISOString(),typeof n=="string")i.status=n;else if(typeof n=="object"){if(i.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(i.name=c.name),c.title&&(i.title=c.title),c.location&&(i.location=c.location),c.company&&(i.company=c.company),c.connectionDegree&&(i.connectionDegree=c.connectionDegree),c.connectionsCount&&(i.connectionsCount=c.connectionsCount),c.mutualConnections&&(i.mutualConnections=c.mutualConnections),c.photoUrl&&(i.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(i.hasVerifiedBadge=c.hasVerifiedBadge)}i.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}l.lastUpdated=new Date().toISOString(),q.writeFileSync(r,JSON.stringify(l,null,2))}}catch(l){console.error("Error marking profile processed:",l.message)}}function Ht(e){let t=Ut(e),n=t.filter(r=>r.processed),o=t.filter(r=>!r.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((r,l)=>(r[l.status]=(r[l.status]||0)+1,r),{})}}function Wt(){Qe();try{return q.readdirSync(De).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(q.readFileSync(ne.join(De,t),"utf-8"));return{file:t,source:n,date:o,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(l=>!l.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as w from"fs";import*as st from"os";import*as I from"path";import{fileURLToPath as Uo}from"url";var et={};ke(et,{NAME:()=>fo,VERSION:()=>uo,up:()=>ho});import*as V from"fs";import*as Me from"path";var uo=1,fo="normalize-jobs-and-questions",mo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],po=50;function Ze(e){return V.existsSync(e)?JSON.parse(V.readFileSync(e,"utf-8")):null}function Xe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{V.writeFileSync(o,n)}catch(r){try{V.unlinkSync(o)}catch{}throw r}try{V.renameSync(o,e)}catch(r){try{V.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function ho(e,t){let n=Me.join(e,"jobs.json"),o=Me.join(t,"scouted-jobs.json"),r=Me.join(e,"application-questions.json"),l=Ze(n)||{},i=Ze(o)||{},c=0,s=[];for(let a of Object.keys(l)){if(!i[a])continue;let d=i[a],f=l[a];for(let m of mo)d[m]!=null&&f[m]==null&&(f[m]=d[m]);s.push(a),c++}c>0?(Xe(n,l),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Ze(r);if(u&&Array.isArray(u.applications)){let a={},d=0;for(let f of u.applications){let m=f.jobId||"unknown";a[m]||(a[m]={applications:[]});let g=(f.questions||[]).map(y=>{let h={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=po?h.options=y.options:(h.optionsOmitted=!0,d++)),y.page&&(h.page=y.page),y.wasPreFilled&&(h.wasPreFilled=!0),y.wasRetry&&(h.wasRetry=!0),h});a[m].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||g.length,questions:g})}Xe(r,a),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(s.length>0){for(let a of s)delete i[a];Xe(o,i),console.log(` Phase 3: Removed ${s.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 tt={};ke(tt,{NAME:()=>yo,VERSION:()=>go,up:()=>bo});import*as H from"fs";import*as Yt from"path";var go=2,yo="reset-unread-flags";function wo(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function So(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(r){try{H.unlinkSync(o)}catch{}throw r}try{H.renameSync(o,e)}catch(r){try{H.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function bo(e){let t=Yt.join(e,"conversations.json"),n=wo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}So(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var nt={};ke(nt,{NAME:()=>ko,VERSION:()=>vo,up:()=>Ao});import*as W from"fs";import*as Gt from"path";var vo=3,ko="recompute-last-message-by",Co=new Set(["draft","confirmed","rejected","needs_review"]);function $o(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function xo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(r){try{W.unlinkSync(o)}catch{}throw r}try{W.renameSync(o,e)}catch(r){try{W.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}function Eo(e,t){if(!e||e.length===0)return"them";let n=e.filter(l=>!Co.has(l.status));if(n.length===0)return"them";let o=n.map(l=>({m:l,t:Date.parse(l.time)})).filter(l=>Number.isFinite(l.t)).sort((l,i)=>i.t-l.t).map(l=>l.m),r=o.length>0?o:[...n].reverse();for(let l of r){let i=l.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Ao(e){let t=Gt.join(e,"conversations.json"),n=$o(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,l=0,i=0;for(let c of Object.keys(n)){let s=n[c];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,l++);let u=Array.isArray(s.messages)?s.messages:[],a=Eo(u,o),d=a==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==a&&i++,s.lastMessageBy=a,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}xo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),l>0&&console.log(` Cleaned ${l} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var ot={};ke(ot,{NAME:()=>Do,VERSION:()=>Io,up:()=>To});import*as Y from"fs";import*as Kt from"path";var Io=4,Do="split-connection-timestamps",_o=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ro(e){if(!Y.existsSync(e))return null;let t=Y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Oo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function To(e){let t=Kt.join(e,"people.json"),n=Ro(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let l of Object.keys(n)){let i=n[l];!i||typeof i!="object"||(r++,_o.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Oo(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as U from"path";import{fileURLToPath as No}from"url";var jo=No(import.meta.url),Fo=U.dirname(U.dirname(jo)),_e=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(Fo,"market-research"),Wr=U.join(_e,"scouted-jobs.json"),Yr=U.join(_e,"discovered-people.json"),Gr=U.join(_e,"visit-log.json"),Kr=U.join(_e,"companies.json"),zr=U.join(_e,"job-decisions.json");function zt(){Lo=null,Mo=null,Po=null,qo=null,Bo=null}var Lo=null;var Mo=null;var Po=null;var qo=null;var Bo=null;var Jo=Uo(import.meta.url),Vo=I.dirname(Jo),Ho=I.dirname(I.dirname(Vo));function Wo(e){return e&&(e==="~"?st.homedir():e.startsWith("~/")||e.startsWith("~\\")?I.join(st.homedir(),e.slice(2)):e)}var z=process.env.DATA_DIR?I.resolve(Wo(process.env.DATA_DIR)):Ho,me=I.join(z,"collected-profiles"),pe=I.join(z,"market-research"),B=I.join(z,".schema-version"),Qt=[I.join(me,".schema-version"),I.join(pe,".schema-version")],le=4,oe=[{version:1,module:et},{version:2,module:tt},{version:3,module:nt},{version:4,module:ot}];(function(){oe.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of oe){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=oe.length?oe[oe.length-1].version:0;if(n!==le)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${le}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<oe.length;o++){let r=o+1;if(oe[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${oe[o].version}`)}})();function tn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
253
253
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
254
254
  `),process.exit(1));try{w.mkdirSync(z,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
255
  [FATAL] Cannot create DATA_DIR (${z}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -259,19 +259,19 @@ ${o.join(`
259
259
  [FATAL] DATA_DIR (${z}) 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.
260
260
  `),process.exit(1));for(let t of[me,pe]){let n;try{n=w.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
261
261
  [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.
262
- `),process.exit(1))}}var fe=E.join(z,".migration-lock");function Yo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return w.writeFileSync(fe,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(w.readFileSync(fe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,l=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(l=Date.now()-i)}o&&l<r&&(console.error(`
262
+ `),process.exit(1))}}var fe=I.join(z,".migration-lock");function Yo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return w.writeFileSync(fe,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(w.readFileSync(fe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,l=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(l=Date.now()-i)}o&&l<r&&(console.error(`
263
263
  [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${fe}
264
264
  `),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.
265
- `),process.exit(1)),o&&l>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=fe+".tmp";try{return w.writeFileSync(n,e),w.renameSync(n,fe),!0}catch(o){try{w.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function it(){try{if(JSON.parse(w.readFileSync(fe,"utf-8")).pid!==process.pid)return;w.unlinkSync(fe)}catch{}}var Zt=!1;function Go(){if(Zt)return;Zt=!0;let e=()=>{try{it()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ko(){if(w.existsSync(U))return;let e=[],t=[];for(let l of Qt)if(w.existsSync(l))try{e.push({file:l,schema:Pe(l)})}catch(i){t.push({file:l,err:i.message})}if(t.length>0){console.error(`
265
+ `),process.exit(1)),o&&l>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=fe+".tmp";try{return w.writeFileSync(n,e),w.renameSync(n,fe),!0}catch(o){try{w.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function it(){try{if(JSON.parse(w.readFileSync(fe,"utf-8")).pid!==process.pid)return;w.unlinkSync(fe)}catch{}}var Zt=!1;function Go(){if(Zt)return;Zt=!0;let e=()=>{try{it()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ko(){if(w.existsSync(B))return;let e=[],t=[];for(let l of Qt)if(w.existsSync(l))try{e.push({file:l,schema:Pe(l)})}catch(i){t.push({file:l,err:i.message})}if(t.length>0){console.error(`
266
266
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let l of t)console.error(` ${l.file}: ${l.err}`);console.error(`
267
267
  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.
268
268
  `),process.exit(1)}if(e.length===0)return;let n=e.map(l=>l.schema.version);if(new Set(n).size>1){console.error(`
269
269
  [FATAL] Legacy .schema-version files disagree:`);for(let l of e)console.error(` ${l.file}: v${l.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.
270
- `),process.exit(1)}let o=e[0].schema,r=U+".tmp";try{w.writeFileSync(r,JSON.stringify(o,null,2)),w.renameSync(r,U)}catch(l){try{w.unlinkSync(r)}catch{}throw l}for(let l of Qt)if(w.existsSync(l))try{w.unlinkSync(l)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${U}`)}function zo(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 Pe(e){let t=w.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Xt(){if(Ko(),!w.existsSync(U))return{version:0,migrations:[]};let e;try{e=Pe(U)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
271
- [FATAL] ${U} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
270
+ `),process.exit(1)}let o=e[0].schema,r=B+".tmp";try{w.writeFileSync(r,JSON.stringify(o,null,2)),w.renameSync(r,B)}catch(l){try{w.unlinkSync(r)}catch{}throw l}for(let l of Qt)if(w.existsSync(l))try{w.unlinkSync(l)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${B}`)}function zo(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 Pe(e){let t=w.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Xt(){if(Ko(),!w.existsSync(B))return{version:0,migrations:[]};let e;try{e=Pe(B)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
271
+ [FATAL] ${B} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
272
272
  `),process.exit(1)}let t=zo(e);return t===null&&(console.error(`
273
- [FATAL] ${U} 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.
274
- `),process.exit(1)),t}function nn(e){try{w.chmodSync(e,384)}catch{}}function Qo(e){if(tn(),w.existsSync(U))try{if(w.lstatSync(U).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${U}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=U+".tmp";try{w.writeFileSync(t,JSON.stringify(e,null,2)),nn(t),w.renameSync(t,U)}catch(n){try{w.unlinkSync(t)}catch{}throw n}}function en(e,t){if(!w.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=w.readdirSync(e).filter(c=>{let s=c.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return w.statSync(E.join(e,c)).isFile()}catch{return!1}}),r=0,l=0,i=[];for(let c of o){let s=E.join(e,c),u=E.join(e,c+n);if(w.existsSync(u)){l++;continue}try{rn(s,u),r++}catch(a){i.push({file:c,err:a.message})}}if(i.length>0){let c=new Error(`Failed to back up ${i.length} file(s) in ${E.basename(e)}/: `+i.map(s=>`${s.file} (${s.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||l>0){let c=l>0?` (${l} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${E.basename(e)}/ (${n})${c}`)}}var rt=!1;async function on(){if(rt)return;tn(),nr();let t=Xt().version;if(t===le){rt=!0;return}Go(),Yo(),process.on("exit",it),t>le&&(console.error(`
273
+ [FATAL] ${B} 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.
274
+ `),process.exit(1)),t}function nn(e){try{w.chmodSync(e,384)}catch{}}function Qo(e){if(tn(),w.existsSync(B))try{if(w.lstatSync(B).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${B}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=B+".tmp";try{w.writeFileSync(t,JSON.stringify(e,null,2)),nn(t),w.renameSync(t,B)}catch(n){try{w.unlinkSync(t)}catch{}throw n}}function en(e,t){if(!w.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=w.readdirSync(e).filter(c=>{let s=c.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return w.statSync(I.join(e,c)).isFile()}catch{return!1}}),r=0,l=0,i=[];for(let c of o){let s=I.join(e,c),u=I.join(e,c+n);if(w.existsSync(u)){l++;continue}try{rn(s,u),r++}catch(a){i.push({file:c,err:a.message})}}if(i.length>0){let c=new Error(`Failed to back up ${i.length} file(s) in ${I.basename(e)}/: `+i.map(s=>`${s.file} (${s.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||l>0){let c=l>0?` (${l} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${I.basename(e)}/ (${n})${c}`)}}var rt=!1;async function on(){if(rt)return;tn(),nr();let t=Xt().version;if(t===le){rt=!0;return}Go(),Yo(),process.on("exit",it),t>le&&(console.error(`
275
275
  [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${le}.`),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.
276
276
  `),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${le}.
277
277
  `),process.exit(1)),console.log(`
@@ -287,9 +287,9 @@ ${o.join(`
287
287
  `))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
288
288
  `)}process.exit(1)}try{let s=new Date().toISOString(),u={version:r.version,name:c.NAME||l,appliedAt:s},a=Xt();a.version=r.version,a.migratedAt=s,a.migrations=a.migrations||[],a.migrations.push(u),Qo(a)}catch(s){console.error(`
289
289
  [FATAL] Migration ${l} applied successfully but schema version file could NOT be updated: ${s.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${l}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
290
- `),process.exit(1)}console.log(` \u2713 Migration ${l} complete`)}try{Et()}catch{}try{zt()}catch{}rt=!0,it(),console.log(`
290
+ `),process.exit(1)}console.log(` \u2713 Migration ${l} complete`)}try{At()}catch{}try{zt()}catch{}rt=!0,it(),console.log(`
291
291
  \u2713 Schema is now at v${le}
292
- `)}var Zo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Xo(e){let t=e.toLowerCase();return Zo.some(n=>n.test(t))}var er=6e4;function tr(){let e=Date.now(),t=[];for(let n of[z,me,pe]){if(!w.existsSync(n))continue;let o;try{o=w.readdirSync(n)}catch{continue}for(let r of o){if(!Xo(r))continue;let l=E.join(n,r);try{let i=w.statSync(l);if(!i.isFile()||e-i.mtimeMs<er)continue;t.push({dir:n,file:r,fullPath:l})}catch{}}}return t}function nr({verbose:e=!1}={}){let t=tr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{w.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${E.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function or(){let e=[];for(let t of[me,pe]){if(!w.existsSync(t))continue;let n=w.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=E.join(t,o);try{Pe(r)}catch(l){e.push({dir:E.basename(t),file:o,err:l.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function rr(e){let t=[],n=[];for(let l of[me,pe]){if(!w.existsSync(l))continue;let i=w.readdirSync(l).filter(c=>c.endsWith(e));for(let c of i){let s=E.join(l,c),u=c.slice(0,-e.length),a=E.join(l,u);try{u.toLowerCase().endsWith(".json")?Pe(s):w.accessSync(s,w.constants.R_OK),t.push({backupPath:s,originalPath:a,fileName:c,dir:l})}catch(d){n.push(`${E.basename(l)}/${c}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:l,originalPath:i,fileName:c,dir:s}of t)try{rn(l,i),o++}catch(u){r.push(`${E.basename(s)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function rn(e,t){let n=t+".tmp";try{w.copyFileSync(e,n),nn(n)}catch(o){try{w.unlinkSync(n)}catch{}throw o}try{w.renameSync(n,t)}catch(o){try{w.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}import Q from"fs";import ae from"path";var sr="cookies.json";function sn(){let e=process.env.ILML_SCOPE_DIR;return e?ae.join(e,"plugins-state","linkedin","cookies.json"):sr}function ln(){let e=sn();if(!Q.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Q.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function an(){return Q.existsSync(sn())}function ir(){let e=process.env.ILML_SCOPE_DIR;return e?ae.join(e,"plugins-state","linkedin"):"."}function cn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function lr(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?cn(t[1]):"default"}function un(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Q.existsSync(t)||Q.mkdirSync(t,{recursive:!0}),ae.resolve(t);let n=cn(e||lr()),o=ae.join(ir(),"chrome-profile",n);return Q.existsSync(o)||Q.mkdirSync(o,{recursive:!0}),ae.resolve(o)}var dn=".ilml-seeded";function fn(e){return!Q.existsSync(ae.join(e,dn))}function mn(e){try{Q.writeFileSync(ae.join(e,dn),new Date().toISOString())}catch{}}function pn(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Q.rmSync(ae.join(e,n),{force:!0}),t++}catch{}return t}var ar={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function hn(e,t={}){let n=un(),o={...ar,...t,userDataDir:n},r;try{r=await e.launch(o)}catch{pn(n);try{r=await e.launch(o)}catch(i){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${i.message})`)}}return{browser:r,profileDir:n,needsSeed:fn(n)}}async function gn(e,t){if(!t||!t.needsSeed)return!1;if(!an())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...ln()),mn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await on();function ur(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function dr(){let e=ur();if(e.list){console.log(`
292
+ `)}var Zo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Xo(e){let t=e.toLowerCase();return Zo.some(n=>n.test(t))}var er=6e4;function tr(){let e=Date.now(),t=[];for(let n of[z,me,pe]){if(!w.existsSync(n))continue;let o;try{o=w.readdirSync(n)}catch{continue}for(let r of o){if(!Xo(r))continue;let l=I.join(n,r);try{let i=w.statSync(l);if(!i.isFile()||e-i.mtimeMs<er)continue;t.push({dir:n,file:r,fullPath:l})}catch{}}}return t}function nr({verbose:e=!1}={}){let t=tr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{w.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${I.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function or(){let e=[];for(let t of[me,pe]){if(!w.existsSync(t))continue;let n=w.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=I.join(t,o);try{Pe(r)}catch(l){e.push({dir:I.basename(t),file:o,err:l.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function rr(e){let t=[],n=[];for(let l of[me,pe]){if(!w.existsSync(l))continue;let i=w.readdirSync(l).filter(c=>c.endsWith(e));for(let c of i){let s=I.join(l,c),u=c.slice(0,-e.length),a=I.join(l,u);try{u.toLowerCase().endsWith(".json")?Pe(s):w.accessSync(s,w.constants.R_OK),t.push({backupPath:s,originalPath:a,fileName:c,dir:l})}catch(d){n.push(`${I.basename(l)}/${c}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:l,originalPath:i,fileName:c,dir:s}of t)try{rn(l,i),o++}catch(u){r.push(`${I.basename(s)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function rn(e,t){let n=t+".tmp";try{w.copyFileSync(e,n),nn(n)}catch(o){try{w.unlinkSync(n)}catch{}throw o}try{w.renameSync(n,t)}catch(o){try{w.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}import Q from"fs";import ae from"path";var sr="cookies.json";function sn(){let e=process.env.ILML_SCOPE_DIR;return e?ae.join(e,"plugins-state","linkedin","cookies.json"):sr}function ln(){let e=sn();if(!Q.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Q.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function an(){return Q.existsSync(sn())}function ir(){let e=process.env.ILML_SCOPE_DIR;return e?ae.join(e,"plugins-state","linkedin"):"."}function cn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function lr(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?cn(t[1]):"default"}function un(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Q.existsSync(t)||Q.mkdirSync(t,{recursive:!0}),ae.resolve(t);let n=cn(e||lr()),o=ae.join(ir(),"chrome-profile",n);return Q.existsSync(o)||Q.mkdirSync(o,{recursive:!0}),ae.resolve(o)}var dn=".ilml-seeded";function fn(e){return!Q.existsSync(ae.join(e,dn))}function mn(e){try{Q.writeFileSync(ae.join(e,dn),new Date().toISOString())}catch{}}function pn(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Q.rmSync(ae.join(e,n),{force:!0}),t++}catch{}return t}var ar={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function hn(e,t={}){let n=un(),o={...ar,...t,userDataDir:n},r;try{r=await e.launch(o)}catch{pn(n);try{r=await e.launch(o)}catch(i){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${i.message})`)}}return{browser:r,profileDir:n,needsSeed:fn(n)}}async function gn(e,t){if(!t||!t.needsSeed)return!1;if(!an())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...ln()),mn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await on();function ur(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function dr(){let e=ur();if(e.list){console.log(`
293
293
  \u{1F4C2} Available profile files:
294
294
  `);let u=Wt();if(u.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let a of u)console.log(` ${a.file}`),console.log(` Total: ${a.count}, Unprocessed: ${a.unprocessed}`);console.log(""),process.exit(0)}console.log(`
295
295
  ========================================`),console.log("Profile Funnel Runner"),console.log(`========================================