ilml-plugin-linkedin 1.20.21 → 1.20.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/syncAll.mjs CHANGED
@@ -1,10 +1,11 @@
1
- var Zs=Object.defineProperty;var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{for(var n in t)Zs(e,n,{get:t[n],enumerable:!0})};import Y from"fs";import fe from"path";function Gt(){let e=process.env.ILML_SCOPE_DIR;return e?fe.join(e,"plugins-state","linkedin","cookies.json"):er}function tr(){let e=Gt(),t=fe.dirname(e);return t&&t!=="."&&!Y.existsSync(t)&&Y.mkdirSync(t,{recursive:!0}),e}function Qn(e){let t=tr();return Y.writeFileSync(t,JSON.stringify(e)),t}function xt(){let e=Gt();if(!Y.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Y.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 Xn(){return Y.existsSync(Gt())}function nr(){let e=process.env.ILML_SCOPE_DIR;return e?fe.join(e,"plugins-state","linkedin"):"."}function Zn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function or(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Zn(t[1]):"default"}function eo(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),fe.resolve(t);let n=Zn(e||or()),o=fe.join(nr(),"chrome-profile",n);return Y.existsSync(o)||Y.mkdirSync(o,{recursive:!0}),fe.resolve(o)}function no(e){return!Y.existsSync(fe.join(e,to))}function oo(e){try{Y.writeFileSync(fe.join(e,to),new Date().toISOString())}catch{}}function so(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Y.rmSync(fe.join(e,n),{force:!0}),t++}catch{}return t}var er,to,et=Z(()=>{er="cookies.json";to=".ilml-seeded"});function tt(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function Qt(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let c=tt(n),a=new Date(t);return c?a.setHours(c.hours,c.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let c=sr[o[1].toLowerCase()],a=tt(o[2]||""),l=new Date(t),f=l.getDay()-c;return f<=0&&(f+=7),l.setDate(l.getDate()-f),a?l.setHours(a.hours,a.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let c=Kt[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(s[2],10),l=parseInt(s[3],10),u=tt(s[4]||"");return new Date(l,c,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let c=Kt[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(i[2],10),l=tt(i[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(r){let c=Kt[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(r[2],10),l=tt(r[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function rr(e,t,{timeout:n=45e3,poll:o=1e3,label:s="page"}={}){let i=Date.now();for(;Date.now()-i<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${s})`),!0}}catch{}await new Promise(r=>setTimeout(r,o))}return!1}function Tt(e){return io.test(e||"")}async function zt(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),s=o?t:Math.min(t,45e3),i=Date.now(),r=!1;for(;Date.now()-i<s;){let a="wait";try{a=await e.evaluate(l=>!new RegExp(l).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",io.source)}catch{}if(a==="in"){try{let l=await e.cookies();if(Array.isArray(l)&&l.some(f=>f.name==="li_at")){let f=Qn(l);console.log(` \u2713 Session recovered \u2014 re-saved ${l.length} cookies (${f}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(l){console.log(` \u2713 Session recovered (cookie re-save skipped: ${l.message}).`)}return!0}if(a==="creds"){if(!o){let l=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}r||(r=!0,console.log(`
1
+ var sr=Object.defineProperty;var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)sr(e,n,{get:t[n],enumerable:!0})};import G from"fs";import me from"path";function Qt(){let e=process.env.ILML_SCOPE_DIR;return e?me.join(e,"plugins-state","linkedin","cookies.json"):rr}function ir(){let e=Qt(),t=me.dirname(e);return t&&t!=="."&&!G.existsSync(t)&&G.mkdirSync(t,{recursive:!0}),e}function to(e){let t=ir();return G.writeFileSync(t,JSON.stringify(e)),t}function It(){let e=Qt();if(!G.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=G.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 no(){return G.existsSync(Qt())}function ar(){let e=process.env.ILML_SCOPE_DIR;return e?me.join(e,"plugins-state","linkedin"):"."}function oo(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]?oo(t[1]):"default"}function so(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return G.existsSync(t)||G.mkdirSync(t,{recursive:!0}),me.resolve(t);let n=oo(e||lr()),o=me.join(ar(),"chrome-profile",n);return G.existsSync(o)||G.mkdirSync(o,{recursive:!0}),me.resolve(o)}function io(e){return!G.existsSync(me.join(e,ro))}function ao(e){try{G.writeFileSync(me.join(e,ro),new Date().toISOString())}catch{}}function lo(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{G.rmSync(me.join(e,n),{force:!0}),t++}catch{}return t}var rr,ro,nt=Z(()=>{rr="cookies.json";ro=".ilml-seeded"});function ot(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function en(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let c=ot(n),a=new Date(t);return c?a.setHours(c.hours,c.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let c=cr[o[1].toLowerCase()],a=ot(o[2]||""),l=new Date(t),f=l.getDay()-c;return f<=0&&(f+=7),l.setDate(l.getDate()-f),a?l.setHours(a.hours,a.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let c=Xt[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(s[2],10),l=parseInt(s[3],10),u=ot(s[4]||"");return new Date(l,c,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let c=Xt[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(i[2],10),l=ot(i[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(r){let c=Xt[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(r[2],10),l=ot(r[3]||""),u=t.getFullYear(),f=new Date(u,c,a,l?.hours||0,l?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ur(e,t,{timeout:n=45e3,poll:o=1e3,label:s="page"}={}){let i=Date.now();for(;Date.now()-i<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${s})`),!0}}catch{}await new Promise(r=>setTimeout(r,o))}return!1}function Dt(e){return uo.test(e||"")}async function Zt(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),s=o?t:Math.min(t,45e3),i=Date.now(),r=!1;for(;Date.now()-i<s;){let a="wait";try{a=await e.evaluate(l=>!new RegExp(l).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",uo.source)}catch{}if(a==="in"){try{let l=await e.cookies();if(Array.isArray(l)&&l.some(f=>f.name==="li_at")){let f=to(l);console.log(` \u2713 Session recovered \u2014 re-saved ${l.length} cookies (${f}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(l){console.log(` \u2713 Session recovered (cookie re-save skipped: ${l.message}).`)}return!0}if(a==="creds"){if(!o){let l=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}r||(r=!0,console.log(`
2
2
  \u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
3
- `))}await new Promise(l=>setTimeout(l,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function ro(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let s=await rr(e,t,{timeout:o,label:n});if(!s&&Tt(e.url())){let i=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return s}async function we(e,t,{readySelector:n,label:o="page",timeout:s=45e3,gotoTimeout:i=6e4,autoRecover:r=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:i});try{return await ro(e,{readySelector:n,label:o,timeout:s})}catch(c){if(r&&c.code==="SESSION_EXPIRED"){await zt(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:i})}catch{}return await ro(e,{readySelector:n,label:o,timeout:s})}throw c}}async function ao(e){let t=e.url();if(t.includes("/messaging"))return!1;if(Tt(t)?await zt(e,{label:"inbox"}):console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3),Tt(e.url())&&(await zt(e,{label:"inbox"}),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),Tt(e.url())))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function Ee(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),r=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),c=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||r||c){let a=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:s.substring(0,80)};let l=o.querySelectorAll("button");for(let u of l){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:s.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})}function lo(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function co(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var Kt,sr,io,Fe=Z(()=>{et();Kt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},sr={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};io=/\/authwall|\/login|\/checkpoint|\/uas\/login/});function ar(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function fo(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let s=(e.JOB_SEARCH_GEO_ID||"").trim();s&&n.set("geoId",s);let i=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(i)&&i>0&&n.set("distance",String(i)),uo(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),uo(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let r=ar(e.JOB_SEARCH_COMPANY_IDS);r.length&&n.set("f_C",r.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&n.set("f_TPR",ir[c]||c),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let a="https://www.linkedin.com/jobs/search/?"+n.toString(),l=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return l&&(a+="&"+l),a}var ir,uo,mo=Z(()=>{ir={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},uo=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as lr}from"@ilivemylife/graph-sdk";var cr,po,z,V,nt,Ue,ot=Z(async()=>{mo();cr=await lr();for(let[e,t]of Object.entries(cr))process.env[e]===void 0&&(process.env[e]=t);po=fo(process.env);po&&(process.env.LINKEDIN_SEARCH_URL=po);z=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),nt=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Ue=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as F from"fs";import*as B from"path";import{fileURLToPath as ur}from"url";import{execSync as Xt}from"child_process";function ko(){qe=null,mr=null,me=null,xe=null,Be=null,Ae=null}function pe(){F.existsSync(ee)||F.mkdirSync(ee,{recursive:!0})}function Je(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";F.writeFileSync(o,n);for(let s=0;s<3;s++)try{F.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function it(e,t){if(!F.existsSync(e))return null;try{let n=JSON.parse(F.readFileSync(e,"utf-8"));try{F.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(F.existsSync(o))try{let s=JSON.parse(F.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{F.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function at(){return new Date().toISOString().split("T")[0]}function Te(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function go(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function He(e,t,n=null){if(!t||e[t])return t;let o=Te(t);if(!o)return t;let s=null;for(let[i,r]of Object.entries(e)){if(Te(r.profileUrl||i)===o)return i;!s&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}if(s){let i=go(n),r=go(e[s].name);if(i&&r&&i===r)return s}return t}function gr(){F.existsSync(en)||F.mkdirSync(en,{recursive:!0})}function $o(e){let t=Te(e);return t?B.join(en,`${t}.json`):null}function yr(e){let t=$o(e);return t?it(t,`profile-history/${Te(e)}.json`)||[]:[]}function wr(e,t){let n=$o(e);if(!n)return;gr();let o=yr(e);o.unshift(t);try{Je(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Te(e)}: ${s.message}`)}}function yo(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function wo(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function br(e,t){if(!e)return[];let n=[];for(let o of hr){let s=e[o],i=t[o];yo(s)||yo(i)||wo(s)!==wo(i)&&n.push(o)}return n}function Sr(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function J(){return qe||(pe(),qe=it(Zt,"people.json")||{},qe)}function Ie(e){pe(),qe=e;try{Je(Zt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(Zt)}`)}}function lt(){return xe||(pe(),xe=it(Rt,"conversations.json")||{},vr(xe),xe)}function vr(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(i=>i.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Je(Rt,e)}catch{}}}function be(e){pe(),xe=e;try{Je(Rt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(Rt)}`)}}function Re(e,t={}){if(!e)return null;let n=J(),o=at(),s=new Date().toISOString(),i=He(n,e,t.name),r=n[i];if(r){let c=br(r,t);c.length>0&&(wr(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:c,snapshot:Sr(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let a of pr)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(r[a])&&r[a].length>0)continue;r[a]=t[a]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[i]={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:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Ie(n),n[i]}function Co(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:at(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Ie(n))}function _o(e){return e&&J()[e]?.connectionStatus||null}function Eo(e,t,n={}){if(!e)return;if(n.profileInfo)Re(e,n.profileInfo);else{let c=J(),a=He(c,e,n.profileInfo?.name);c[a]||Re(e,{})}let o=J(),s=He(o,e,n.profileInfo?.name),i=o[s];if(!i)return;let r=at();i.connectionStatus=t,t==="connected"?i.connectionDate=r:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=r)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Ie(o)}function It(e,t,n={}){if(n.dryRun||!e||!t)return;let o=Te(t);if(!o)return;let s=J(),i=He(s,e),r=s[i];if(!r)return;let c=Te(r.profileUrl||i);o!==c&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(o)||(r.aliases.push(o),r.lastUpdated=new Date().toISOString(),Ie(s)))}function Ao(){return me||(pe(),me=it(bo,"quota.json"),(!me||!me.connections)&&(me={connections:[]}),me)}function kr(e){pe(),me=e;try{Je(bo,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function xo(e,t="unknown"){let n=Ao(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),kr(n)}function To(){let e=Ao(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function tn(){let e=To(),t=at(),n=e.filter(a=>a.date===t).length,o=e.length,s=n>=st,i=o>=rt,r=!s&&!i,c={allowed:r,daily:{sent:n,max:st},weekly:{sent:o,max:rt}};return r||(c.reason=s?`Daily limit reached (${n}/${st})`:`Weekly limit reached (${o}/${rt})`),c}function ct(){let e=To(),t=at(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:st,remaining:st-n},weekly:{sent:o,max:rt,remaining:rt-o}}}function nn(){return Be||(pe(),Be=it(So,"sync-state.json")||{},Be)}function Ro(e){pe(),Be=e;try{Je(So,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function $r(){if(Ae)return Ae;pe();try{F.existsSync(ho)&&(Ae=JSON.parse(F.readFileSync(ho,"utf-8")))}catch{}return Ae||(Ae={}),Ae}function Cr(e){return Array.isArray(e.applications)}function _r(){let e=$r();if(Cr(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function Io(){let e=_r(),t=new Map;for(let i of e)for(let r of i.questions||[]){let c=r.question.toLowerCase().trim();if(!c)continue;t.has(c)||t.set(c,{question:r.question,count:0,answers:new Map});let a=t.get(c);a.count++;let l=(r.answer||"").trim();a.answers.set(l,(a.answers.get(l)||0)+1)}let n=[...t.values()].sort((i,r)=>r.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((r,c)=>c[1]-r[1])[0]?.[0]||""})),s=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((r,c)=>c[1]-r[1]).map(([r,c])=>`${r} (${c}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function on(e){if(F.existsSync(B.join(ee,".git")))try{let t={cwd:ee,stdio:"pipe",timeout:1e4};Xt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{Xt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Xt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var dr,fr,ee,Zt,cl,bo,Rt,So,ho,en,vo,st,rt,qe,mr,me,xe,Be,Ae,pr,hr,Ve=Z(async()=>{await ot();dr=ur(import.meta.url),fr=B.dirname(B.dirname(dr)),ee=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(fr,"collected-profiles"),Zt=B.join(ee,"people.json"),cl=B.join(ee,"jobs.json"),bo=B.join(ee,"quota.json"),Rt=B.join(ee,"conversations.json"),So=B.join(ee,"sync-state.json"),ho=B.join(ee,"application-questions.json"),en=B.join(ee,"profile-history"),vo=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},st=vo(process.env.CONNECT_MAX_DAILY,20),rt=vo(process.env.CONNECT_MAX_WEEKLY,100),qe=null,mr=null,me=null,xe=null,Be=null,Ae=null;pr=["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"],hr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Mo={};ue(Mo,{BLOCK_MARKERS:()=>Do,dedupeAndCap:()=>No,extractSidePanelProfiles:()=>Er,normalizeFundUrl:()=>Dt,normalizeProfileUrl:()=>We,scanRelatedBlocks:()=>Oo});function We(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function Dt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Oo(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=l=>(l||"").replace(/\s+/g," ").trim(),s=l=>{let u=String(l||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=l=>o(l).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),r=l=>{let u=l,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))return u}return f||l.parentElement},c=[],a=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let l of a){let u=o(l.textContent).toLowerCase();if(!u)continue;let f=e.find(([b])=>u.includes(b));if(!f)continue;let d=f[1],m=r(l);if(!m)continue;let w=0,h=new Set;for(let b of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let y=b.href||b.getAttribute("href")||"",S=s(y);if(!S)continue;let g=b.querySelector('span[aria-hidden="true"]'),p=o(g?g.textContent:b.getAttribute("aria-label")||b.textContent),v=i(p);if(!v||h.has(S))continue;h.add(S);let C="",x=p.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(x&&(C=o(x[1])),!C){let R=b.closest("li")||b.parentElement;R&&(C=Array.from(R.querySelectorAll("p, span")).map(D=>o(D.textContent)).filter(D=>D&&D!==v&&!/^view\b/i.test(D)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(D)&&/[a-z]/i.test(D)&&D.length>2)[0]||"")}c.push({href:y,name:v,headline:C,block:d,rank:w++})}}return c}function No(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=We(t.seedUrl||""),s=new Map,i={};for(let r of e||[]){let c=We(r.href);c&&(o&&c===o||(i[r.block]=i[r.block]||0,!(i[r.block]>=n)&&(s.has(c)||(i[r.block]++,s.set(c,{url:c,name:r.name,headline:r.headline||null,block:r.block,rank:r.rank})))))}return Array.from(s.values())}async function Er(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(Oo,Do)}catch{return[]}return No(n,t)}var Do,sn=Z(()=>{Do=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var qo={};ue(qo,{getJobDecision:()=>Dr,getLastVisit:()=>Ur,getScoutStats:()=>un,loadCompanies:()=>cn,loadDiscoveredPeople:()=>yt,loadJobDecisions:()=>gt,loadScoutedJobs:()=>ht,loadVisitLog:()=>Mt,recordCompany:()=>jr,recordDiscoveredEdge:()=>Mr,recordDiscoveredEdges:()=>Pr,recordVisit:()=>Fr,resetCaches:()=>ln,saveCompany:()=>Lr,saveDiscoveredPerson:()=>Or,saveScoutedJob:()=>Rr,setJobDecision:()=>Ir});import"dotenv/config";import*as te from"fs";import*as Q from"path";import{fileURLToPath as Ar}from"url";function Se(){te.existsSync(Oe)||te.mkdirSync(Oe,{recursive:!0})}function ve(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";te.writeFileSync(o,n);for(let s=0;s<3;s++)try{te.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function pt(e){try{if(te.existsSync(e))return JSON.parse(te.readFileSync(e,"utf-8"))}catch{}return null}function ln(){ut=null,dt=null,ft=null,mt=null,De=null}function ht(){return ut||(ut=pt(Po)||{},ut)}function Rr(e,t){if(!e)return;Se();let n=ht(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[s,i]of Object.entries(t))i!=null&&(n[e][s]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{ve(Po,n)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function gt(){return dt||(dt=pt(Lo)||{},dt)}function Ir(e,t,n={}){if(!e||!t)return;Se();let o=gt(),s=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=s,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:s,updatedAt:s,reason:n.reason||null,score:n.score??null,source:n.source||null};try{ve(Lo,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Dr(e){return gt()[e]||null}function yt(){return ft||(ft=pt(Nt)||{},ft)}function Ye(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Fo(e,t){let n=We(t)||t;if(e[n])return n;let o=Ye(t);if(!o)return n;let s=null;for(let[i,r]of Object.entries(e)){if(Ye(r&&(r.canonicalUrl||r.profileUrl)||i)===o)return i;!s&&r&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}return s||n}function Or(e,t){if(!e)return;Se();let n=yt(),o=new Date().toISOString().slice(0,10),s=Fo(n,e),i=Ye(e);if(n[s]){let r=n[s];t.name&&(r.name=t.name),t.title&&(r.title=t.title),t.company&&(r.company=t.company),t.location&&(r.location=t.location),t.role&&(r.role=t.role),t.isConnected!=null&&(r.isConnected=t.isConnected),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),i&&Ye(r.canonicalUrl||r.profileUrl||s)!==i&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(i)||r.aliases.push(i)),r.lastSeen=o,r.seenCount=(r.seenCount||1)+1}else n[s]={canonicalUrl:s,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{ve(Nt,n)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function Nr(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function Uo(e,t,n={},o){if(!t)return;let s=Ye(t);t=Fo(e,t);let i=n.seedUrl?{...n,seedUrl:We(n.seedUrl)||n.seedUrl}:n,r=o.slice(0,10),{edge:c,match:a}=Nr(i,o),l=e[t];l||(l=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:r,firstSeen:r,lastSeen:r}),n.name&&(l.name=n.name),n.headline&&(!l.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(l.headline))&&(l.headline=n.headline),n.location&&(l.location=l.location||n.location),n.company&&(l.company=n.company),n.companyUrl&&(l.companyUrl=l.companyUrl||n.companyUrl),n.isConnected!=null&&(l.isConnected=n.isConnected),n.connectionsCount!=null&&(l.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(l.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(l.connectGate=n.connectGate),n.note&&!l.note&&(l.note=n.note),n.whyUseful&&!l.whyUseful&&(l.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(l.extra={...l.extra||{},...n.extra}),Array.isArray(l.sources)||(l.sources=[]);let u=l.sources.find(a);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):l.sources.push(c),Array.isArray(l.categories)||(l.categories=[]),Array.isArray(l.sectors)||(l.sectors=[]),Array.isArray(l.aliases)||(l.aliases=[]),Array.isArray(l.graphRefs)||(l.graphRefs=[]),rn(l.categories,n.category),Ot(l.categories,n.categories),Ot(l.sectors,n.sectors),Ot(l.aliases,n.aliases),s&&Ye(l.canonicalUrl||t)!==s&&rn(l.aliases,s),Ot(l.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(l.affiliations)||(l.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||l.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||l.affiliations.push(f)}l.lastSeen=r,l.seenCount=(l.seenCount||0)+1}function Mr(e,t={}){if(!e)return;Se();let n=yt();Uo(n,e,t,new Date().toISOString());try{ve(Nt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Pr(e){if(!Array.isArray(e)||e.length===0)return;Se();let t=yt(),n=new Date().toISOString(),o=0;for(let s of e)!s||!s.url||(Uo(t,s.url,s,n),o++);if(o)try{ve(Nt,t)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function jr(e={}){if(!e||!e.name)return;Se();let t=e.key||Dt(e.website)||Dt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=cn(),o=new Date().toISOString().slice(0,10),s=(a,l)=>{l&&Array.isArray(a)&&!a.includes(l)&&a.push(l)},i=(a,l)=>{if(Array.isArray(l))for(let u of l)s(a,u)},r=n[t];r||(r=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(r.name=e.name),e.website&&(r.website=r.website||e.website),e.linkedinUrl&&(r.linkedinUrl=r.linkedinUrl||e.linkedinUrl);for(let a of["size","check","stage","location","industries","about"])e[a]&&!r[a]&&(r[a]=e[a]);e.note&&!r.note&&(r.note=e.note),e.whyUseful&&!r.whyUseful&&(r.whyUseful=e.whyUseful),e.fitScore!=null&&(r.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(r.extra={...r.extra||{},...e.extra});for(let a of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(r[a])||(r[a]=[]),i(r[a],e[a]);Array.isArray(r.people)||(r.people=[]);let c=a=>{if(!a||!a.url)return;let l=r.people.find(u=>u.url===a.url&&(u.role||null)===(a.role||null));l?a.current!=null&&(l.current=a.current):r.people.push({url:a.url,name:a.name||null,role:a.role||null,current:a.current??null,from:a.from??null,to:a.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(a=>c({url:a.url,name:a.name,role:"Partner",current:!0})),Array.isArray(r.portfolio)||(r.portfolio=[]);for(let a of e.portfolio||[]){let l=a&&(a.key||a.name);l&&!r.portfolio.some(u=>(u.key||u.name)===l)&&r.portfolio.push(a)}r.lastSeen=o,r.seenCount=(r.seenCount||0)+1;try{ve(an,n)}catch(a){console.error(`[!] Failed to save companies.json: ${a.message}`)}return t}function cn(){return mt||(mt=pt(an)||{},mt)}function Lr(e,t){if(!e)return;Se();let n=cn(),o=new Date().toISOString().slice(0,10);if(n[e]){let s=n[e];t.name&&(s.name=t.name),t.about&&(s.about=t.about),t.size&&(s.size=t.size),t.industries&&(s.industries=t.industries),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),t.recruiterUrl&&(s.recruiterUrls||(s.recruiterUrls=[]),s.recruiterUrls.includes(t.recruiterUrl)||s.recruiterUrls.push(t.recruiterUrl)),s.lastSeen=o,s.jobCount=s.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{ve(an,n)}catch(s){console.error(`[!] Failed to save companies.json: ${s.message}`)}}function Mt(){return De||(De=pt(jo)||{visits:[]},Array.isArray(De.visits)||(De.visits=[]),De)}function Fr(e,t={}){if(!e)return;Se();let n=Mt();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(s=>new Date(s.date).getTime()>o);try{ve(jo,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function Ur(e){let t=Mt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function un(){let e=ht(),t=yt(),n=Object.values(e),o=Object.values(t),s={};for(let d of n)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),r={};for(let d of n)for(let m of d.techStack||[])r[m]=(r[m]||0)+1;let c=Object.entries(r).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),a=Mt(),l=new Date().toISOString().slice(0,10),u=a.visits.filter(d=>d.date.startsWith(l)).length,f=new Set(a.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var xr,Tr,Oe,Po,Nt,jo,an,Lo,ut,dt,ft,rn,Ot,mt,De,wt=Z(()=>{sn();xr=Ar(import.meta.url),Tr=Q.dirname(Q.dirname(xr)),Oe=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(Tr,"market-research"),Po=Q.join(Oe,"scouted-jobs.json"),Nt=Q.join(Oe,"discovered-people.json"),jo=Q.join(Oe,"visit-log.json"),an=Q.join(Oe,"companies.json"),Lo=Q.join(Oe,"job-decisions.json");ut=null;dt=null;ft=null;rn=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Ot=(e,t)=>{if(Array.isArray(t))for(let n of t)rn(e,n)};mt=null;De=null});var ms={};ue(ms,{computeEngagement:()=>Sn,detectCategory:()=>is,detectCategoryFromTitle:()=>Lt,determineAction:()=>ds,determineLastMessageBy:()=>Ut,determineSituation:()=>as,enrichConversation:()=>Ft,enrichPerson:()=>kn,enrichPersonContext:()=>fs,extractAutoTags:()=>cs,generateSummary:()=>ls,normPreview:()=>ze});function Ft(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(a=>!Ue.has(a.status)),i=ii(t,e.profileUrl,n),r=Ut(s,t);if(e.lastMessageBy=r,e.conversationStatus=r==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let a=is(s,t,i);a&&(e.category=a,e.categorySource=e.categorySource||"message_content")}if(e.situation=as(s,r,t),s.length>0){let a=s[s.length-1];e.lastMessageTime=a.time}if(s.length>0&&!e.initiatedBy){let a=s[0];a.sender===z?e.initiatedBy="us":a.sender!=="Unknown"&&a.sender!==""&&(e.initiatedBy="them")}e.engagement=Sn(s,t),e.personContext=fs(i),e.summary=ls(e,t,i),e.autoTags=cs(e,t,i);let c=ds(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=ri(e),e}function is(e,t,n){if(!e||e.length===0)return n?.title?Lt(n.title):null;let o=e.filter(s=>s.sender!==z&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,i]of Object.entries(rs))if(i.theirMessages){for(let r of i.theirMessages)if(r.test(o))return s}if(n?.title){let s=Lt(n.title);if(s)return s}return null}function Lt(e){if(!e)return null;for(let[t,n]of Object.entries(rs))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function as(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return ss.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(i=>i.sender!==z&&i.sender!=="Unknown");return ss.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Ut(e,t){if(!e||e.length===0)return"them";let n=[...e].map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),o=n.length>0?n:[...e].reverse();for(let s of o){let i=s.sender;if(i===z)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function ls(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,r=n?.title,c=n?.company,a=n?.location;i==="recruiter"&&c?s.push(`Recruiter from ${c}`):i==="hiring_manager"&&c?s.push(`Hiring manager at ${c}`):i==="founder"&&c?s.push(`Founder of ${c}`):i&&r?s.push(`${vn(i)}: ${Ke(r,40)}`):r?s.push(Ke(r,50)):s.push(t.split(" ")[0]);let l=o.filter(w=>w.sender!==z&&w.sender!=="Unknown").map(w=>w.text).join(" "),u=ai(l),f=li(l),d=ci(l),m=[];return u&&m.push(u),d&&d!==a&&m.push(d),f&&m.push(f),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function cs(e,t,n){let o=[],s=(e.messages||[]).filter(l=>!Ue.has(l.status)),i=s.map(l=>l.text).join(" "),r=s.filter(l=>l.sender!==z&&l.sender!=="Unknown").map(l=>l.text).join(" "),c=us(r,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let a=e.engagement||Sn(s,t);return a.messageCount>=6&&o.push("active-thread"),a.theirCount===0&&a.ourCount>0&&o.push("no-response"),a.ourCount===0&&a.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(l=>nt.has(l.status))&&o.push("has-draft"),[...new Set(o)]}function us(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let r of o)i.includes(r)&&n.push(r.replace(/\s+/g,"-"));for(let[r,c]of s)i.includes(r)&&n.push(c);return n}function ds(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&ze(e.lastMessagePreview)===ze(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(i=>nt.has(i.status));return s?s.status===V.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${vn(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Sn(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,s=0,i=!1,r=!1,c=e.map(a=>a.text).join(" ");for(let a of e)a.sender===z?n++:a.sender==="Unknown"||a.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(c),r=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:r}}function fs(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function ri(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function ii(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let s=He(n,t,e);if(n[s])return n[s]}if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function ze(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function vn(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ke(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function ai(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function li(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function ci(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function kn(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Lt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}ui(e),e.personSummary=di(e),e.personAutoTags=fi(e);let n=mi(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=pi(e)),e}function ui(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function di(e){let t=[],n=e.category,o=e.title,s=e.company,i=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${Ke(o,40)} at ${Ke(s,30)}`):o?t.push(Ke(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let r=new Date(e.connectionDate);if(!isNaN(r)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[r.getMonth()]} ${r.getDate()}`)}}if(e.jobCount>0){let r=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(r+=` (last: ${Ke(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(r+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}r+=")"}t.push(r)}return t.join(". ").replace(/\.\./g,".")||null}function fi(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=us("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function mi(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${vn(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function pi(e){let t=e.category;if(!t)return null;let n=hi(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function hi(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var rs,ss,$n=Z(async()=>{await ot();await Ve();rs={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};ss=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Is={};ue(Is,{extractCertificationsFromDetails:()=>Sa,extractEducationFromDetails:()=>wa,extractExperienceFromDetails:()=>ga,extractFeaturedFromDetails:()=>ya,extractRecommendationsFromDetails:()=>va,extractSkillsFromDetails:()=>ba});async function ga(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await we(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await k(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let r of document.querySelectorAll("button"))if(/^Load more$/i.test((r.textContent||"").trim()))return r.click(),!0;return!1});)s++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function r(u){let f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(h=>h.tagName==="DIV");if(m.length<3)continue;let w=m.filter(h=>(h.textContent||"").trim().length>50);w.length<3||(d.textContent||"").length<500||f.push({el:d,count:w.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let c=r(i);if(!c)return[];let a=Array.from(c.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function l(u){let f=u[0]||null,d=null,m=null;if(u[1]){let A=u[1].split("\xB7").map(D=>D.trim());d=A[0]||null,A[1]&&(m=A[1])}let w=u.findIndex(A=>/(\d{4}|present)/i.test(A)&&/(-|–|—)/i.test(A)&&A.length<80),h=null,b=null;if(w>=0){let A=u[w].split("\xB7").map(D=>D.trim());h=A[0]||null,A[1]&&(b=A[1])}let y=null,S=-1;if(w>=0&&u[w+1]){let A=u[w+1],D=/^[>*\-•]|^&gt;/.test(A),K=/https?:\/\//.test(A),$=/\d{4}/.test(A),_=/,/.test(A)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(A);!D&&!K&&!$&&A.length<100&&_&&(y=A,S=w+1)}let g=null,p=-1,v=u[u.length-1];if(v&&/and\s+\+\d+\s+skills?$/i.test(v)){p=u.length-1;let A=v.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);A&&(g={listed:A[1].split(",").map(D=>D.trim()),additional:parseInt(A[2],10)})}let C=new Set([0,1,w,S,p].filter(A=>A>=0)),x=u.filter((A,D)=>!C.has(D)),R=x.length>0?x.join(`
3
+ `))}await new Promise(l=>setTimeout(l,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function co(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let s=await ur(e,t,{timeout:o,label:n});if(!s&&Dt(e.url())){let i=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return s}async function be(e,t,{readySelector:n,label:o="page",timeout:s=45e3,gotoTimeout:i=6e4,autoRecover:r=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:i});try{return await co(e,{readySelector:n,label:o,timeout:s})}catch(c){if(r&&c.code==="SESSION_EXPIRED"){await Zt(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:i})}catch{}return await co(e,{readySelector:n,label:o,timeout:s})}throw c}}async function fo(e){let t=e.url();if(t.includes("/messaging"))return!1;if(Dt(t)?await Zt(e,{label:"inbox"}):console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3),Dt(e.url())&&(await Zt(e,{label:"inbox"}),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),Dt(e.url())))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function Ae(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),r=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),c=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||r||c){let a=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:s.substring(0,80)};let l=o.querySelectorAll("button");for(let u of l){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:s.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})}function mo(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function po(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var Xt,cr,uo,qe=Z(()=>{nt();Xt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},cr={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};uo=/\/authwall|\/login|\/checkpoint|\/uas\/login/});function fr(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function ho(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let s=(e.JOB_SEARCH_GEO_ID||"").trim();s&&n.set("geoId",s);let i=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(i)&&i>0&&n.set("distance",String(i)),go(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),go(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let r=fr(e.JOB_SEARCH_COMPANY_IDS);r.length&&n.set("f_C",r.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&n.set("f_TPR",dr[c]||c),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let a="https://www.linkedin.com/jobs/search/?"+n.toString(),l=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return l&&(a+="&"+l),a}var dr,go,yo=Z(()=>{dr={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},go=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as mr}from"@ilivemylife/graph-sdk";var pr,wo,K,W,st,Be,rt=Z(async()=>{yo();pr=await mr();for(let[e,t]of Object.entries(pr))process.env[e]===void 0&&(process.env[e]=t);wo=ho(process.env);wo&&(process.env.LINKEDIN_SEARCH_URL=wo);K=process.env.LINKEDIN_NAME,W=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),st=Object.freeze(new Set([W.DRAFT,W.CONFIRMED,W.NEEDS_REVIEW])),Be=Object.freeze(new Set([W.DRAFT,W.CONFIRMED,W.REJECTED,W.NEEDS_REVIEW]))});import"dotenv/config";import*as F from"fs";import*as B from"path";import{fileURLToPath as gr}from"url";import{execSync as tn}from"child_process";function Eo(){He=null,wr=null,pe=null,Re=null,Je=null,xe=null}function ge(){F.existsSync(te)||F.mkdirSync(te,{recursive:!0})}function We(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";F.writeFileSync(o,n);for(let s=0;s<3;s++)try{F.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function lt(e,t){if(!F.existsSync(e))return null;try{let n=JSON.parse(F.readFileSync(e,"utf-8"));try{F.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(F.existsSync(o))try{let s=JSON.parse(F.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{F.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function ct(){return new Date().toISOString().split("T")[0]}function Te(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function So(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Ve(e,t,n=null){if(!t||e[t])return t;let o=Te(t);if(!o)return t;let s=null;for(let[i,r]of Object.entries(e)){if(Te(r.profileUrl||i)===o)return i;!s&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}if(s){let i=So(n),r=So(e[s].name);if(i&&r&&i===r)return s}return t}function vr(){F.existsSync(on)||F.mkdirSync(on,{recursive:!0})}function Ao(e){let t=Te(e);return t?B.join(on,`${t}.json`):null}function kr(e){let t=Ao(e);return t?lt(t,`profile-history/${Te(e)}.json`)||[]:[]}function $r(e,t){let n=Ao(e);if(!n)return;vr();let o=kr(e);o.unshift(t);try{We(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Te(e)}: ${s.message}`)}}function vo(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function ko(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Cr(e,t){if(!e)return[];let n=[];for(let o of Sr){let s=e[o],i=t[o];vo(s)||vo(i)||ko(s)!==ko(i)&&n.push(o)}return n}function _r(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function V(){return He||(ge(),He=lt(nn,"people.json")||{},He)}function De(e){ge(),He=e;try{We(nn,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(nn)}`)}}function ut(){return Re||(ge(),Re=lt(Ot,"conversations.json")||{},Er(Re),Re)}function Er(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(i=>i.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{We(Ot,e)}catch{}}}function Se(e){ge(),Re=e;try{We(Ot,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(Ot)}`)}}function Ie(e,t={}){if(!e)return null;let n=V(),o=ct(),s=new Date().toISOString(),i=Ve(n,e,t.name),r=n[i];if(r){let c=Cr(r,t);c.length>0&&($r(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:c,snapshot:_r(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let a of br)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(r[a])&&r[a].length>0)continue;r[a]=t[a]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[i]={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:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return De(n),n[i]}function xo(e,t){if(!e||!t)return;let n=V(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:ct(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),De(n))}function Ro(e){return e&&V()[e]?.connectionStatus||null}function To(e,t,n={}){if(!e)return;if(n.profileInfo)Ie(e,n.profileInfo);else{let c=V(),a=Ve(c,e,n.profileInfo?.name);c[a]||Ie(e,{})}let o=V(),s=Ve(o,e,n.profileInfo?.name),i=o[s];if(!i)return;let r=ct();i.connectionStatus=t,t==="connected"?i.connectionDate=r:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=r)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),De(o)}function Nt(e,t,n={}){if(n.dryRun||!e||!t)return;let o=Te(t);if(!o)return;let s=V(),i=Ve(s,e),r=s[i];if(!r)return;let c=Te(r.profileUrl||i);o!==c&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(o)||(r.aliases.push(o),r.lastUpdated=new Date().toISOString(),De(s)))}function Io(){return pe||(ge(),pe=lt($o,"quota.json"),(!pe||!pe.connections)&&(pe={connections:[]}),pe)}function Ar(e){ge(),pe=e;try{We($o,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Do(e,t="unknown"){let n=Io(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Ar(n)}function Oo(){let e=Io(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function sn(){let e=Oo(),t=ct(),n=e.filter(a=>a.date===t).length,o=e.length,s=n>=it,i=o>=at,r=!s&&!i,c={allowed:r,daily:{sent:n,max:it},weekly:{sent:o,max:at}};return r||(c.reason=s?`Daily limit reached (${n}/${it})`:`Weekly limit reached (${o}/${at})`),c}function dt(){let e=Oo(),t=ct(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:it,remaining:it-n},weekly:{sent:o,max:at,remaining:at-o}}}function rn(){return Je||(ge(),Je=lt(Co,"sync-state.json")||{},Je)}function No(e){ge(),Je=e;try{We(Co,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function xr(){if(xe)return xe;ge();try{F.existsSync(bo)&&(xe=JSON.parse(F.readFileSync(bo,"utf-8")))}catch{}return xe||(xe={}),xe}function Rr(e){return Array.isArray(e.applications)}function Tr(){let e=xr();if(Rr(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function Mo(){let e=Tr(),t=new Map;for(let i of e)for(let r of i.questions||[]){let c=r.question.toLowerCase().trim();if(!c)continue;t.has(c)||t.set(c,{question:r.question,count:0,answers:new Map});let a=t.get(c);a.count++;let l=(r.answer||"").trim();a.answers.set(l,(a.answers.get(l)||0)+1)}let n=[...t.values()].sort((i,r)=>r.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((r,c)=>c[1]-r[1])[0]?.[0]||""})),s=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((r,c)=>c[1]-r[1]).map(([r,c])=>`${r} (${c}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function an(e){if(F.existsSync(B.join(te,".git")))try{let t={cwd:te,stdio:"pipe",timeout:1e4};tn("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{tn("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');tn(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var hr,yr,te,nn,Sl,$o,Ot,Co,bo,on,_o,it,at,He,wr,pe,Re,Je,xe,br,Sr,Ye=Z(async()=>{await rt();hr=gr(import.meta.url),yr=B.dirname(B.dirname(hr)),te=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(yr,"collected-profiles"),nn=B.join(te,"people.json"),Sl=B.join(te,"jobs.json"),$o=B.join(te,"quota.json"),Ot=B.join(te,"conversations.json"),Co=B.join(te,"sync-state.json"),bo=B.join(te,"application-questions.json"),on=B.join(te,"profile-history"),_o=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},it=_o(process.env.CONNECT_MAX_DAILY,20),at=_o(process.env.CONNECT_MAX_WEEKLY,100),He=null,wr=null,pe=null,Re=null,Je=null,xe=null;br=["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"],Sr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Fo={};ee(Fo,{BLOCK_MARKERS:()=>Po,dedupeAndCap:()=>Lo,extractSidePanelProfiles:()=>Ir,normalizeFundUrl:()=>Mt,normalizeProfileUrl:()=>Ge,scanRelatedBlocks:()=>jo});function Ge(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function Mt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function jo(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=l=>(l||"").replace(/\s+/g," ").trim(),s=l=>{let u=String(l||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=l=>o(l).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),r=l=>{let u=l,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))return u}return f||l.parentElement},c=[],a=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let l of a){let u=o(l.textContent).toLowerCase();if(!u)continue;let f=e.find(([y])=>u.includes(y));if(!f)continue;let d=f[1],m=r(l);if(!m)continue;let w=0,g=new Set,b=/[·•]\s*(1st|2nd|3rd)\b/i;for(let y of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let S=y.href||y.getAttribute("href")||"",h=s(S);if(!h||g.has(h))continue;let p="",v="",C=y,x=null;for(let R=0;R<8&&C.parentElement;R++)if(C=C.parentElement,(C.innerText||"").trim().length>15&&C.querySelectorAll('a[href*="/in/"]').length<=2){x=C;break}if(x){let R=(x.innerText||"").split(`
4
+ `).map(o).filter(Boolean),E=R.findIndex(O=>b.test(O));E>=0&&(p=o(R[E].split(/[·•]/)[0]).replace(/^View\s+/i,""),!p&&E>0&&(p=o(R[E-1]).replace(/^View\s+/i,"")),v=R.slice(E+1).filter(H=>!b.test(H)&&!/^view\b/i.test(H)&&!/mutual connection/i.test(H)&&/[a-z]/i.test(H)&&H.length>2)[0]||"")}if(!p){let R=y.querySelector('span[aria-hidden="true"]'),E=o(R?R.textContent:y.getAttribute("aria-label")||y.textContent);if(p=i(E),p){let O=E.match(/[·•]\s*(?:1st|2nd|3rd)\+?\s*(.+)$/i);O&&(v=o(O[1]))}}p&&(g.add(h),c.push({href:S,name:p,title:v,block:d,rank:w++}))}}return c}function Lo(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=Ge(t.seedUrl||""),s=new Map,i={};for(let r of e||[]){let c=Ge(r.href);c&&(o&&c===o||(i[r.block]=i[r.block]||0,!(i[r.block]>=n)&&(s.has(c)||(i[r.block]++,s.set(c,{url:c,name:r.name,title:r.title||null,block:r.block,rank:r.rank})))))}return Array.from(s.values())}async function Ir(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(jo,Po)}catch{return[]}return Lo(n,t)}var Po,ln=Z(()=>{Po=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"],["explore premium profiles","explore_premium"]]});var Vo={};ee(Vo,{getJobDecision:()=>jr,getLastVisit:()=>Vr,getScoutStats:()=>mn,loadCompanies:()=>fn,loadDiscoveredPeople:()=>bt,loadJobDecisions:()=>wt,loadScoutedJobs:()=>yt,loadVisitLog:()=>Lt,recordCompany:()=>Br,recordDiscoveredEdge:()=>Ur,recordDiscoveredEdges:()=>qr,recordVisit:()=>Jr,resetCaches:()=>dn,saveCompany:()=>Hr,saveDiscoveredPerson:()=>Lr,saveScoutedJob:()=>Mr,setJobDecision:()=>Pr});import"dotenv/config";import*as ne from"fs";import*as Q from"path";import{fileURLToPath as Dr}from"url";function ve(){ne.existsSync(Ne)||ne.mkdirSync(Ne,{recursive:!0})}function ke(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ne.writeFileSync(o,n);for(let s=0;s<3;s++)try{ne.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function ht(e){try{if(ne.existsSync(e))return JSON.parse(ne.readFileSync(e,"utf-8"))}catch{}return null}function dn(){ft=null,mt=null,pt=null,gt=null,Oe=null}function yt(){return ft||(ft=ht(Uo)||{},ft)}function Mr(e,t){if(!e)return;ve();let n=yt(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[s,i]of Object.entries(t))i!=null&&(n[e][s]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{ke(Uo,n)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function wt(){return mt||(mt=ht(Bo)||{},mt)}function Pr(e,t,n={}){if(!e||!t)return;ve();let o=wt(),s=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=s,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:s,updatedAt:s,reason:n.reason||null,score:n.score??null,source:n.source||null};try{ke(Bo,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function jr(e){return wt()[e]||null}function bt(){return pt||(pt=ht(jt)||{},pt)}function ze(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Ho(e,t){let n=Ge(t)||t;if(e[n])return n;let o=ze(t);if(!o)return n;let s=null;for(let[i,r]of Object.entries(e)){if(ze(r&&(r.canonicalUrl||r.profileUrl)||i)===o)return i;!s&&r&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}return s||n}function Lr(e,t){if(!e)return;ve();let n=bt(),o=new Date().toISOString().slice(0,10),s=Ho(n,e),i=ze(e);if(n[s]){let r=n[s];t.name&&(r.name=t.name),t.title&&(r.title=t.title),t.company&&(r.company=t.company),t.location&&(r.location=t.location),t.role&&(r.role=t.role),t.isConnected!=null&&(r.isConnected=t.isConnected),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),i&&ze(r.canonicalUrl||r.profileUrl||s)!==i&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(i)||r.aliases.push(i)),r.lastSeen=o,r.seenCount=(r.seenCount||1)+1}else n[s]={canonicalUrl:s,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{ke(jt,n)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function Fr(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function Jo(e,t,n={},o){if(!t)return;let s=ze(t);t=Ho(e,t);let i=n.seedUrl?{...n,seedUrl:Ge(n.seedUrl)||n.seedUrl}:n,r=o.slice(0,10),{edge:c,match:a}=Fr(i,o),l=e[t];l||(l=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,title:n.title||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:r,firstSeen:r,lastSeen:r}),n.name&&(l.name=n.name),n.title&&(!l.title||/^[·•\s]*(1st|2nd|3rd)\b/i.test(l.title))&&(l.title=n.title),n.location&&(l.location=l.location||n.location),n.company&&(l.company=n.company),n.companyUrl&&(l.companyUrl=l.companyUrl||n.companyUrl),n.isConnected!=null&&(l.isConnected=n.isConnected),n.connectionsCount!=null&&(l.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(l.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(l.connectGate=n.connectGate),n.note&&!l.note&&(l.note=n.note),n.whyUseful&&!l.whyUseful&&(l.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(l.extra={...l.extra||{},...n.extra}),Array.isArray(l.sources)||(l.sources=[]);let u=l.sources.find(a);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):l.sources.push(c),Array.isArray(l.categories)||(l.categories=[]),Array.isArray(l.sectors)||(l.sectors=[]),Array.isArray(l.aliases)||(l.aliases=[]),Array.isArray(l.graphRefs)||(l.graphRefs=[]),cn(l.categories,n.category),Pt(l.categories,n.categories),Pt(l.sectors,n.sectors),Pt(l.aliases,n.aliases),s&&ze(l.canonicalUrl||t)!==s&&cn(l.aliases,s),Pt(l.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(l.affiliations)||(l.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||l.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||l.affiliations.push(f)}l.lastSeen=r,l.seenCount=(l.seenCount||0)+1}function Ur(e,t={}){if(!e)return;ve();let n=bt();Jo(n,e,t,new Date().toISOString());try{ke(jt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function qr(e){if(!Array.isArray(e)||e.length===0)return;ve();let t=bt(),n=new Date().toISOString(),o=0;for(let s of e)!s||!s.url||(Jo(t,s.url,s,n),o++);if(o)try{ke(jt,t)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function Br(e={}){if(!e||!e.name)return;ve();let t=e.key||Mt(e.website)||Mt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=fn(),o=new Date().toISOString().slice(0,10),s=(a,l)=>{l&&Array.isArray(a)&&!a.includes(l)&&a.push(l)},i=(a,l)=>{if(Array.isArray(l))for(let u of l)s(a,u)},r=n[t];r||(r=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(r.name=e.name),e.website&&(r.website=r.website||e.website),e.linkedinUrl&&(r.linkedinUrl=r.linkedinUrl||e.linkedinUrl);for(let a of["size","check","stage","location","industries","about"])e[a]&&!r[a]&&(r[a]=e[a]);e.note&&!r.note&&(r.note=e.note),e.whyUseful&&!r.whyUseful&&(r.whyUseful=e.whyUseful),e.fitScore!=null&&(r.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(r.extra={...r.extra||{},...e.extra});for(let a of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(r[a])||(r[a]=[]),i(r[a],e[a]);Array.isArray(r.people)||(r.people=[]);let c=a=>{if(!a||!a.url)return;let l=r.people.find(u=>u.url===a.url&&(u.role||null)===(a.role||null));l?a.current!=null&&(l.current=a.current):r.people.push({url:a.url,name:a.name||null,role:a.role||null,current:a.current??null,from:a.from??null,to:a.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(a=>c({url:a.url,name:a.name,role:"Partner",current:!0})),Array.isArray(r.portfolio)||(r.portfolio=[]);for(let a of e.portfolio||[]){let l=a&&(a.key||a.name);l&&!r.portfolio.some(u=>(u.key||u.name)===l)&&r.portfolio.push(a)}r.lastSeen=o,r.seenCount=(r.seenCount||0)+1;try{ke(un,n)}catch(a){console.error(`[!] Failed to save companies.json: ${a.message}`)}return t}function fn(){return gt||(gt=ht(un)||{},gt)}function Hr(e,t){if(!e)return;ve();let n=fn(),o=new Date().toISOString().slice(0,10);if(n[e]){let s=n[e];t.name&&(s.name=t.name),t.about&&(s.about=t.about),t.size&&(s.size=t.size),t.industries&&(s.industries=t.industries),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),t.recruiterUrl&&(s.recruiterUrls||(s.recruiterUrls=[]),s.recruiterUrls.includes(t.recruiterUrl)||s.recruiterUrls.push(t.recruiterUrl)),s.lastSeen=o,s.jobCount=s.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{ke(un,n)}catch(s){console.error(`[!] Failed to save companies.json: ${s.message}`)}}function Lt(){return Oe||(Oe=ht(qo)||{visits:[]},Array.isArray(Oe.visits)||(Oe.visits=[]),Oe)}function Jr(e,t={}){if(!e)return;ve();let n=Lt();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(s=>new Date(s.date).getTime()>o);try{ke(qo,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function Vr(e){let t=Lt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function mn(){let e=yt(),t=bt(),n=Object.values(e),o=Object.values(t),s={};for(let d of n)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),r={};for(let d of n)for(let m of d.techStack||[])r[m]=(r[m]||0)+1;let c=Object.entries(r).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),a=Lt(),l=new Date().toISOString().slice(0,10),u=a.visits.filter(d=>d.date.startsWith(l)).length,f=new Set(a.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var Or,Nr,Ne,Uo,jt,qo,un,Bo,ft,mt,pt,cn,Pt,gt,Oe,St=Z(()=>{ln();Or=Dr(import.meta.url),Nr=Q.dirname(Q.dirname(Or)),Ne=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(Nr,"market-research"),Uo=Q.join(Ne,"scouted-jobs.json"),jt=Q.join(Ne,"discovered-people.json"),qo=Q.join(Ne,"visit-log.json"),un=Q.join(Ne,"companies.json"),Bo=Q.join(Ne,"job-decisions.json");ft=null;mt=null;pt=null;cn=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Pt=(e,t)=>{if(Array.isArray(t))for(let n of t)cn(e,n)};gt=null;Oe=null});var ys={};ee(ys,{computeEngagement:()=>$n,detectCategory:()=>us,detectCategoryFromTitle:()=>qt,determineAction:()=>gs,determineLastMessageBy:()=>Ht,determineSituation:()=>ds,enrichConversation:()=>Bt,enrichPerson:()=>_n,enrichPersonContext:()=>hs,extractAutoTags:()=>ms,generateSummary:()=>fs,normPreview:()=>Xe});function Bt(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(a=>!Be.has(a.status)),i=di(t,e.profileUrl,n),r=Ht(s,t);if(e.lastMessageBy=r,e.conversationStatus=r==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let a=us(s,t,i);a&&(e.category=a,e.categorySource=e.categorySource||"message_content")}if(e.situation=ds(s,r,t),s.length>0){let a=s[s.length-1];e.lastMessageTime=a.time}if(s.length>0&&!e.initiatedBy){let a=s[0];a.sender===K?e.initiatedBy="us":a.sender!=="Unknown"&&a.sender!==""&&(e.initiatedBy="them")}e.engagement=$n(s,t),e.personContext=hs(i),e.summary=fs(e,t,i),e.autoTags=ms(e,t,i);let c=gs(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=ui(e),e}function us(e,t,n){if(!e||e.length===0)return n?.title?qt(n.title):null;let o=e.filter(s=>s.sender!==K&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,i]of Object.entries(cs))if(i.theirMessages){for(let r of i.theirMessages)if(r.test(o))return s}if(n?.title){let s=qt(n.title);if(s)return s}return null}function qt(e){if(!e)return null;for(let[t,n]of Object.entries(cs))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function ds(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return ls.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(i=>i.sender!==K&&i.sender!=="Unknown");return ls.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Ht(e,t){if(!e||e.length===0)return"them";let n=[...e].map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),o=n.length>0?n:[...e].reverse();for(let s of o){let i=s.sender;if(i===K)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function fs(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,r=n?.title,c=n?.company,a=n?.location;i==="recruiter"&&c?s.push(`Recruiter from ${c}`):i==="hiring_manager"&&c?s.push(`Hiring manager at ${c}`):i==="founder"&&c?s.push(`Founder of ${c}`):i&&r?s.push(`${Cn(i)}: ${Qe(r,40)}`):r?s.push(Qe(r,50)):s.push(t.split(" ")[0]);let l=o.filter(w=>w.sender!==K&&w.sender!=="Unknown").map(w=>w.text).join(" "),u=fi(l),f=mi(l),d=pi(l),m=[];return u&&m.push(u),d&&d!==a&&m.push(d),f&&m.push(f),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function ms(e,t,n){let o=[],s=(e.messages||[]).filter(l=>!Be.has(l.status)),i=s.map(l=>l.text).join(" "),r=s.filter(l=>l.sender!==K&&l.sender!=="Unknown").map(l=>l.text).join(" "),c=ps(r,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let a=e.engagement||$n(s,t);return a.messageCount>=6&&o.push("active-thread"),a.theirCount===0&&a.ourCount>0&&o.push("no-response"),a.ourCount===0&&a.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(l=>st.has(l.status))&&o.push("has-draft"),[...new Set(o)]}function ps(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let r of o)i.includes(r)&&n.push(r.replace(/\s+/g,"-"));for(let[r,c]of s)i.includes(r)&&n.push(c);return n}function gs(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Xe(e.lastMessagePreview)===Xe(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(i=>st.has(i.status));return s?s.status===W.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Cn(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function $n(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,s=0,i=!1,r=!1,c=e.map(a=>a.text).join(" ");for(let a of e)a.sender===K?n++:a.sender==="Unknown"||a.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(c),r=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:r}}function hs(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function ui(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function di(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let s=Ve(n,t,e);if(n[s])return n[s]}if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function Xe(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Cn(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Qe(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function fi(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function mi(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function pi(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function _n(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=qt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}gi(e),e.personSummary=hi(e),e.personAutoTags=yi(e);let n=wi(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=bi(e)),e}function gi(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function hi(e){let t=[],n=e.category,o=e.title,s=e.company,i=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${Qe(o,40)} at ${Qe(s,30)}`):o?t.push(Qe(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let r=new Date(e.connectionDate);if(!isNaN(r)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[r.getMonth()]} ${r.getDate()}`)}}if(e.jobCount>0){let r=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(r+=` (last: ${Qe(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(r+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}r+=")"}t.push(r)}return t.join(". ").replace(/\.\./g,".")||null}function yi(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=ps("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function wi(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Cn(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function bi(e){let t=e.category;if(!t)return null;let n=Si(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function Si(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var cs,ls,En=Z(async()=>{await rt();await Ye();cs={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};ls=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Ps={};ee(Ps,{extractCertificationsFromDetails:()=>Ia,extractEducationFromDetails:()=>Ra,extractExperienceFromDetails:()=>Aa,extractFeaturedFromDetails:()=>xa,extractRecommendationsFromDetails:()=>Da,extractSkillsFromDetails:()=>Ta});async function Aa(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await be(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await k(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let r of document.querySelectorAll("button"))if(/^Load more$/i.test((r.textContent||"").trim()))return r.click(),!0;return!1});)s++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function r(u){let f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(g=>g.tagName==="DIV");if(m.length<3)continue;let w=m.filter(g=>(g.textContent||"").trim().length>50);w.length<3||(d.textContent||"").length<500||f.push({el:d,count:w.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let c=r(i);if(!c)return[];let a=Array.from(c.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function l(u){let f=u[0]||null,d=null,m=null;if(u[1]){let E=u[1].split("\xB7").map(O=>O.trim());d=E[0]||null,E[1]&&(m=E[1])}let w=u.findIndex(E=>/(\d{4}|present)/i.test(E)&&/(-|–|—)/i.test(E)&&E.length<80),g=null,b=null;if(w>=0){let E=u[w].split("\xB7").map(O=>O.trim());g=E[0]||null,E[1]&&(b=E[1])}let y=null,S=-1;if(w>=0&&u[w+1]){let E=u[w+1],O=/^[>*\-•]|^&gt;/.test(E),H=/https?:\/\//.test(E),$=/\d{4}/.test(E),_=/,/.test(E)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(E);!O&&!H&&!$&&E.length<100&&_&&(y=E,S=w+1)}let h=null,p=-1,v=u[u.length-1];if(v&&/and\s+\+\d+\s+skills?$/i.test(v)){p=u.length-1;let E=v.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);E&&(h={listed:E[1].split(",").map(O=>O.trim()),additional:parseInt(E[2],10)})}let C=new Set([0,1,w,S,p].filter(E=>E>=0)),x=u.filter((E,O)=>!C.has(O)),R=x.length>0?x.join(`
4
5
 
5
- `):null;return{title:f,company:d,employmentType:m,dates:h,duration:b,location:y,description:R,skills:g,_raw:u}}return a.map(u=>{let d=(u.innerText||"").trim().split(`
6
- `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return l(d)}).filter(u=>u.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function kt(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await we(e,o,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:`details/${n}`}),await k(1e3);let s=e.url();if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let r=0;r<4;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);await k(800);let i=0;for(;i<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});)i++,await k(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(600)}async function Ct(e,t,n,o){try{return await o()}catch(s){let i=s.message||"";if(s.code==="SESSION_EXPIRED"||/^session expired/i.test(i))throw s;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function ya(e,t){return Ct(t,"featured","extractFeaturedFromDetails",async()=>(await kt(e,t,"featured"),await e.evaluate(`(() => {
7
- ${$t}
6
+ `):null;return{title:f,company:d,employmentType:m,dates:g,duration:b,location:y,description:R,skills:h,_raw:u}}return a.map(u=>{let d=(u.innerText||"").trim().split(`
7
+ `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return l(d)}).filter(u=>u.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function _t(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await be(e,o,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:`details/${n}`}),await k(1e3);let s=e.url();if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let r=0;r<4;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);await k(800);let i=0;for(;i<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});)i++,await k(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(600)}async function At(e,t,n,o){try{return await o()}catch(s){let i=s.message||"";if(s.code==="SESSION_EXPIRED"||/^session expired/i.test(i))throw s;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function xa(e,t){return At(t,"featured","extractFeaturedFromDetails",async()=>(await _t(e,t,"featured"),await e.evaluate(`(() => {
8
+ ${Et}
8
9
 
9
10
  const main = document.querySelector('main');
10
11
  if (!main) return [];
@@ -44,8 +45,8 @@ var Zs=Object.defineProperty;var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{f
44
45
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
45
46
  return true;
46
47
  });
47
- })()`)))}async function wa(e,t){return Ct(t,"education","extractEducationFromDetails",async()=>(await kt(e,t,"education"),await e.evaluate(`(() => {
48
- ${$t}
48
+ })()`)))}async function Ra(e,t){return At(t,"education","extractEducationFromDetails",async()=>(await _t(e,t,"education"),await e.evaluate(`(() => {
49
+ ${Et}
49
50
 
50
51
  const main = document.querySelector('main');
51
52
  if (!main) return [];
@@ -81,8 +82,8 @@ var Zs=Object.defineProperty;var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{f
81
82
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
82
83
  return true;
83
84
  });
84
- })()`)))}async function ba(e,t){return Ct(t,"skills","extractSkillsFromDetails",async()=>(await kt(e,t,"skills"),await e.evaluate(`(() => {
85
- ${$t}
85
+ })()`)))}async function Ta(e,t){return At(t,"skills","extractSkillsFromDetails",async()=>(await _t(e,t,"skills"),await e.evaluate(`(() => {
86
+ ${Et}
86
87
 
87
88
  const main = document.querySelector('main');
88
89
  if (!main) return [];
@@ -113,8 +114,8 @@ var Zs=Object.defineProperty;var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{f
113
114
  skills.push({ name, endorsements, _raw: lines });
114
115
  }
115
116
  return skills;
116
- })()`)))}async function Sa(e,t){return Ct(t,"certifications","extractCertificationsFromDetails",async()=>(await kt(e,t,"certifications"),await e.evaluate(`(() => {
117
- ${$t}
117
+ })()`)))}async function Ia(e,t){return At(t,"certifications","extractCertificationsFromDetails",async()=>(await _t(e,t,"certifications"),await e.evaluate(`(() => {
118
+ ${Et}
118
119
 
119
120
  const main = document.querySelector('main');
120
121
  if (!main) return [];
@@ -138,8 +139,8 @@ var Zs=Object.defineProperty;var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{f
138
139
 
139
140
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
140
141
  }).filter(e => e.name);
141
- })()`)))}async function va(e,t){return Ct(t,"recommendations","extractRecommendationsFromDetails",async()=>(await kt(e,t,"recommendations"),await e.evaluate(`(() => {
142
- ${$t}
142
+ })()`)))}async function Da(e,t){return At(t,"recommendations","extractRecommendationsFromDetails",async()=>(await _t(e,t,"recommendations"),await e.evaluate(`(() => {
143
+ ${Et}
143
144
 
144
145
  const main = document.querySelector('main');
145
146
  if (!main) return [];
@@ -174,7 +175,7 @@ var Zs=Object.defineProperty;var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{f
174
175
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
175
176
  return true;
176
177
  });
177
- })()`)))}var $t,Ds=Z(()=>{Fe();$t=`
178
+ })()`)))}var Et,js=Z(()=>{qe();Et=`
178
179
  function findEntryContainer(root) {
179
180
  const candidates = [];
180
181
  for (const div of root.querySelectorAll('div')) {
@@ -237,127 +238,127 @@ function findEntryContainer(root) {
237
238
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
238
239
  return candidates[0]?.el;
239
240
  }
240
- `});var Ns={};ue(Ns,{DEFAULT_PROFILE_INTERESTS:()=>Os,computeFit:()=>Ca,detectSectors:()=>$a});function $a(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,s]of Object.entries(ka))s.some(i=>i.test(t))&&n.push(o);return n}function Ca(e,t=Os){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),s=0;for(let i of e){let r=n(t&&t[i]);r>s&&(s=r)}return Math.min(1,s/o)}var ka,Os,Ms=Z(()=>{ka={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};Os={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});var Ls={};ue(Ls,{clickConnectButton:()=>jn,default:()=>Aa,detectConnectionStatus:()=>_e,findConnectButton:()=>_t,runFunnel:()=>js,sendConnectionRequest:()=>Ln,shouldExcludeLocation:()=>Vt,viewProfile:()=>Pn});async function Ps(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 k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Vt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Pn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:r=!1,extractRecommendations:c=!1,extractCertifications:a=!1}=n;try{await we(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await k(1500),await Ee(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await Ps(e,t));let u=0;for(let p=0;p<2;p++){let v=await e.evaluate(()=>document.body.scrollHeight);for(let x=1;x<=6;x++)await e.evaluate(R=>window.scrollTo(0,R),v*x/6),await k(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===u)break;u=C}await k(800);let f=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(f=p.split("?")[0].replace(/\/+$/,""))}catch{}let d=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","Licenses & certifications","Courses","Test scores","Organizations"]),v=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),C=I=>{let O=(I||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(O)},x={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:[]},R=document.querySelector("main");if(!R)return x;let A=[...Array.from(R.querySelectorAll("h1")),...Array.from(R.querySelectorAll("h2"))],D=Array.from(R.querySelectorAll("h2")),K=A.find(I=>{let O=I.textContent&&I.textContent.trim(),M=(O||"").replace(/\s*\(\d+\)$/,"").trim();return O&&O.length>1&&O.length<100&&!p.has(M)&&!v.has(M)}),$=K?K.textContent.trim():null,_=K?K.parentElement:null;for(;_&&_!==R&&!Array.from(_.children).filter(O=>O.tagName==="P").some(O=>{let M=O.textContent&&O.textContent.trim();return M&&M.length>5&&!C(M)});)_=_.parentElement;let T=null,N=null,H=null,ae=null;if(_&&_!==R){let I=Array.from(_.children).filter(M=>M.tagName==="P").filter(M=>{let ye=M.textContent&&M.textContent.trim();return ye&&ye.length>5&&!C(ye)});if(I[0]&&(T=I[0].textContent.trim()),I[1]){let M=I[1].textContent.trim().split(/\s*[·•]\s*/);N=M[0]||null,M.length>1&&(H=M.slice(1).join(" \xB7 "))}let O=Array.from(_.children).filter(M=>M.tagName==="DIV");for(let M=O.length-1;M>=0;M--){let ye=O[M].textContent&&O[M].textContent.trim();if(ye&&!($&&ye.startsWith($))&&(ae=ye.split(/[·•]/)[0].trim(),ae))break}}let le=null;if(_){let I=_.querySelectorAll("p, span, div");for(let O of I){let M=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){le=M;break}}}let j=!!R.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=L&&L.src||null,q=R.textContent||"",ce=null,Hn=q.match(/(\d+\+?)\s+connections\b/i);Hn&&(ce=Hn[1]+" connections");let At=null,Jn=q.match(/(\d+)\s+mutual connection/i),Vn=q.match(/and\s+(\d+)\s+other mutual/i),Gs=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Jn?At=parseInt(Jn[1],10):Vn?At=2+parseInt(Vn[1],10):Gs&&(At=2);let Wn=null,Yn=null,Gn=D.find(I=>I.textContent&&I.textContent.trim()==="About");if(Gn){let I=Gn.parentElement;for(;I&&I.tagName!=="SECTION";)I=I.parentElement;if(I){let O=(I.textContent||"").trim();O=O.replace(/^About\s*/,"").trim();let M=O.match(/Top skills\s*(.+?)$/i);if(M){let Yt=M[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Xs=>Xs.trim()).filter(Boolean);Yt.length>0&&Yt.length<10&&(Yn=Yt)}O=O.split(/\n?…\s*more/i)[0].trim(),O=O.split(/\n?\.\.\.\s*more/i)[0].trim(),O=O.split(/\bTop skills\b/i)[0].trim(),O=O.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Wn=O||null}}let Kn=null,zn=D.find(I=>I.textContent&&I.textContent.trim()==="Activity");if(zn){let I=zn.parentElement;for(;I&&I.tagName!=="SECTION";)I=I.parentElement;if(I){let O=(I.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);O&&(Kn=parseInt(O[1].replace(/,/g,""),10))}}let Ks=[...new Set(D.map(I=>(I.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(I=>I&&I.length>1&&I.length<60&&I!==$).filter(I=>p.has(I)))],Ze=document.body.textContent||"",zs=/#OpenToWork\b/i.test(Ze)||/\bOpen to work\b/.test(Ze),Qs=/#Hiring\b/i.test(Ze)||/\bI'?m hiring\b/i.test(Ze)||/\bWe are hiring\b/i.test(Ze);return{name:$,title:T,location:ae,currentCompany:N,currentSchool:H,connectionDegree:le,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:ce,mutualConnectionsCount:At,followers:Kn,openToWork:zs,hiring:Qs,about:Wn,topSkills:Yn,availableSections:Ks}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,w=null,h=null,b=null,y=null,S=null;if(o||s||i||r||c||a){let p=await Promise.resolve().then(()=>(Ds(),Is));o&&(m=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(w=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${w.length} entries`)),i&&(h=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),r&&(b=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),c&&(y=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),a&&(S=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...w!==null&&{featured:w},...h!==null&&{education:h},...b!==null&&{skillsFull:b},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function _e(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let s='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(s),r=f=>Array.from(document.querySelectorAll(f)).filter(i),c=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return c.length>0?{status:"pending",debug:u}:a&&!l?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await k(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function _t(e){let t=null,n=await e.evaluate(()=>{let l=document.querySelector("h1")?.textContent?.trim();if(l&&!l.includes("notification"))return l;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(l=u.textContent?.trim(),l&&!l.includes("notification")))return l;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let l=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});l.count>0&&console.log(` S0: ${l.count} custom-invite links: ${JSON.stringify(l.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),m=f.toLowerCase().split(" ")[0],w='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let b=h.getBoundingClientRect();if(b.width===0||b.height===0||h.closest(w))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(m))return h}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let l=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${l}"`);let u=await e.evaluate(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),w=document.querySelectorAll("button[aria-label]");return Array.from(w).filter(b=>{let y=b.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&m.test(y)}).map(b=>b.getAttribute("aria-label")?.slice(0,50))},l);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),w='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',h=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let b of m){if(b.closest(w))continue;let y=b.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&h.test(y))return b}return null},l);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,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 l=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();l.includes("invite")&&!l.includes(u)&&(console.log(` Skipping primary button: wrong person (${l})`),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 s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let l of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),w=f.className.includes("sticky-header")||f.className.includes("sticky"),h=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,b=(f.getAttribute("aria-label")||"").toLowerCase(),y=b.includes("invite"),S=d?b.includes(d):!0;return{isMuted:m,isStickyHeader:w,inRecommendations:h,hasInvite:y,matchesName:S,ariaLabel:b}},l,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=l;break}}for(let l of o)l!==i&&await l.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,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 r=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let l of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,w=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:w,top:d.top}},l);if(u.isVisible&&!u.isInStickyHeader){r=l,console.log(" Found More button by ID pattern (main)");break}}for(let l of c)l!==r&&await l.dispose().catch(()=>{});if(!r&&c.length>0&&(r=c[c.length-1],console.log(" Found More button by ID pattern (last)")),r||(r=await e.$('button[aria-label="More actions"]'),r&&console.log(" Found More button by aria-label")),!r){let l=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(m=>{let w=m.innerText?.trim(),h=m.getAttribute("aria-label")||"",b=m.getBoundingClientRect();return b.top<100||b.top>600||b.width===0?!1:w==="Follow"||w==="Message"||w==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let w of d.querySelectorAll("button"))if(w.innerText?.trim()==="More"&&w!==f)return w;d=d.parentElement}return null});r=l?.asElement?.()||null,r||await l?.dispose?.().catch(()=>{}),r&&console.log(" Found More button by text (near profile actions)")}if(r)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),r),await k(500),await e.evaluate(d=>d.click(),r),await k(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let w of m){let h=w.querySelector('a[href*="custom-invite"]');if(h)return h;for(let b of w.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(b.innerText?.trim()==="Connect")return b}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let w of d)for(let h of w.querySelectorAll('[role="menuitem"], a, div')){let b=h.innerText?.trim();b&&b.length<40&&m.push(b)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(l){console.log(" More dropdown click failed:",l.message),await e.keyboard.press("Escape")}let a=await e.evaluateHandle(l=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(l||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let m=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let w=d.getBoundingClientRect();if(!(w.width===0||w.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="connect")return d}}return null},n||"");return t=a?.asElement?.()||null,t||await a?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function jn(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await k(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",r=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(r))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(r.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!r.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await k(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await k(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await k(3e3)):(await e.evaluate(u=>u.click(),t),await k(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 a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),l=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${l}`:` \u26A0 No modal after connect click \u2014 ${l}`),"success"}async function _a(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 k(1500);let n=await _t(e);if(n){await e.evaluate(s=>s.click(),n),await k(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await Qe(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Qe(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(r=>{let c=a=>!!(a&&a.querySelector(r));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),s=()=>e.evaluate(()=>{for(let r of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(r.innerText||""))return!0;return!1}),i=async()=>{let r=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(r)return r;let c=await e.evaluateHandle(a=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(a)||null,n);return r=c?.asElement?.()||null,r||await c?.dispose?.().catch(()=>{}),r};for(let r=0;r<2;r++){try{await t.evaluate(c=>c.click())}catch{}if(await k(3e3),await s())return!1;if(await o())return!0;if(r===0){let c=await i();if(!c)return await o();t=c,await k(600)}}return await o()}async function Ln(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let c=tn();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 r=await Ea(e,t,n);return r.connectionSent&&!i&&xo(t,o),r}async function Ea(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:r=!0,excludeLocations:c=[]}=n,a={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
241
- --- Connecting: ${l} ---`),c.length>0){let y=J()[t]?.location;if(Vt(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),a.reason="excluded_location",a.profileInfo={location:y},a}try{await we(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(y){if(y.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),a.reason="session_expired",a.fatal=!0,a;throw y}if(await k(2e3),await Ee(e)&&(console.log(" Dismissed Premium overlay"),await k(2e3),await Ps(e,t),await k(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(sn(),Mo)),{recordDiscoveredEdges:g}=await Promise.resolve().then(()=>(wt(),qo)),{detectCategoryFromTitle:p}=await $n().then(()=>ms),{detectSectors:v}=await Promise.resolve().then(()=>(Ms(),Ns)),C=S(t)||t,x=await y(e,{seedUrl:C}),R=x.map(A=>{let D=A.headline?p(A.headline):null;return{url:A.url,seedUrl:C,block:A.block,rank:A.rank,name:A.name,headline:A.headline,categories:D?[D]:[],sectors:v(A.headline||"")}});g(R),x.length&&console.log(` \xB7 discovery: harvested ${x.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}a.profileInfo=await e.evaluate(()=>{let y=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"]),S=j=>{let L=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},g={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},p=document.querySelector("main");if(!p)return g;let v=[...Array.from(p.querySelectorAll("h1")),...Array.from(p.querySelectorAll("h2"))],C=Array.from(p.querySelectorAll("h2")),x=v.find(j=>{let L=j.textContent&&j.textContent.trim();return L&&L.length>1&&L.length<100&&!y.has(L)&&L!=="0 notifications"}),R=x?x.textContent.trim():null,A=x?x.parentElement:null;for(;A&&A!==p&&!Array.from(A.children).filter(U=>U.tagName==="P").some(U=>{let q=U.textContent&&U.textContent.trim();return q&&q.length>5&&!S(q)});)A=A.parentElement;let D=null,K=null,$=null;if(A&&A!==p){let j=Array.from(A.children),L=j.filter(q=>q.tagName==="P").filter(q=>{let ce=q.textContent&&q.textContent.trim();return ce&&ce.length>5&&!S(ce)});L[0]&&(D=L[0].textContent.trim()),L[1]&&(K=L[1].textContent.trim());let U=j.filter(q=>q.tagName==="DIV");for(let q=U.length-1;q>=0;q--){let ce=U[q].textContent&&U[q].textContent.trim();if(ce&&!(R&&ce.startsWith(R))&&($=ce.split(/[·•]/)[0].trim(),$))break}}let _=null;if(A){let j=A.querySelectorAll("p, span, div");for(let L of j){let U=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){_=U;break}}}let T=null,N=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(N){let j=N.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(T=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,T&&(T=T.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let H=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),ae=H&&H.src||null,le=!!p.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:D,location:$,about:T,company:K,connectionDegree:_,connectionsCount:null,mutualConnections:null,photoUrl:ae,hasVerifiedBadge:le}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(a.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let y=a.profileInfo?.location,S=J()[t]?.location,g=y||S;if(Vt(g,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${g}`),a.reason="excluded_location",a;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await _e(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),a.reason="pending",a;await Ee(e);let d=await _t(e);if(d||await Ee(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await k(2e3),d=await _t(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),a.reason="connected",a;if(!d){let y=await _e(e,{detail:!0});return r&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),a.reason="connected",a):(console.log(" \u2717 Connect not found"),a.reason="button_not_found",a)}a.method=d.method;let m=await jn(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),a.reason="wrong_target",a;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3);let y=await _e(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await Ee(e),await k(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),S),await k(500),await S.click().catch(()=>e.evaluate(p=>p.click(),S)),await k(2e3);let g=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(g){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),g),await k(3e3);let p=e.url();if(p.includes("/premium/")||p.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),a.reason="premium_required",a;if(await _e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.method="more_dropdown",a.withCustomMessage=!1,a;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await k(500),a.reason="premium_required",a}catch(g){return console.log(" More dropdown failed:",g.message),await e.keyboard.press("Escape").catch(()=>{}),a.reason="premium_required",a}else return console.log(" \u2717 No More button found \u2014 Premium required"),a.reason="premium_required",a}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of y){let g=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!g)continue;let p=(g.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(p)||g.querySelector('input[type="email"], input[name="email"]'))return!0;let v=g.querySelector('button[aria-label="Send without a note"]');if(v&&(v.disabled||v.getAttribute("aria-disabled")==="true"||(v.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await k(500),a.reason="email_required",a}let h=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!h&&!b){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let g=S.querySelector('button[aria-label="Add a note"]'),p=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!g,sendWithout:!!p}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=S?.asElement?.()||null,h||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=S?.asElement?.()||null,b||await S.dispose().catch(()=>{})}}if(s)if(h&&o){if(console.log(" Adding personalized note..."),await h.click(),await k(1500),await e.$("div.modal-upsell")){let g=await _a(e);return a.success=g,a.connectionSent=g,a.reason=g?"sent_without_note_upsell":"upsell_failed",a.withCustomMessage=!1,a}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let g=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),p=o.replace("{name}",g);await S.type(p,{delay:20}),await k(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v)return await Qe(e,v)?(console.log(" \u2713 Connection sent (with note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_with_note",a.withCustomMessage=!0,a.messageSent=p,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{if(b)return console.log(" Sending without note..."),await Qe(e,b)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a);if(h&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await Qe(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y)return await Qe(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}if(d.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 k(4e3)),await Ee(e),await k(500);let S=await e.$$('button[id*="profile-overflow-action"]'),g=null;for(let p of S){let v=await e.evaluate(C=>{let x=C.getBoundingClientRect();return{visible:x.width>0&&x.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},p);if(v.visible&&!v.inSticky){g=p;break}}!g&&S.length>0&&(g=S[S.length-1]);for(let p of S)p!==g&&await p.dispose().catch(()=>{});if(g)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),g),await k(500),await g.click().catch(()=>e.evaluate(v=>v.click(),g)),await k(2e3);let p=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(p){console.log(" Found Connect in More dropdown, clicking..."),a.method="more_dropdown",await e.evaluate(R=>R.click(),p),await k(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),await _e(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(a.reason="premium_required",a);if(await _e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;let x=await e.$('button[aria-label="Send without a note"]');if(x)return console.log(" Modal appeared via More dropdown, sending without note..."),await Qe(e,x)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),a.reason="modal_failed",a);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(p){console.log(" More dropdown fallback failed:",p.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),a.reason="modal_failed",a}catch(l){console.error(` \u2717 Error: ${l.message}`),a.reason="error",a.error=l.message;let u=l.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return a.fatal=!0,a;try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{a.fatal=!0}return a}}async function js(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:r=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:a=null,excludeLocations:l=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
242
- === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${r?"View Only":`Connect (max ${i})`}`),r||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!r){let m=ct();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let w=t[m];try{if(e.isClosed()){console.log(`
241
+ `});var Fs={};ee(Fs,{DEFAULT_PROFILE_INTERESTS:()=>Ls,computeFit:()=>Ma,detectSectors:()=>Na});function Na(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,s]of Object.entries(Oa))s.some(i=>i.test(t))&&n.push(o);return n}function Ma(e,t=Ls){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),s=0;for(let i of e){let r=n(t&&t[i]);r>s&&(s=r)}return Math.min(1,s/o)}var Oa,Ls,Us=Z(()=>{Oa={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};Ls={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});var Hs={};ee(Hs,{clickConnectButton:()=>qn,default:()=>La,detectConnectionStatus:()=>Ee,findConnectButton:()=>xt,runFunnel:()=>Bs,sendConnectionRequest:()=>Bn,shouldExcludeLocation:()=>Gt,viewProfile:()=>Un});async function qs(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 k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Gt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Un(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:r=!1,extractRecommendations:c=!1,extractCertifications:a=!1}=n;try{await be(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await k(1500),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await qs(e,t));let u=0;for(let p=0;p<2;p++){let v=await e.evaluate(()=>document.body.scrollHeight);for(let x=1;x<=6;x++)await e.evaluate(R=>window.scrollTo(0,R),v*x/6),await k(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===u)break;u=C}await k(800);let f=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(f=p.split("?")[0].replace(/\/+$/,""))}catch{}let d=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","Licenses & certifications","Courses","Test scores","Organizations"]),v=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),C=I=>{let D=(I||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},x={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:[]},R=document.querySelector("main");if(!R)return x;let E=[...Array.from(R.querySelectorAll("h1")),...Array.from(R.querySelectorAll("h2"))],O=Array.from(R.querySelectorAll("h2")),H=E.find(I=>{let D=I.textContent&&I.textContent.trim(),M=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!p.has(M)&&!v.has(M)}),$=H?H.textContent.trim():null,_=H?H.parentElement:null;for(;_&&_!==R&&!Array.from(_.children).filter(D=>D.tagName==="P").some(D=>{let M=D.textContent&&D.textContent.trim();return M&&M.length>5&&!C(M)});)_=_.parentElement;let T=null,N=null,J=null,ce=null;if(_&&_!==R){let I=Array.from(_.children).filter(M=>M.tagName==="P").filter(M=>{let we=M.textContent&&M.textContent.trim();return we&&we.length>5&&!C(we)});if(I[0]&&(T=I[0].textContent.trim()),I[1]){let M=I[1].textContent.trim().split(/\s*[·•]\s*/);N=M[0]||null,M.length>1&&(J=M.slice(1).join(" \xB7 "))}let D=Array.from(_.children).filter(M=>M.tagName==="DIV");for(let M=D.length-1;M>=0;M--){let we=D[M].textContent&&D[M].textContent.trim();if(we&&!($&&we.startsWith($))&&(ce=we.split(/[·•]/)[0].trim(),ce))break}}let ue=null;if(_){let I=_.querySelectorAll("p, span, div");for(let D of I){let M=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){ue=M;break}}}let j=!!R.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=L&&L.src||null,q=R.textContent||"",de=null,Yn=q.match(/(\d+\+?)\s+connections\b/i);Yn&&(de=Yn[1]+" connections");let Tt=null,Gn=q.match(/(\d+)\s+mutual connection/i),zn=q.match(/and\s+(\d+)\s+other mutual/i),Zs=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Gn?Tt=parseInt(Gn[1],10):zn?Tt=2+parseInt(zn[1],10):Zs&&(Tt=2);let Kn=null,Qn=null,Xn=O.find(I=>I.textContent&&I.textContent.trim()==="About");if(Xn){let I=Xn.parentElement;for(;I&&I.tagName!=="SECTION";)I=I.parentElement;if(I){let D=(I.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let M=D.match(/Top skills\s*(.+?)$/i);if(M){let Kt=M[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(or=>or.trim()).filter(Boolean);Kt.length>0&&Kt.length<10&&(Qn=Kt)}D=D.split(/\n?…\s*more/i)[0].trim(),D=D.split(/\n?\.\.\.\s*more/i)[0].trim(),D=D.split(/\bTop skills\b/i)[0].trim(),D=D.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Kn=D||null}}let Zn=null,eo=O.find(I=>I.textContent&&I.textContent.trim()==="Activity");if(eo){let I=eo.parentElement;for(;I&&I.tagName!=="SECTION";)I=I.parentElement;if(I){let D=(I.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(Zn=parseInt(D[1].replace(/,/g,""),10))}}let er=[...new Set(O.map(I=>(I.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(I=>I&&I.length>1&&I.length<60&&I!==$).filter(I=>p.has(I)))],tt=document.body.textContent||"",tr=/#OpenToWork\b/i.test(tt)||/\bOpen to work\b/.test(tt),nr=/#Hiring\b/i.test(tt)||/\bI'?m hiring\b/i.test(tt)||/\bWe are hiring\b/i.test(tt);return{name:$,title:T,location:ce,currentCompany:N,currentSchool:J,connectionDegree:ue,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:de,mutualConnectionsCount:Tt,followers:Zn,openToWork:tr,hiring:nr,about:Kn,topSkills:Qn,availableSections:er}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,w=null,g=null,b=null,y=null,S=null;if(o||s||i||r||c||a){let p=await Promise.resolve().then(()=>(js(),Ps));o&&(m=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(w=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${w.length} entries`)),i&&(g=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),r&&(b=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),c&&(y=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),a&&(S=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...w!==null&&{featured:w},...g!==null&&{education:g},...b!==null&&{skillsFull:b},...y!==null&&{recommendations:y},...S!==null&&{certifications:S}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function Ee(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let s='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(s),r=f=>Array.from(document.querySelectorAll(f)).filter(i),c=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return c.length>0?{status:"pending",debug:u}:a&&!l?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await k(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function xt(e){let t=null,n=await e.evaluate(()=>{let l=document.querySelector("h1")?.textContent?.trim();if(l&&!l.includes("notification"))return l;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(l=u.textContent?.trim(),l&&!l.includes("notification")))return l;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let l=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});l.count>0&&console.log(` S0: ${l.count} custom-invite links: ${JSON.stringify(l.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),m=f.toLowerCase().split(" ")[0],w='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let g of d){let b=g.getBoundingClientRect();if(b.width===0||b.height===0||g.closest(w))continue;if((g.getAttribute("aria-label")||"").toLowerCase().includes(m))return g}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let l=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${l}"`);let u=await e.evaluate(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),w=document.querySelectorAll("button[aria-label]");return Array.from(w).filter(b=>{let y=b.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&m.test(y)}).map(b=>b.getAttribute("aria-label")?.slice(0,50))},l);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),w='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',g=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let b of m){if(b.closest(w))continue;let y=b.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(y)&&(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&g.test(y))return b}return null},l);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,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 l=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();l.includes("invite")&&!l.includes(u)&&(console.log(` Skipping primary button: wrong person (${l})`),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 s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let l of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),w=f.className.includes("sticky-header")||f.className.includes("sticky"),g=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,b=(f.getAttribute("aria-label")||"").toLowerCase(),y=b.includes("invite"),S=d?b.includes(d):!0;return{isMuted:m,isStickyHeader:w,inRecommendations:g,hasInvite:y,matchesName:S,ariaLabel:b}},l,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=l;break}}for(let l of o)l!==i&&await l.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,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 r=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let l of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,w=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:w,top:d.top}},l);if(u.isVisible&&!u.isInStickyHeader){r=l,console.log(" Found More button by ID pattern (main)");break}}for(let l of c)l!==r&&await l.dispose().catch(()=>{});if(!r&&c.length>0&&(r=c[c.length-1],console.log(" Found More button by ID pattern (last)")),r||(r=await e.$('button[aria-label="More actions"]'),r&&console.log(" Found More button by aria-label")),!r){let l=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(m=>{let w=m.innerText?.trim(),g=m.getAttribute("aria-label")||"",b=m.getBoundingClientRect();return b.top<100||b.top>600||b.width===0?!1:w==="Follow"||w==="Message"||w==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let w of d.querySelectorAll("button"))if(w.innerText?.trim()==="More"&&w!==f)return w;d=d.parentElement}return null});r=l?.asElement?.()||null,r||await l?.dispose?.().catch(()=>{}),r&&console.log(" Found More button by text (near profile actions)")}if(r)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),r),await k(500),await e.evaluate(d=>d.click(),r),await k(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let w of m){let g=w.querySelector('a[href*="custom-invite"]');if(g)return g;for(let b of w.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(b.innerText?.trim()==="Connect")return b}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let w of d)for(let g of w.querySelectorAll('[role="menuitem"], a, div')){let b=g.innerText?.trim();b&&b.length<40&&m.push(b)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(l){console.log(" More dropdown click failed:",l.message),await e.keyboard.press("Escape")}let a=await e.evaluateHandle(l=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(l||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let m=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let w=d.getBoundingClientRect();if(!(w.width===0||w.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="connect")return d}}return null},n||"");return t=a?.asElement?.()||null,t||await a?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function qn(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await k(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",r=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(r))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(r.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!r.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await k(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await k(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await k(3e3)):(await e.evaluate(u=>u.click(),t),await k(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 a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),l=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${l}`:` \u26A0 No modal after connect click \u2014 ${l}`),"success"}async function Pa(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 k(1500);let n=await xt(e);if(n){await e.evaluate(s=>s.click(),n),await k(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await Ze(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Ze(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(r=>{let c=a=>!!(a&&a.querySelector(r));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),s=()=>e.evaluate(()=>{for(let r of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(r.innerText||""))return!0;return!1}),i=async()=>{let r=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(r)return r;let c=await e.evaluateHandle(a=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(a)||null,n);return r=c?.asElement?.()||null,r||await c?.dispose?.().catch(()=>{}),r};for(let r=0;r<2;r++){try{await t.evaluate(c=>c.click())}catch{}if(await k(3e3),await s())return!1;if(await o())return!0;if(r===0){let c=await i();if(!c)return await o();t=c,await k(600)}}return await o()}async function Bn(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let c=sn();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 r=await ja(e,t,n);return r.connectionSent&&!i&&Do(t,o),r}async function ja(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:r=!0,excludeLocations:c=[]}=n,a={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
242
+ --- Connecting: ${l} ---`),c.length>0){let y=V()[t]?.location;if(Gt(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),a.reason="excluded_location",a.profileInfo={location:y},a}try{await be(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(y){if(y.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),a.reason="session_expired",a.fatal=!0,a;throw y}if(await k(2e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(2e3),await qs(e,t),await k(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:y,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(ln(),Fo)),{recordDiscoveredEdges:h}=await Promise.resolve().then(()=>(St(),Vo)),{detectCategoryFromTitle:p}=await En().then(()=>ys),{detectSectors:v}=await Promise.resolve().then(()=>(Us(),Fs)),C=S(t)||t,x=await y(e,{seedUrl:C}),R=x.map(E=>{let O=E.title?p(E.title):null;return{url:E.url,seedUrl:C,block:E.block,rank:E.rank,name:E.name,title:E.title,categories:O?[O]:[],sectors:v(E.title||"")}});h(R),x.length&&console.log(` \xB7 discovery: harvested ${x.length} related profiles`)}catch(y){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${y.message}`)}a.profileInfo=await e.evaluate(()=>{let y=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"]),S=j=>{let L=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},h={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},p=document.querySelector("main");if(!p)return h;let v=[...Array.from(p.querySelectorAll("h1")),...Array.from(p.querySelectorAll("h2"))],C=Array.from(p.querySelectorAll("h2")),x=v.find(j=>{let L=j.textContent&&j.textContent.trim();return L&&L.length>1&&L.length<100&&!y.has(L)&&L!=="0 notifications"}),R=x?x.textContent.trim():null,E=x?x.parentElement:null;for(;E&&E!==p&&!Array.from(E.children).filter(U=>U.tagName==="P").some(U=>{let q=U.textContent&&U.textContent.trim();return q&&q.length>5&&!S(q)});)E=E.parentElement;let O=null,H=null,$=null;if(E&&E!==p){let j=Array.from(E.children),L=j.filter(q=>q.tagName==="P").filter(q=>{let de=q.textContent&&q.textContent.trim();return de&&de.length>5&&!S(de)});L[0]&&(O=L[0].textContent.trim()),L[1]&&(H=L[1].textContent.trim());let U=j.filter(q=>q.tagName==="DIV");for(let q=U.length-1;q>=0;q--){let de=U[q].textContent&&U[q].textContent.trim();if(de&&!(R&&de.startsWith(R))&&($=de.split(/[·•]/)[0].trim(),$))break}}let _=null;if(E){let j=E.querySelectorAll("p, span, div");for(let L of j){let U=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){_=U;break}}}let T=null,N=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(N){let j=N.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(T=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,T&&(T=T.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let J=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),ce=J&&J.src||null,ue=!!p.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:O,location:$,about:T,company:H,connectionDegree:_,connectionsCount:null,mutualConnections:null,photoUrl:ce,hasVerifiedBadge:ue}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(a.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let y=a.profileInfo?.location,S=V()[t]?.location,h=y||S;if(Gt(h,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${h}`),a.reason="excluded_location",a;!y&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Ee(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),a.reason="pending",a;await Ae(e);let d=await xt(e);if(d||await Ae(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await k(2e3),d=await xt(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),a.reason="connected",a;if(!d){let y=await Ee(e,{detail:!0});return r&&(y.status==="connected"||y.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),a.reason="connected",a):(console.log(" \u2717 Connect not found"),a.reason="button_not_found",a)}a.method=d.method;let m=await qn(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),a.reason="wrong_target",a;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3);let y=await Ee(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await Ae(e),await k(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),S),await k(500),await S.click().catch(()=>e.evaluate(p=>p.click(),S)),await k(2e3);let h=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(h){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),h),await k(3e3);let p=e.url();if(p.includes("/premium/")||p.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),a.reason="premium_required",a;if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.method="more_dropdown",a.withCustomMessage=!1,a;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await k(500),a.reason="premium_required",a}catch(h){return console.log(" More dropdown failed:",h.message),await e.keyboard.press("Escape").catch(()=>{}),a.reason="premium_required",a}else return console.log(" \u2717 No More button found \u2014 Premium required"),a.reason="premium_required",a}if(await e.evaluate(()=>{let y=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of y){let h=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!h)continue;let p=(h.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(p)||h.querySelector('input[type="email"], input[name="email"]'))return!0;let v=h.querySelector('button[aria-label="Send without a note"]');if(v&&(v.disabled||v.getAttribute("aria-disabled")==="true"||(v.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let y=await e.$('button[aria-label="Dismiss"]');if(y)try{await y.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await k(500),a.reason="email_required",a}let g=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!g&&!b){let y=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let h=S.querySelector('button[aria-label="Add a note"]'),p=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!h,sendWithout:!!p}});if(y.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}if(y.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=S?.asElement?.()||null,b||await S.dispose().catch(()=>{})}}if(s)if(g&&o){if(console.log(" Adding personalized note..."),await g.click(),await k(1500),await e.$("div.modal-upsell")){let h=await Pa(e);return a.success=h,a.connectionSent=h,a.reason=h?"sent_without_note_upsell":"upsell_failed",a.withCustomMessage=!1,a}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let h=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),p=o.replace("{name}",h);await S.type(p,{delay:20}),await k(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v)return await Ze(e,v)?(console.log(" \u2713 Connection sent (with note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_with_note",a.withCustomMessage=!0,a.messageSent=p,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{if(b)return console.log(" Sending without note..."),await Ze(e,b)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a);if(g&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y)return await Ze(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y)return await Ze(e,y)?(console.log(" \u2713 Connection sent (without note)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),a.reason="modal_failed",a)}if(d.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 k(4e3)),await Ae(e),await k(500);let S=await e.$$('button[id*="profile-overflow-action"]'),h=null;for(let p of S){let v=await e.evaluate(C=>{let x=C.getBoundingClientRect();return{visible:x.width>0&&x.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},p);if(v.visible&&!v.inSticky){h=p;break}}!h&&S.length>0&&(h=S[S.length-1]);for(let p of S)p!==h&&await p.dispose().catch(()=>{});if(h)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),h),await k(500),await h.click().catch(()=>e.evaluate(v=>v.click(),h)),await k(2e3);let p=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(p){console.log(" Found Connect in More dropdown, clicking..."),a.method="more_dropdown",await e.evaluate(R=>R.click(),p),await k(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),await Ee(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(a.reason="premium_required",a);if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a;let x=await e.$('button[aria-label="Send without a note"]');if(x)return console.log(" Modal appeared via More dropdown, sending without note..."),await Ze(e,x)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),a.success=!0,a.connectionSent=!0,a.reason="sent_without_note",a.withCustomMessage=!1,a):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),a.reason="modal_failed",a);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(p){console.log(" More dropdown fallback failed:",p.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),a.reason="modal_failed",a}catch(l){console.error(` \u2717 Error: ${l.message}`),a.reason="error",a.error=l.message;let u=l.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return a.fatal=!0,a;try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{a.fatal=!0}return a}}async function Bs(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:r=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:a=null,excludeLocations:l=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
243
+ === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${r?"View Only":`Connect (max ${i})`}`),r||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!r){let m=dt();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let w=t[m];try{if(e.isClosed()){console.log(`
243
244
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
244
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!w.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let h=_o(w.profileUrl);if(h==="pending"||h==="connected"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${w.name||w.profileUrl} \u2014 skipped (db: ${h})`),h==="pending"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,a&&await a(w,f,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${w.name||w.profileUrl}`);let b=null;if(r){let y=await Pn(e,w.profileUrl);y?(Re(w.profileUrl,{...y,source:u}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=tn();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await Ln(e,w.profileUrl,{message:o,useCustomMessage:s,excludeLocations:l,source:u,skipQuotaGate:!0}),b.success)f.connectionsSent++;else switch(b.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(b?.fatal){console.log(`
245
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!w.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let g=Ro(w.profileUrl);if(g==="pending"||g==="connected"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${w.name||w.profileUrl} \u2014 skipped (db: ${g})`),g==="pending"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,a&&await a(w,f,{success:!1,reason:g,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${w.name||w.profileUrl}`);let b=null;if(r){let y=await Un(e,w.profileUrl);y?(Ie(w.profileUrl,{...y,source:u}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(f.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=sn();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await Bn(e,w.profileUrl,{message:o,useCustomMessage:s,excludeLocations:l,source:u,skipQuotaGate:!0}),b.success)f.connectionsSent++;else switch(b.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(b?.fatal){console.log(`
245
246
  \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(b?.reason==="error"){if(d++,d>=3){console.log(`
246
- \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(b&&b.reason&&(Eo(w.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&It(w.profileUrl,b.resolvedUrl),Co(w.profileUrl,{source:u||"funnel",jobId:w.jobId||w.fromJob?.jobId||null,jobTitle:w.fromJob?.title||null,jobCompany:w.fromJob?.company||null,action:b.reason})),a&&await a(w,f,b),m<t.length-1){let y=c+Math.random()*2e3;await k(y)}}if(console.log(`
247
- === Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!r){let m=ct();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}var Aa,Fs=Z(async()=>{Fe();await Ve();Aa={viewProfile:Pn,detectConnectionStatus:_e,findConnectButton:_t,clickConnectButton:jn,sendConnectionRequest:Ln,runFunnel:js,shouldExcludeLocation:Vt}});Fe();await Ve();wt();await Ve();wt();var qr=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),Br=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Bo=["vancouver","british columbia"],Hr=["canada","montreal","quebec","alberta","calgary","ottawa"],Jr=["toronto","ontario"],Vr=["india","pakistan","nigeria","philippines"];function Wr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)qr.has(u)&&s++,Br.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=Yr(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let r=(e.location||"").toLowerCase(),c=/remote/i.test(r)||e.workplaceType==="remote";Vr.some(u=>r.includes(u))?n-=30:c&&/united states|usa|\bus\b/i.test(r)?n+=25:c&&Bo.some(u=>r.includes(u))?n+=22:c?n+=20:Bo.some(u=>r.includes(u))?n+=18:Hr.some(u=>r.includes(u))?n+=10:Jr.some(u=>r.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let a=(e.seniority||"").toLowerCase();a.includes("senior")||a.includes("lead")||a.includes("staff")?n+=10:a.includes("mid")?n+=5:(a.includes("entry")||a.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let l=new Set(e.jobTags||[]);return l.has("managerial")?n+=8:l.has("senior-ic")&&(n+=5),l.has("junior")&&(n-=15),l.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function Ho(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=ht(),s=J(),i=new Set,r=new Set;for(let[f,d]of Object.entries(s))d.connectionStatus==="connected"&&i.add(f);let c={connectedRecruiters:i,conversationRecruiters:r},a=gt(),l=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([f,d])=>{if(typeof d!="object"||n&&!d.isEasyApply||d.applied)return!1;let m=a[f];return!(m&&l.has(m.status))}).map(([f,d])=>({jobId:f,score:Wr(d,c),job:d})).sort((f,d)=>{if(d.score!==f.score)return d.score-f.score;let m=f.job.scoutedAt||f.job.postedTime||"";return(d.job.scoutedAt||d.job.postedTime||"").localeCompare(m)}).slice(0,e)}function Yr(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await ot();import ei from"puppeteer";import{addExtra as ti}from"puppeteer-extra";import ni from"puppeteer-extra-plugin-stealth";Fe();await ot();et();et();import dn from"fs";import Gr from"path";var Kr={headless:!1,defaultViewport:null,protocolTimeout:3e5},St=new Set,Jo=!1;async function Pt(){let e=[...St].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});St.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function zr(){if(Jo)return;Jo=!0;let e=t=>async()=>{await Pt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Pt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Pt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Pt(),process.exit(0))}),process.on("exit",()=>{for(let t of St)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function fn(e){return Gr.join(e,".ilml-browser-session.json")}function Go(e,t={}){try{dn.writeFileSync(fn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Qr(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Go(e,n?{wsEndpoint:n}:{})}catch{}}function Xr(e){let t=Ko(e);t&&t.ownerPid===process.pid&&bt(e)}function bt(e){try{dn.rmSync(fn(e),{force:!0})}catch{}}function Ko(e){try{return JSON.parse(dn.readFileSync(fn(e),"utf-8"))}catch{return null}}function Vo(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Wo(e,t,n){let o,s=new Promise(r=>{o=setTimeout(()=>r(n),t)}),i=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([i,s])}async function Yo(e,t,{probeTimeoutMs:n=4e3}={}){let o=Ko(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Vo(o.ownerPid)?"live":(bt(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await Wo(i,n,s);if(r===s)return i.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!r)return bt(t),"free";if(Vo(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Wo(r.close().then(()=>!0).catch(()=>!1),n,!1))return bt(t),"free";try{r.disconnect()}catch{}return"live"}function Zr(e,t){e&&(zr(),St.add(e),e.on("disconnected",()=>{St.delete(e),t&&bt(t)}))}async function zo(e,t={}){let n=eo(),o={...Kr,...t,userDataDir:n},s=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Yo(e,n)==="live")throw new Error(s);Go(n);let i;try{i=await e.launch(o)}catch{if(await Yo(e,n)==="live")throw new Error(s);so(n);try{i=await e.launch(o)}catch(c){throw Xr(n),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: ${c.message})`)}}return Zr(i,n),Qr(n,i),{browser:i,profileDir:n,needsSeed:no(n)}}async function Qo(e,t){if(!t||!t.needsSeed)return!1;if(!Xn())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(...xt()),oo(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var es=ti(ei);es.use(ni());async function ts(){let{browser:e,profileDir:t,needsSeed:n}=await zo(es),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Qo(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}async function mn(e){await we(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(console.warn(" Inbox container not found via known selectors, proceeding..."),await k(3e3)),console.log(" Inbox loaded.")}async function ns(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let r=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!r)continue;let a=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",f=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,d,m;if(a.startsWith("You:"))d="me",m=a.slice(4).trim();else{let h=r.split(" ")[0];if(a.startsWith(r+":")||a.startsWith(h+":")){d="them";let b=a.indexOf(":");m=a.slice(b+1).trim()}else d="them",m=a}let w=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:f,lastMessageBy:d,x:w.x+w.width/2,y:w.y+w.height/2})}return o});for(let n of t)n.lastMessageTime=Qt(n.lastMessageTime)||n.lastMessageTime;return t}async function pn(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function oi(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let i=document.querySelector(s);if(i){let r=i.textContent?.trim()?.replace(/\s+/g," ");if(r&&r.length>1&&r.length<100&&!t.test(r))return r}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function hn(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function Xo(e,t){let n=await oi(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(c=>i.includes(c)),headerName:n}}async function jt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:a,headerName:l}=await Xo(e,t);if(a)return await k(500),{verified:!0,headerName:l};let u=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),d=Array.from(f).map(w=>w.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:d,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(d=>d.toLowerCase().includes(n.toLowerCase())))return await k(300),{verified:!0,headerName:n};await k(s),i+=s}let{match:r,headerName:c}=await Xo(e,t);return r?{verified:!0,headerName:c}:{verified:!1,headerName:c}}async function si(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let l=document.querySelector(".msg-overlay-conversation-bubble");l&&(r=l.querySelector(".msg-s-message-list-container")||l.querySelector(".msg-s-message-list"))}if(!r)return{found:!1};let c=r.querySelectorAll("li.msg-s-message-list__event").length;return r.scrollTop<=1?{found:!0,atTop:!0,msgCount:c}:(r.scrollTop=0,{found:!0,atTop:!1,msgCount:c})});if(!i.found||i.atTop)break;if(await k(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function gn(e,{scrollUp:t=!0}={}){t&&await si(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let r=i.querySelectorAll("li.msg-s-message-list__event");if(r.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(r=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function c(u){let f=u.getAttribute("data-event-urn");if(!f)return null;let d=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!d)return null;try{let w=atob(d[1]).match(/^(\d{13})/);if(!w)return null;let h=Number(w[1]);if(h>14200704e5&&h<20512224e5)return h}catch{}return null}let a="";function l(u,f,d){let m=c(u),h=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=u.querySelector(".msg-s-event-listitem__message-bubble");if(!b)return null;let y=b.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!y)return null;let S=m?new Date(m).toISOString():d?`${d} ${h}`.trim():h;return{sender:f,text:y,time:S}}for(let u of r){let f=u.querySelector("time.msg-s-message-list__time-heading");f&&(a=f.textContent?.trim()||a);let d=u.querySelectorAll(".msg-s-message-group");if(d.length>0)for(let m of d){let w=m.querySelector(".msg-s-message-group__name");w&&(s=w.textContent?.trim()||s);let h=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let y of b){let S=l(y,h,a);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let w of m){let h=w.querySelector(".msg-s-message-group__name");h&&(s=h.textContent?.trim()||s);let y=l(w,s||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of u){let d=f.textContent?.trim();d&&o.push({sender:"",text:d,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Qt(o.time)||o.time);return n}function yn(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),i=[...new Set(e.map(l=>l.sender).filter(l=>l&&l!=="Unknown"))],r=i.some(l=>{let u=l.toLowerCase();return u.includes(o)||s.some(f=>u.includes(f))}),c=z.toLowerCase().split(/\s+/),a=i.every(l=>{let u=l.toLowerCase();return c.some(f=>u.includes(f))});if(r)return!0;if(a){for(let l of e){let f=(l.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let d=f[1].toLowerCase();if(d!=="there"&&d!=="all"&&!(s.some(w=>w===d)||d===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let l=n.map(f=>f.toLowerCase());if(i.some(f=>{let d=f.toLowerCase();return l.some(m=>d.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Ge(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function wn(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=d=>Ge(d.sender)+"||"+Ge(d.text).replace(/\s+/g,""),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(d=>Ue.has(d.status)?!1:!o.has(n(d))),r=t.filter(d=>!s.has(n(d))),c=t.filter(d=>s.has(n(d))),a=e.filter(d=>Ue.has(d.status)),l=[...i,...c,...r],u=[];for(let d of l){let m=Ge(d.text),w=Ge(d.sender),h=!1;for(let b=0;b<u.length;b++){let y=u[b];if(Ge(y.sender)!==w)continue;let S=Ge(y.text);if(m.length>S.length&&m.endsWith(S)){h=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=d,h=!0;break}}h||u.push(d)}return[...u,...a]}async function os(e,t){await mn(e),await k(2500),await e.evaluate(()=>{let c=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let a of c){let l=document.querySelector(a);if(l){l.scrollTop=0;return}}}),await k(500);async function n(){return e.evaluate(c=>{let a=document.querySelectorAll(".msg-conversation-listitem");for(let l of a)if(l.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===c){let d=l.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t)}let o=await n(),s=50,i=-1,r=0;for(let c=0;c<s&&!o;c++){let a=await pn(e);if(!a)break;if(a.scrollTop===i){if(r++,r>=2)break}else r=0,i=a.scrollTop;await k(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await k(3e3),jt(e,t)):{verified:!1,headerName:null}}async function bn(e,t){let n=await e.evaluate(r=>{let c=document.querySelectorAll(".msg-conversation-listitem");for(let a of c)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===r){let f=a.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await k(3e3);let r=await jt(e,t);if(r.verified)return r}let o=lo(t),s=o!==t?[t,o]:[t];for(let r of s)if(await Zo(e,r,t)){let a=await jt(e,t);if(a.verified)return a}let i=co(o);if(i!==o&&i.length>0&&await Zo(e,i,t,{requireUnique:!0})){let c=await jt(e,t);if(c.verified)return c}return{verified:!1,headerName:null}}async function Zo(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await k(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await k(300),await i.type(t,{delay:30}),await k(500),await e.keyboard.press("Enter"),await k(3500);let r=await e.evaluate((c,a)=>{let l=c.split(" ")[0].toLowerCase(),u=c.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),d=[],m=[];for(let h of f){let y=h.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=y.toLowerCase();if(S.includes(l)){let g=h.getBoundingClientRect();if(g.height>0){let p=y.includes(",")||/\d+ other/.test(y),v=S===u?3:S.includes(u)?2:1,C={text:y,isGroup:p,score:v,x:g.x+g.width/2,y:g.y+g.height/2};p?m.push(C):d.push(C)}}}d.sort((h,b)=>b.score-h.score);let w=[...d,...m];return a&&w.length!==1?null:d[0]||m[0]||null},n,s);return r?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(r.x,r.y),!0):!1}async function ke(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await k(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await k(1e3))}await $n();import"dotenv/config";import*as ne from"fs";import*as $e from"path";import{fileURLToPath as $i}from"url";import"dotenv/config";import{createGraphClient as gi,resolveToken as yi}from"@ilivemylife/graph-sdk";import{config as wi}from"dotenv";wi();var ps=yi()||process.env.TOKEN;ps||(console.error(`
247
+ \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(b&&b.reason&&(To(w.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&Nt(w.profileUrl,b.resolvedUrl),xo(w.profileUrl,{source:u||"funnel",jobId:w.jobId||w.fromJob?.jobId||null,jobTitle:w.fromJob?.title||null,jobCompany:w.fromJob?.company||null,action:b.reason})),a&&await a(w,f,b),m<t.length-1){let y=c+Math.random()*2e3;await k(y)}}if(console.log(`
248
+ === Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!r){let m=dt();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}var La,Js=Z(async()=>{qe();await Ye();La={viewProfile:Un,detectConnectionStatus:Ee,findConnectButton:xt,clickConnectButton:qn,sendConnectionRequest:Bn,runFunnel:Bs,shouldExcludeLocation:Gt}});qe();await Ye();St();await Ye();St();var Wr=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),Yr=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Wo=["vancouver","british columbia"],Gr=["canada","montreal","quebec","alberta","calgary","ottawa"],zr=["toronto","ontario"],Kr=["india","pakistan","nigeria","philippines"];function Qr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)Wr.has(u)&&s++,Yr.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=Xr(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let r=(e.location||"").toLowerCase(),c=/remote/i.test(r)||e.workplaceType==="remote";Kr.some(u=>r.includes(u))?n-=30:c&&/united states|usa|\bus\b/i.test(r)?n+=25:c&&Wo.some(u=>r.includes(u))?n+=22:c?n+=20:Wo.some(u=>r.includes(u))?n+=18:Gr.some(u=>r.includes(u))?n+=10:zr.some(u=>r.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let a=(e.seniority||"").toLowerCase();a.includes("senior")||a.includes("lead")||a.includes("staff")?n+=10:a.includes("mid")?n+=5:(a.includes("entry")||a.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let l=new Set(e.jobTags||[]);return l.has("managerial")?n+=8:l.has("senior-ic")&&(n+=5),l.has("junior")&&(n-=15),l.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function Yo(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=yt(),s=V(),i=new Set,r=new Set;for(let[f,d]of Object.entries(s))d.connectionStatus==="connected"&&i.add(f);let c={connectedRecruiters:i,conversationRecruiters:r},a=wt(),l=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([f,d])=>{if(typeof d!="object"||n&&!d.isEasyApply||d.applied)return!1;let m=a[f];return!(m&&l.has(m.status))}).map(([f,d])=>({jobId:f,score:Qr(d,c),job:d})).sort((f,d)=>{if(d.score!==f.score)return d.score-f.score;let m=f.job.scoutedAt||f.job.postedTime||"";return(d.job.scoutedAt||d.job.postedTime||"").localeCompare(m)}).slice(0,e)}function Xr(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await rt();import ri from"puppeteer";import{addExtra as ii}from"puppeteer-extra";import ai from"puppeteer-extra-plugin-stealth";qe();await rt();nt();nt();import pn from"fs";import Zr from"path";var ei={headless:!1,defaultViewport:null,protocolTimeout:3e5},kt=new Set,Go=!1;async function Ft(){let e=[...kt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});kt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function ti(){if(Go)return;Go=!0;let e=t=>async()=>{await Ft(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Ft(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Ft(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Ft(),process.exit(0))}),process.on("exit",()=>{for(let t of kt)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function gn(e){return Zr.join(e,".ilml-browser-session.json")}function Xo(e,t={}){try{pn.writeFileSync(gn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function ni(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Xo(e,n?{wsEndpoint:n}:{})}catch{}}function oi(e){let t=Zo(e);t&&t.ownerPid===process.pid&&vt(e)}function vt(e){try{pn.rmSync(gn(e),{force:!0})}catch{}}function Zo(e){try{return JSON.parse(pn.readFileSync(gn(e),"utf-8"))}catch{return null}}function zo(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Ko(e,t,n){let o,s=new Promise(r=>{o=setTimeout(()=>r(n),t)}),i=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([i,s])}async function Qo(e,t,{probeTimeoutMs:n=4e3}={}){let o=Zo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&zo(o.ownerPid)?"live":(vt(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await Ko(i,n,s);if(r===s)return i.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!r)return vt(t),"free";if(zo(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Ko(r.close().then(()=>!0).catch(()=>!1),n,!1))return vt(t),"free";try{r.disconnect()}catch{}return"live"}function si(e,t){e&&(ti(),kt.add(e),e.on("disconnected",()=>{kt.delete(e),t&&vt(t)}))}async function es(e,t={}){let n=so(),o={...ei,...t,userDataDir:n},s=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Qo(e,n)==="live")throw new Error(s);Xo(n);let i;try{i=await e.launch(o)}catch{if(await Qo(e,n)==="live")throw new Error(s);lo(n);try{i=await e.launch(o)}catch(c){throw oi(n),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: ${c.message})`)}}return si(i,n),ni(n,i),{browser:i,profileDir:n,needsSeed:io(n)}}async function ts(e,t){if(!t||!t.needsSeed)return!1;if(!no())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(...It()),ao(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var ss=ii(ri);ss.use(ai());async function rs(){let{browser:e,profileDir:t,needsSeed:n}=await es(ss),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await ts(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}async function hn(e){await be(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(console.warn(" Inbox container not found via known selectors, proceeding..."),await k(3e3)),console.log(" Inbox loaded.")}async function is(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let r=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!r)continue;let a=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",f=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,d,m;if(a.startsWith("You:"))d="me",m=a.slice(4).trim();else{let g=r.split(" ")[0];if(a.startsWith(r+":")||a.startsWith(g+":")){d="them";let b=a.indexOf(":");m=a.slice(b+1).trim()}else d="them",m=a}let w=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:f,lastMessageBy:d,x:w.x+w.width/2,y:w.y+w.height/2})}return o});for(let n of t)n.lastMessageTime=en(n.lastMessageTime)||n.lastMessageTime;return t}async function yn(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function li(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let i=document.querySelector(s);if(i){let r=i.textContent?.trim()?.replace(/\s+/g," ");if(r&&r.length>1&&r.length<100&&!t.test(r))return r}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function wn(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function ns(e,t){let n=await li(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(c=>i.includes(c)),headerName:n}}async function Ut(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:a,headerName:l}=await ns(e,t);if(a)return await k(500),{verified:!0,headerName:l};let u=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),d=Array.from(f).map(w=>w.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:d,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(d=>d.toLowerCase().includes(n.toLowerCase())))return await k(300),{verified:!0,headerName:n};await k(s),i+=s}let{match:r,headerName:c}=await ns(e,t);return r?{verified:!0,headerName:c}:{verified:!1,headerName:c}}async function ci(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let l=document.querySelector(".msg-overlay-conversation-bubble");l&&(r=l.querySelector(".msg-s-message-list-container")||l.querySelector(".msg-s-message-list"))}if(!r)return{found:!1};let c=r.querySelectorAll("li.msg-s-message-list__event").length;return r.scrollTop<=1?{found:!0,atTop:!0,msgCount:c}:(r.scrollTop=0,{found:!0,atTop:!1,msgCount:c})});if(!i.found||i.atTop)break;if(await k(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function bn(e,{scrollUp:t=!0}={}){t&&await ci(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let r=i.querySelectorAll("li.msg-s-message-list__event");if(r.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(r=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function c(u){let f=u.getAttribute("data-event-urn");if(!f)return null;let d=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!d)return null;try{let w=atob(d[1]).match(/^(\d{13})/);if(!w)return null;let g=Number(w[1]);if(g>14200704e5&&g<20512224e5)return g}catch{}return null}let a="";function l(u,f,d){let m=c(u),g=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=u.querySelector(".msg-s-event-listitem__message-bubble");if(!b)return null;let y=b.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!y)return null;let S=m?new Date(m).toISOString():d?`${d} ${g}`.trim():g;return{sender:f,text:y,time:S}}for(let u of r){let f=u.querySelector("time.msg-s-message-list__time-heading");f&&(a=f.textContent?.trim()||a);let d=u.querySelectorAll(".msg-s-message-group");if(d.length>0)for(let m of d){let w=m.querySelector(".msg-s-message-group__name");w&&(s=w.textContent?.trim()||s);let g=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let y of b){let S=l(y,g,a);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let w of m){let g=w.querySelector(".msg-s-message-group__name");g&&(s=g.textContent?.trim()||s);let y=l(w,s||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of u){let d=f.textContent?.trim();d&&o.push({sender:"",text:d,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=en(o.time)||o.time);return n}function Sn(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),i=[...new Set(e.map(l=>l.sender).filter(l=>l&&l!=="Unknown"))],r=i.some(l=>{let u=l.toLowerCase();return u.includes(o)||s.some(f=>u.includes(f))}),c=K.toLowerCase().split(/\s+/),a=i.every(l=>{let u=l.toLowerCase();return c.some(f=>u.includes(f))});if(r)return!0;if(a){for(let l of e){let f=(l.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let d=f[1].toLowerCase();if(d!=="there"&&d!=="all"&&!(s.some(w=>w===d)||d===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let l=n.map(f=>f.toLowerCase());if(i.some(f=>{let d=f.toLowerCase();return l.some(m=>d.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Ke(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function vn(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=d=>Ke(d.sender)+"||"+Ke(d.text).replace(/\s+/g,""),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(d=>Be.has(d.status)?!1:!o.has(n(d))),r=t.filter(d=>!s.has(n(d))),c=t.filter(d=>s.has(n(d))),a=e.filter(d=>Be.has(d.status)),l=[...i,...c,...r],u=[];for(let d of l){let m=Ke(d.text),w=Ke(d.sender),g=!1;for(let b=0;b<u.length;b++){let y=u[b];if(Ke(y.sender)!==w)continue;let S=Ke(y.text);if(m.length>S.length&&m.endsWith(S)){g=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=d,g=!0;break}}g||u.push(d)}return[...u,...a]}async function as(e,t){await hn(e),await k(2500),await e.evaluate(()=>{let c=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let a of c){let l=document.querySelector(a);if(l){l.scrollTop=0;return}}}),await k(500);async function n(){return e.evaluate(c=>{let a=document.querySelectorAll(".msg-conversation-listitem");for(let l of a)if(l.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===c){let d=l.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t)}let o=await n(),s=50,i=-1,r=0;for(let c=0;c<s&&!o;c++){let a=await yn(e);if(!a)break;if(a.scrollTop===i){if(r++,r>=2)break}else r=0,i=a.scrollTop;await k(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await k(3e3),Ut(e,t)):{verified:!1,headerName:null}}async function kn(e,t){let n=await e.evaluate(r=>{let c=document.querySelectorAll(".msg-conversation-listitem");for(let a of c)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===r){let f=a.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await k(3e3);let r=await Ut(e,t);if(r.verified)return r}let o=mo(t),s=o!==t?[t,o]:[t];for(let r of s)if(await os(e,r,t)){let a=await Ut(e,t);if(a.verified)return a}let i=po(o);if(i!==o&&i.length>0&&await os(e,i,t,{requireUnique:!0})){let c=await Ut(e,t);if(c.verified)return c}return{verified:!1,headerName:null}}async function os(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await k(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await k(300),await i.type(t,{delay:30}),await k(500),await e.keyboard.press("Enter"),await k(3500);let r=await e.evaluate((c,a)=>{let l=c.split(" ")[0].toLowerCase(),u=c.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),d=[],m=[];for(let g of f){let y=g.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=y.toLowerCase();if(S.includes(l)){let h=g.getBoundingClientRect();if(h.height>0){let p=y.includes(",")||/\d+ other/.test(y),v=S===u?3:S.includes(u)?2:1,C={text:y,isGroup:p,score:v,x:h.x+h.width/2,y:h.y+h.height/2};p?m.push(C):d.push(C)}}}d.sort((g,b)=>b.score-g.score);let w=[...d,...m];return a&&w.length!==1?null:d[0]||m[0]||null},n,s);return r?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(r.x,r.y),!0):!1}async function $e(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await k(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await k(1e3))}await En();import"dotenv/config";import*as oe from"fs";import*as Ce from"path";import{fileURLToPath as xi}from"url";import"dotenv/config";import{createGraphClient as vi,resolveToken as ki}from"@ilivemylife/graph-sdk";import{config as $i}from"dotenv";$i();var ws=ki()||process.env.TOKEN;ws||(console.error(`
248
249
  [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.
249
250
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
250
251
  `),console.error(` Or add ILML_TOKEN=... to .env
251
- `),process.exit(1));var hs=gi({token:ps});function bi(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`}var Si={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function vi(e){let t=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(t)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(t)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(t)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(t)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(t)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function ki({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let r=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",c=n==="error"?"stopped early":n==="quota-reached"?"daily limit reached":"done",a=Si[e]||e,l=t&&t!=="default"?` \xB7 ${t}`:"",u=new Date().toISOString().slice(0,16).replace("T"," "),f=i?` \xB7 ${bi(i)}`:"",d=[];d.push(`## ${r} ${a} \u2014 ${c}`),d.push(`_${u}${l}${f}_`),d.push("");for(let m of o)d.push(`- ${m}`);if(n==="error"){d.push(""),d.push(`**What happened:** ${vi(s)}`);let m=String(s||"").replace(/\s+/g," ").trim();m&&d.push(`_Technical detail: ${m.slice(0,140)}_`)}return d.join(`
252
- `)}async function Cn({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let r=process.env.NODE_RUN_REPORTS;if(!r||!Array.isArray(o)||o.length===0)return;let c=ki({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i});try{await hs.addMessage(r,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Ci=$i(import.meta.url),_i=$e.dirname($e.dirname(Ci)),_n=process.env.DATA_DIR?$e.resolve(process.env.DATA_DIR,"collected-profiles"):$e.join(_i,"collected-profiles"),En=$e.join(_n,"run-log.json");function Ei(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ne.writeFileSync(o,n);for(let s=0;s<3;s++)try{ne.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function qt(){try{if(!ne.existsSync(En))return{runs:[]};let e=JSON.parse(ne.readFileSync(En,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function gs(e){ne.existsSync(_n)||ne.mkdirSync(_n,{recursive:!0});try{Ei(En,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Bt(e,t="default"){let n=qt();for(let r of n.runs)r.status==="running"&&(r.status="interrupted",r.result="interrupted",r.timestamp&&(r.duration=Date.now()-new Date(r.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(r=>new Date(r.timestamp).getTime()>i),gs(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function vt(e,t,n=null,o=null){if(!e)return;let s=null;try{let c=qt(),a=c.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration;else{let l=c.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,s=l.duration)}gs(c)}catch(c){console.error(`[runLog] Failed to end run: ${c.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null,r=n&&n.__deferReport===!0;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS&&!r){let c=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Cn({scriptName:e.script,mode:e.mode,status:c,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}async function ys(e,t,n,o,s={}){let{rethrow:i=!0}=s,r=Bt(e,t),c={},a=null;try{await n(c)}catch(f){a=f}let l=[];try{let f=o?o(c):[];l=(Array.isArray(f)?f:[]).filter(d=>typeof d=="string"&&d.trim())}catch(f){console.error(`[runLog] summarize threw (report still sent): ${f.message}`)}if(l.length===0&&a&&(l=["(crashed before any progress was recorded)"]),a){let f=t&&t!=="default"?` (${t})`:"";console.error(`
253
- \u2717 ${e}${f} failed: ${a.message||a}`)}let u=Date.now()-r.startTime;try{vt(r,a?"error":"success",{...c,summaryLines:l,__deferReport:!0},a?a.message||String(a):null)}catch(f){console.error(`[runLog] endRun failed: ${f.message}`)}if(l.length>0&&process.env.NODE_RUN_REPORTS){let f=a?"error":c.dailyLimitHit?"quota-reached":"done";try{await Cn({scriptName:r.script,mode:r.mode,status:f,summaryLines:l,error:a?a.message||String(a):null,duration:u})}catch(d){console.error(`[runLog] report post failed: ${d.message}`)}}if(a&&i)throw a;return c}function Ai(){let e=new Date().toISOString().slice(0,10),t=qt(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let s=n[o.script];s.total++,o.status==="success"?s.success++:o.status==="error"?s.error++:o.status==="interrupted"?s.interrupted++:o.status==="partial"?s.partial++:o.status==="running"&&s.running++,s.lastRun=o}return n}function xi(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:s===1?"yesterday":`${s} days ago`}function ws(){let e=["sync-all","messages","funnel","sync","apply"],t=qt(),n=Ai(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let i of e){let r=t.runs.filter(h=>h.script===i),c=[...r].reverse().find(h=>h.status==="success"),a=r[r.length-1],l=c||a,u=l?xi(l.timestamp):"never",d=(l?Math.floor((Date.now()-new Date(l.timestamp).getTime())/864e5):1/0)>1?" \u26A0":l?.status==="error"?" \u2717":" \u2713",m="";if(l?.stats){let h=l.stats,b=Object.entries(h).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,S])=>`${S} ${y}`);b.length&&(m=` (${b.join(", ")})`)}let w=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${u.padEnd(16)}${w}${m}${d}`)}let s=Object.entries(n);if(s.length>0){o.push("");for(let[i,r]of s){let c=[];r.success&&c.push(`${r.success} success`),r.error&&c.push(`${r.error} error`),r.interrupted&&c.push(`${r.interrupted} interrupted`),r.running&&c.push(`${r.running} running`),o.push(` Today: ${i} \xD7${r.total} (${c.join(", ")})`)}}return o.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),o.join(`
254
- `)}import"dotenv/config";import*as E from"fs";import*as Nn from"os";import*as P from"path";import{fileURLToPath as Xi}from"url";var Tn={};ue(Tn,{NAME:()=>Ri,VERSION:()=>Ti,up:()=>Oi});import*as oe from"fs";import*as Ht from"path";var Ti=1,Ri="normalize-jobs-and-questions",Ii=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Di=50;function An(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function xn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(s){try{oe.unlinkSync(o)}catch{}throw s}try{oe.renameSync(o,e)}catch(s){try{oe.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Oi(e,t){let n=Ht.join(e,"jobs.json"),o=Ht.join(t,"scouted-jobs.json"),s=Ht.join(e,"application-questions.json"),i=An(n)||{},r=An(o)||{},c=0,a=[];for(let u of Object.keys(i)){if(!r[u])continue;let f=r[u],d=i[u];for(let m of Ii)f[m]!=null&&d[m]==null&&(d[m]=f[m]);a.push(u),c++}c>0?(xn(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=An(s);if(l&&Array.isArray(l.applications)){let u={},f=0;for(let d of l.applications){let m=d.jobId||"unknown";u[m]||(u[m]={applications:[]});let w=(d.questions||[]).map(h=>{let b={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=Di?b.options=h.options:(b.optionsOmitted=!0,f++)),h.page&&(b.page=h.page),h.wasPreFilled&&(b.wasPreFilled=!0),h.wasRetry&&(b.wasRetry=!0),b});u[m].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||w.length,questions:w})}xn(s,u),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else l&&!l.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let u of a)delete r[u];xn(o,r),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(r).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Rn={};ue(Rn,{NAME:()=>Mi,VERSION:()=>Ni,up:()=>Li});import*as se from"fs";import*as bs from"path";var Ni=2,Mi="reset-unread-flags";function Pi(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function ji(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{se.writeFileSync(o,n)}catch(s){try{se.unlinkSync(o)}catch{}throw s}try{se.renameSync(o,e)}catch(s){try{se.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Li(e){let t=bs.join(e,"conversations.json"),n=Pi(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}ji(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var In={};ue(In,{NAME:()=>Ui,VERSION:()=>Fi,up:()=>Vi});import*as re from"fs";import*as Ss from"path";var Fi=3,Ui="recompute-last-message-by",qi=new Set(["draft","confirmed","rejected","needs_review"]);function Bi(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function Hi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{re.writeFileSync(o,n)}catch(s){try{re.unlinkSync(o)}catch{}throw s}try{re.renameSync(o,e)}catch(s){try{re.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function Ji(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!qi.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,r)=>r.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let r=i.sender;if(r===t)return"me";if(r!=="Unknown"&&r!=="")return"them"}return"them"}async function Vi(e){let t=Ss.join(e,"conversations.json"),n=Bi(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 s=0,i=0,r=0;for(let c of Object.keys(n)){let a=n[c];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,i++);let l=Array.isArray(a.messages)?a.messages:[],u=Ji(l,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&r++,a.lastMessageBy=u,a.conversationStatus=f,s++}if(s===0){console.log(" No conversations to recompute.");return}Hi(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${r} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Dn={};ue(Dn,{NAME:()=>Yi,VERSION:()=>Wi,up:()=>Qi});import*as ie from"fs";import*as vs from"path";var Wi=4,Yi="split-connection-timestamps",Gi=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ki(e){if(!ie.existsSync(e))return null;let t=ie.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function zi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ie.writeFileSync(o,n)}catch(s){try{ie.unlinkSync(o)}catch{}throw s}try{ie.renameSync(o,e)}catch(s){try{ie.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Qi(e){let t=vs.join(e,"people.json"),n=Ki(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let i of Object.keys(n)){let r=n[i];!r||typeof r!="object"||(s++,Gi.has(r.connectionStatus)&&r.connectionDate&&!r.requestedConnectionAt&&(r.requestedConnectionAt=r.connectionDate,r.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}zi(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Ve();wt();var Zi=Xi(import.meta.url),ea=P.dirname(Zi),ta=P.dirname(P.dirname(ea));function na(e){return e&&(e==="~"?Nn.homedir():e.startsWith("~/")||e.startsWith("~\\")?P.join(Nn.homedir(),e.slice(2)):e)}var de=process.env.DATA_DIR?P.resolve(na(process.env.DATA_DIR)):ta,Me=P.join(de,"collected-profiles"),Pe=P.join(de,"market-research"),G=P.join(de,".schema-version"),ks=[P.join(Me,".schema-version"),P.join(Pe,".schema-version")],Ce=4,he=[{version:1,module:Tn},{version:2,module:Rn},{version:3,module:In},{version:4,module:Dn}];(function(){he.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of he){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 s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=he.length?he[he.length-1].version:0;if(n!==Ce)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${Ce}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<he.length;o++){let s=o+1;if(he[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${he[o].version}`)}})();function Es(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
252
+ `),process.exit(1));var bs=vi({token:ws});function Ci(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`}var _i={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function Ei(e){let t=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(t)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(t)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(t)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(t)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(t)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function Ai({scriptName:e,mode:t,status:n,summaryLines:o,error:s,stoppedReason:i,duration:r}){let c=n==="error"||n==="stopped"?n==="error"?"\u2717":"\u26A0":n==="quota-reached"?"\u26A0":"\u2713",a=n==="error"?"stopped early":n==="stopped"?`stopped \u2014 ${i||"did not finish"}`:n==="quota-reached"?"daily limit reached":"done",l=_i[e]||e,u=t&&t!=="default"?` \xB7 ${t}`:"",f=new Date().toISOString().slice(0,16).replace("T"," "),d=r?` \xB7 ${Ci(r)}`:"",m=[];m.push(`## ${c} ${l} \u2014 ${a}`),m.push(`_${f}${u}${d}_`),m.push("");for(let w of o)m.push(`- ${w}`);if(n==="error"){m.push(""),m.push(`**What happened:** ${Ei(s)}`);let w=String(s||"").replace(/\s+/g," ").trim();w&&m.push(`_Technical detail: ${w.slice(0,140)}_`)}return m.join(`
253
+ `)}async function An({scriptName:e,mode:t,status:n,summaryLines:o,error:s,stoppedReason:i,duration:r}){let c=process.env.NODE_RUN_REPORTS;if(!c||!Array.isArray(o)||o.length===0)return;let a=Ai({scriptName:e,mode:t,status:n,summaryLines:o,error:s,stoppedReason:i,duration:r});try{await bs.addMessage(c,a)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var Ri=xi(import.meta.url),Ti=Ce.dirname(Ce.dirname(Ri)),xn=process.env.DATA_DIR?Ce.resolve(process.env.DATA_DIR,"collected-profiles"):Ce.join(Ti,"collected-profiles"),Rn=Ce.join(xn,"run-log.json");function Ii(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";oe.writeFileSync(o,n);for(let s=0;s<3;s++)try{oe.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function Jt(){try{if(!oe.existsSync(Rn))return{runs:[]};let e=JSON.parse(oe.readFileSync(Rn,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ss(e){oe.existsSync(xn)||oe.mkdirSync(xn,{recursive:!0});try{Ii(Rn,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Vt(e,t="default"){let n=Jt();for(let r of n.runs)r.status==="running"&&(r.status="interrupted",r.result="interrupted",r.timestamp&&(r.duration=Date.now()-new Date(r.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(r=>new Date(r.timestamp).getTime()>i),Ss(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function $t(e,t,n=null,o=null){if(!e)return;let s=null;try{let c=Jt(),a=c.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration;else{let l=c.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,s=l.duration)}Ss(c)}catch(c){console.error(`[runLog] Failed to end run: ${c.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null,r=n&&n.__deferReport===!0;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS&&!r){let c=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";An({scriptName:e.script,mode:e.mode,status:c,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}async function vs(e,t,n,o,s={}){let{rethrow:i=!0}=s,r=Vt(e,t),c={},a=null;try{await n(c)}catch(d){a=d}let l=[];try{let d=o?o(c):[];l=(Array.isArray(d)?d:[]).filter(m=>typeof m=="string"&&m.trim())}catch(d){console.error(`[runLog] summarize threw (report still sent): ${d.message}`)}if(l.length===0&&a&&(l=["(crashed before any progress was recorded)"]),a){let d=t&&t!=="default"?` (${t})`:"";console.error(`
254
+ \u2717 ${e}${d} failed: ${a.message||a}`)}let u=Date.now()-r.startTime,f=!a&&c.stoppedReason?String(c.stoppedReason):null;try{$t(r,a?"error":f?"partial":"success",{...c,summaryLines:l,__deferReport:!0},a?a.message||String(a):null)}catch(d){console.error(`[runLog] endRun failed: ${d.message}`)}if(l.length>0&&process.env.NODE_RUN_REPORTS){let d=a?"error":f?"stopped":c.dailyLimitHit?"quota-reached":"done";try{await An({scriptName:r.script,mode:r.mode,status:d,summaryLines:l,error:a?a.message||String(a):null,stoppedReason:f,duration:u})}catch(m){console.error(`[runLog] report post failed: ${m.message}`)}}if(a&&i)throw a;return c}function Di(){let e=new Date().toISOString().slice(0,10),t=Jt(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let s=n[o.script];s.total++,o.status==="success"?s.success++:o.status==="error"?s.error++:o.status==="interrupted"?s.interrupted++:o.status==="partial"?s.partial++:o.status==="running"&&s.running++,s.lastRun=o}return n}function Oi(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:s===1?"yesterday":`${s} days ago`}function ks(){let e=["sync-all","messages","funnel","sync","apply"],t=Jt(),n=Di(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let i of e){let r=t.runs.filter(g=>g.script===i),c=[...r].reverse().find(g=>g.status==="success"),a=r[r.length-1],l=c||a,u=l?Oi(l.timestamp):"never",d=(l?Math.floor((Date.now()-new Date(l.timestamp).getTime())/864e5):1/0)>1?" \u26A0":l?.status==="error"?" \u2717":" \u2713",m="";if(l?.stats){let g=l.stats,b=Object.entries(g).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,S])=>`${S} ${y}`);b.length&&(m=` (${b.join(", ")})`)}let w=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${u.padEnd(16)}${w}${m}${d}`)}let s=Object.entries(n);if(s.length>0){o.push("");for(let[i,r]of s){let c=[];r.success&&c.push(`${r.success} success`),r.error&&c.push(`${r.error} error`),r.interrupted&&c.push(`${r.interrupted} interrupted`),r.running&&c.push(`${r.running} running`),o.push(` Today: ${i} \xD7${r.total} (${c.join(", ")})`)}}return o.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),o.join(`
255
+ `)}import"dotenv/config";import*as A from"fs";import*as Ln from"os";import*as P from"path";import{fileURLToPath as ca}from"url";var Dn={};ee(Dn,{NAME:()=>Mi,VERSION:()=>Ni,up:()=>Li});import*as se from"fs";import*as Wt from"path";var Ni=1,Mi="normalize-jobs-and-questions",Pi=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],ji=50;function Tn(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function In(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{se.writeFileSync(o,n)}catch(s){try{se.unlinkSync(o)}catch{}throw s}try{se.renameSync(o,e)}catch(s){try{se.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Li(e,t){let n=Wt.join(e,"jobs.json"),o=Wt.join(t,"scouted-jobs.json"),s=Wt.join(e,"application-questions.json"),i=Tn(n)||{},r=Tn(o)||{},c=0,a=[];for(let u of Object.keys(i)){if(!r[u])continue;let f=r[u],d=i[u];for(let m of Pi)f[m]!=null&&d[m]==null&&(d[m]=f[m]);a.push(u),c++}c>0?(In(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=Tn(s);if(l&&Array.isArray(l.applications)){let u={},f=0;for(let d of l.applications){let m=d.jobId||"unknown";u[m]||(u[m]={applications:[]});let w=(d.questions||[]).map(g=>{let b={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=ji?b.options=g.options:(b.optionsOmitted=!0,f++)),g.page&&(b.page=g.page),g.wasPreFilled&&(b.wasPreFilled=!0),g.wasRetry&&(b.wasRetry=!0),b});u[m].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||w.length,questions:w})}In(s,u),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else l&&!l.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let u of a)delete r[u];In(o,r),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(r).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var On={};ee(On,{NAME:()=>Ui,VERSION:()=>Fi,up:()=>Hi});import*as re from"fs";import*as $s from"path";var Fi=2,Ui="reset-unread-flags";function qi(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function Bi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{re.writeFileSync(o,n)}catch(s){try{re.unlinkSync(o)}catch{}throw s}try{re.renameSync(o,e)}catch(s){try{re.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Hi(e){let t=$s.join(e,"conversations.json"),n=qi(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Bi(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Nn={};ee(Nn,{NAME:()=>Vi,VERSION:()=>Ji,up:()=>Ki});import*as ie from"fs";import*as Cs from"path";var Ji=3,Vi="recompute-last-message-by",Wi=new Set(["draft","confirmed","rejected","needs_review"]);function Yi(e){return ie.existsSync(e)?JSON.parse(ie.readFileSync(e,"utf-8")):null}function Gi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ie.writeFileSync(o,n)}catch(s){try{ie.unlinkSync(o)}catch{}throw s}try{ie.renameSync(o,e)}catch(s){try{ie.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function zi(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Wi.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,r)=>r.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let r=i.sender;if(r===t)return"me";if(r!=="Unknown"&&r!=="")return"them"}return"them"}async function Ki(e){let t=Cs.join(e,"conversations.json"),n=Yi(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 s=0,i=0,r=0;for(let c of Object.keys(n)){let a=n[c];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,i++);let l=Array.isArray(a.messages)?a.messages:[],u=zi(l,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&r++,a.lastMessageBy=u,a.conversationStatus=f,s++}if(s===0){console.log(" No conversations to recompute.");return}Gi(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${r} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Mn={};ee(Mn,{NAME:()=>Xi,VERSION:()=>Qi,up:()=>na});import*as ae from"fs";import*as _s from"path";var Qi=4,Xi="split-connection-timestamps",Zi=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ea(e){if(!ae.existsSync(e))return null;let t=ae.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ta(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ae.writeFileSync(o,n)}catch(s){try{ae.unlinkSync(o)}catch{}throw s}try{ae.renameSync(o,e)}catch(s){try{ae.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function na(e){let t=_s.join(e,"people.json"),n=ea(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let i of Object.keys(n)){let r=n[i];!r||typeof r!="object"||(s++,Zi.has(r.connectionStatus)&&r.connectionDate&&!r.requestedConnectionAt&&(r.requestedConnectionAt=r.connectionDate,r.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}ta(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var Pn={};ee(Pn,{NAME:()=>sa,VERSION:()=>oa,up:()=>la});import*as le from"fs";import*as Es from"path";var oa=5,sa="rename-headline-to-title",Me=/[·•]\s*(1st|2nd|3rd)\+?/i,ra=e=>(e||"").replace(/\s+/g," ").trim(),Ct=e=>ra(e).replace(/^[+·•\s]+/,"").replace(/[·•\s]+$/,"");function ia(e){if(!le.existsSync(e))return null;let t=le.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function aa(e,t){let n=JSON.stringify(t),o=e+".tmp";try{le.writeFileSync(o,n)}catch(s){try{le.unlinkSync(o)}catch{}throw s}try{le.renameSync(o,e)}catch(s){try{le.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function la(e,t){let n=Es.join(t,"discovered-people.json"),o=ia(n);if(!o||typeof o!="object"){console.log(" discovered-people.json not found \u2014 nothing to migrate.");return}let s=Array.isArray(o)?o:Object.values(o),i=0,r=0,c=0;for(let a of s)if(!(!a||typeof a!="object")){if(i++,a.name&&Me.test(a.name)){let l=Ct(String(a.name).split(Me)[0]),u=String(a.name).match(/[·•]\s*(?:1st|2nd|3rd)\+?\s*(.+)$/i),f=u?Ct(u[1]):"";l&&(a.name=l,r++),f&&(!a.headline||Me.test(String(a.headline))||!Ct(a.headline))&&(a.headline=f)}if(Object.prototype.hasOwnProperty.call(a,"headline")){let l=Ct(a.headline||"");Me.test(l)&&(l=""),(!a.title||Me.test(String(a.title)))&&(a.title=l||(a.title&&!Me.test(String(a.title))?a.title:null)||null),delete a.headline,c++}else if(typeof a.title=="string"){let l=Ct(a.title);l&&!Me.test(l)&&l!==a.title&&(a.title=l)}}if(c===0&&r===0){console.log(` Scanned ${i} discovered people \u2014 already unified (no headline field, clean names).`);return}aa(n,o),console.log(` discovered-people.json: scanned ${i}, de-glued ${r} names, moved ${c} headline\u2192title.`),console.log(" Every record now carries a single `title` field (matches people.json).")}await Ye();St();var ua=ca(import.meta.url),da=P.dirname(ua),fa=P.dirname(P.dirname(da));function ma(e){return e&&(e==="~"?Ln.homedir():e.startsWith("~/")||e.startsWith("~\\")?P.join(Ln.homedir(),e.slice(2)):e)}var fe=process.env.DATA_DIR?P.resolve(ma(process.env.DATA_DIR)):fa,je=P.join(fe,"collected-profiles"),Le=P.join(fe,"market-research"),z=P.join(fe,".schema-version"),As=[P.join(je,".schema-version"),P.join(Le,".schema-version")],_e=5,he=[{version:1,module:Dn},{version:2,module:On},{version:3,module:Nn},{version:4,module:Mn},{version:5,module:Pn}];(function(){he.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of he){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 s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=he.length?he[he.length-1].version:0;if(n!==_e)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${_e}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<he.length;o++){let s=o+1;if(he[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${he[o].version}`)}})();function Is(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
255
256
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
256
- `),process.exit(1));try{E.mkdirSync(de,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
257
- [FATAL] Cannot create DATA_DIR (${de}): ${t.message}`),console.error(` Fix the path or permissions and try again.
258
- `),process.exit(1))}let e;try{e=E.statSync(de)}catch(t){console.error(`
259
- [FATAL] DATA_DIR (${de}) is not accessible: ${t.message}
257
+ `),process.exit(1));try{A.mkdirSync(fe,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
258
+ [FATAL] Cannot create DATA_DIR (${fe}): ${t.message}`),console.error(` Fix the path or permissions and try again.
259
+ `),process.exit(1))}let e;try{e=A.statSync(fe)}catch(t){console.error(`
260
+ [FATAL] DATA_DIR (${fe}) is not accessible: ${t.message}
260
261
  `),process.exit(1)}e.isDirectory()||(console.error(`
261
- [FATAL] DATA_DIR (${de}) 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.
262
- `),process.exit(1));for(let t of[Me,Pe]){let n;try{n=E.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
262
+ [FATAL] DATA_DIR (${fe}) 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.
263
+ `),process.exit(1));for(let t of[je,Le]){let n;try{n=A.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
263
264
  [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.
264
- `),process.exit(1))}}var Ne=P.join(de,".migration-lock");function oa(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return E.writeFileSync(Ne,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(E.readFileSync(Ne,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(r){r.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,i=1/0;if(t.startedAt){let r=Date.parse(t.startedAt);Number.isNaN(r)||(i=Date.now()-r)}o&&i<s&&(console.error(`
265
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Ne}
265
+ `),process.exit(1))}}var Pe=P.join(fe,".migration-lock");function pa(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return A.writeFileSync(Pe,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(A.readFileSync(Pe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(r){r.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,i=1/0;if(t.startedAt){let r=Date.parse(t.startedAt);Number.isNaN(r)||(i=Date.now()-r)}o&&i<s&&(console.error(`
266
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Pe}
266
267
  `),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.
267
- `),process.exit(1)),o&&i>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Ne+".tmp";try{return E.writeFileSync(n,e),E.renameSync(n,Ne),!0}catch(o){try{E.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Mn(){try{if(JSON.parse(E.readFileSync(Ne,"utf-8")).pid!==process.pid)return;E.unlinkSync(Ne)}catch{}}var $s=!1;function sa(){if($s)return;$s=!0;let e=()=>{try{Mn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function ra(){if(E.existsSync(G))return;let e=[],t=[];for(let i of ks)if(E.existsSync(i))try{e.push({file:i,schema:Jt(i)})}catch(r){t.push({file:i,err:r.message})}if(t.length>0){console.error(`
268
+ `),process.exit(1)),o&&i>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Pe+".tmp";try{return A.writeFileSync(n,e),A.renameSync(n,Pe),!0}catch(o){try{A.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Fn(){try{if(JSON.parse(A.readFileSync(Pe,"utf-8")).pid!==process.pid)return;A.unlinkSync(Pe)}catch{}}var xs=!1;function ga(){if(xs)return;xs=!0;let e=()=>{try{Fn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function ha(){if(A.existsSync(z))return;let e=[],t=[];for(let i of As)if(A.existsSync(i))try{e.push({file:i,schema:Yt(i)})}catch(r){t.push({file:i,err:r.message})}if(t.length>0){console.error(`
268
269
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
269
270
  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.
270
271
  `),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
271
272
  [FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
272
- `),process.exit(1)}let o=e[0].schema,s=G+".tmp";try{E.writeFileSync(s,JSON.stringify(o,null,2)),E.renameSync(s,G)}catch(i){try{E.unlinkSync(s)}catch{}throw i}for(let i of ks)if(E.existsSync(i))try{E.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${G}`)}function ia(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 Jt(e){let t=E.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Cs(){if(ra(),!E.existsSync(G))return{version:0,migrations:[]};let e;try{e=Jt(G)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
273
- [FATAL] ${G} 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.
274
- `),process.exit(1)}let t=ia(e);return t===null&&(console.error(`
275
- [FATAL] ${G} 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.
276
- `),process.exit(1)),t}function As(e){try{E.chmodSync(e,384)}catch{}}function aa(e){if(Es(),E.existsSync(G))try{if(E.lstatSync(G).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${G}. 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=G+".tmp";try{E.writeFileSync(t,JSON.stringify(e,null,2)),As(t),E.renameSync(t,G)}catch(n){try{E.unlinkSync(t)}catch{}throw n}}function _s(e,t){if(!E.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=E.readdirSync(e).filter(c=>{let a=c.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return E.statSync(P.join(e,c)).isFile()}catch{return!1}}),s=0,i=0,r=[];for(let c of o){let a=P.join(e,c),l=P.join(e,c+n);if(E.existsSync(l)){i++;continue}try{Ts(a,l),s++}catch(u){r.push({file:c,err:u.message})}}if(r.length>0){let c=new Error(`Failed to back up ${r.length} file(s) in ${P.basename(e)}/: `+r.map(a=>`${a.file} (${a.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(s>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${P.basename(e)}/ (${n})${c}`)}}var On=!1;async function xs(){if(On)return;Es(),fa();let t=Cs().version;if(t===Ce){On=!0;return}sa(),oa(),process.on("exit",Mn),t>Ce&&(console.error(`
277
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${Ce}.`),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.
278
- `),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${Ce}.
273
+ `),process.exit(1)}let o=e[0].schema,s=z+".tmp";try{A.writeFileSync(s,JSON.stringify(o,null,2)),A.renameSync(s,z)}catch(i){try{A.unlinkSync(s)}catch{}throw i}for(let i of As)if(A.existsSync(i))try{A.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${z}`)}function ya(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 Yt(e){let t=A.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Rs(){if(ha(),!A.existsSync(z))return{version:0,migrations:[]};let e;try{e=Yt(z)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
274
+ [FATAL] ${z} 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.
275
+ `),process.exit(1)}let t=ya(e);return t===null&&(console.error(`
276
+ [FATAL] ${z} 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.
277
+ `),process.exit(1)),t}function Ds(e){try{A.chmodSync(e,384)}catch{}}function wa(e){if(Is(),A.existsSync(z))try{if(A.lstatSync(z).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${z}. 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=z+".tmp";try{A.writeFileSync(t,JSON.stringify(e,null,2)),Ds(t),A.renameSync(t,z)}catch(n){try{A.unlinkSync(t)}catch{}throw n}}function Ts(e,t){if(!A.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=A.readdirSync(e).filter(c=>{let a=c.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return A.statSync(P.join(e,c)).isFile()}catch{return!1}}),s=0,i=0,r=[];for(let c of o){let a=P.join(e,c),l=P.join(e,c+n);if(A.existsSync(l)){i++;continue}try{Ns(a,l),s++}catch(u){r.push({file:c,err:u.message})}}if(r.length>0){let c=new Error(`Failed to back up ${r.length} file(s) in ${P.basename(e)}/: `+r.map(a=>`${a.file} (${a.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(s>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${P.basename(e)}/ (${n})${c}`)}}var jn=!1;async function Os(){if(jn)return;Is(),$a();let t=Rs().version;if(t===_e){jn=!0;return}ga(),pa(),process.on("exit",Fn),t>_e&&(console.error(`
278
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${_e}.`),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.
279
+ `),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${_e}.
279
280
  `),process.exit(1)),console.log(`
280
- \u{1F4E6} Schema migration: v${t} \u2192 v${Ce}`);let n=ma();if(!n.ok){console.error(`
281
+ \u{1F4E6} Schema migration: v${t} \u2192 v${_e}`);let n=Ca();if(!n.ok){console.error(`
281
282
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
282
283
  Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
283
284
  `),process.exit(1)}let o=he.filter(s=>s.version>t);for(let s of o){console.log(`
284
- Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{_s(Me,s.version),_s(Pe,s.version)}catch(a){console.error(`
285
+ Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{Ts(je,s.version),Ts(Le,s.version)}catch(a){console.error(`
285
286
  [FATAL] Pre-migration backup failed for ${i}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
286
- `),process.exit(1)}let c=s.module;try{await c.up(Me,Pe)}catch(a){console.error(`
287
- [FATAL] Migration ${i} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let l=pa(r);l.ok?(console.error(` \u2713 Auto-rollback restored ${l.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
287
+ `),process.exit(1)}let c=s.module;try{await c.up(je,Le)}catch(a){console.error(`
288
+ [FATAL] Migration ${i} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let l=_a(r);l.ok?(console.error(` \u2713 Auto-rollback restored ${l.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
288
289
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${l.error}`),console.error(` Manual recovery: copy *${r} files back over the originals.
289
290
  `))}catch(l){console.error(` [!] Auto-rollback CRASHED while restoring: ${l.message}`),console.error(` Manual recovery: copy *${r} files back over the originals.
290
- `)}process.exit(1)}try{let a=new Date().toISOString(),l={version:s.version,name:c.NAME||i,appliedAt:a},u=Cs();u.version=s.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(l),aa(u)}catch(a){console.error(`
291
+ `)}process.exit(1)}try{let a=new Date().toISOString(),l={version:s.version,name:c.NAME||i,appliedAt:a},u=Rs();u.version=s.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(l),wa(u)}catch(a){console.error(`
291
292
  [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
292
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{ko()}catch{}try{ln()}catch{}On=!0,Mn(),console.log(`
293
- \u2713 Schema is now at v${Ce}
294
- `)}var la=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ca(e){let t=e.toLowerCase();return la.some(n=>n.test(t))}var ua=6e4;function da(){let e=Date.now(),t=[];for(let n of[de,Me,Pe]){if(!E.existsSync(n))continue;let o;try{o=E.readdirSync(n)}catch{continue}for(let s of o){if(!ca(s))continue;let i=P.join(n,s);try{let r=E.statSync(i);if(!r.isFile()||e-r.mtimeMs<ua)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function fa({verbose:e=!1}={}){let t=da();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{E.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${P.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function ma(){let e=[];for(let t of[Me,Pe]){if(!E.existsSync(t))continue;let n=E.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=P.join(t,o);try{Jt(s)}catch(i){e.push({dir:P.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function pa(e){let t=[],n=[];for(let i of[Me,Pe]){if(!E.existsSync(i))continue;let r=E.readdirSync(i).filter(c=>c.endsWith(e));for(let c of r){let a=P.join(i,c),l=c.slice(0,-e.length),u=P.join(i,l);try{l.toLowerCase().endsWith(".json")?Jt(a):E.accessSync(a,E.constants.R_OK),t.push({backupPath:a,originalPath:u,fileName:c,dir:i})}catch(f){n.push(`${P.basename(i)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:r,fileName:c,dir:a}of t)try{Ts(i,r),o++}catch(l){s.push(`${P.basename(a)}/${c}: ${l.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function Ts(e,t){let n=t+".tmp";try{E.copyFileSync(e,n),As(n)}catch(o){try{E.unlinkSync(n)}catch{}throw o}try{E.renameSync(n,t)}catch(o){try{E.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=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 s.code=o.code,s}throw o}}et();Fe();async function ha(e,t,n="op"){let o,s=new Promise((i,r)=>{o=setTimeout(()=>r(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function je(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let n=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(n)||/Target closed/i.test(n)||/Session closed/i.test(n)||/Connection closed/i.test(n)||/Most likely the page has been closed/i.test(n)||/Navigating frame was detached/i.test(n)||/Protocol error.*timed out/i.test(n)}async function Rs(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await ha(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let r=await e.newPage();if(i)try{await i(r)}catch{}if(s)try{let c=s();Array.isArray(c)&&c.length>0&&await r.setCookie(...c)}catch{}if(n){await r.goto(n,{waitUntil:"domcontentloaded",timeout:o});let c=r.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(c))throw new Error(`Session expired after recovery \u2014 landed on ${c}. Run: ilml linkedin login`)}return r}await xs();var Ws="https://www.linkedin.com/messaging/",xa=10,Fn=3,Ta=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},Ra=()=>xt(),Le={pageRecoveries:0};async function Wt(e,t){if(Le.pageRecoveries>=xa)throw new Error(`CDP unrecoverable: ${Le.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
295
- \u{1F504} CDP dead \u2014 recovering page (#${Le.pageRecoveries+1}). Reason: ${t}`),e.page=await Rs(e.browser,e.page,{returnUrl:Ws,cookiesProvider:Ra,setupPage:Ta}),Le.pageRecoveries++,await k(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${Le.pageRecoveries}).
296
- `)}function Xe(e){return(e.messages||[]).find(t=>nt.has(t.status))?.status}var X=process.argv.slice(2),Un=X.includes("--full"),W=X.includes("--dry-run"),Us=X.includes("--report"),qs=X.includes("--verbose"),Bs=X.includes("--backfill"),Hs=X.includes("--enrich"),Js=X.includes("--today"),qn=X.includes("--read-unread"),Et=parseInt(X.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),Ia=X.includes("--auto-enrich-replies"),Vs=parseInt(X.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),Da=parseInt(X.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function Oa(e,t){if(!t)return"new";if(e.unread)return"unread";if(!t.profileUrl&&(t.messages?.length||t.lastMessagePreview))return"missing_url";let n=(t.lastMessagePreview||"").substring(0,50),o=(e.lastMessagePreview||"").substring(0,50);if(o&&n&&o!==n)return"preview_changed";if(e.lastMessageBy==="me"&&t.lastMessageBy!=="me")return"sender_changed";if(t.lastSynced&&e.lastMessageTime){let s=new Date(e.lastMessageTime).getTime(),i=new Date(t.lastSynced).getTime();if(Number.isFinite(s)&&Number.isFinite(i)&&s>i)return"activity_after_last_read"}return null}async function Na(e,t){console.log(`
293
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Eo()}catch{}try{dn()}catch{}jn=!0,Fn(),console.log(`
294
+ \u2713 Schema is now at v${_e}
295
+ `)}var ba=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Sa(e){let t=e.toLowerCase();return ba.some(n=>n.test(t))}var va=6e4;function ka(){let e=Date.now(),t=[];for(let n of[fe,je,Le]){if(!A.existsSync(n))continue;let o;try{o=A.readdirSync(n)}catch{continue}for(let s of o){if(!Sa(s))continue;let i=P.join(n,s);try{let r=A.statSync(i);if(!r.isFile()||e-r.mtimeMs<va)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function $a({verbose:e=!1}={}){let t=ka();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{A.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${P.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Ca(){let e=[];for(let t of[je,Le]){if(!A.existsSync(t))continue;let n=A.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=P.join(t,o);try{Yt(s)}catch(i){e.push({dir:P.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function _a(e){let t=[],n=[];for(let i of[je,Le]){if(!A.existsSync(i))continue;let r=A.readdirSync(i).filter(c=>c.endsWith(e));for(let c of r){let a=P.join(i,c),l=c.slice(0,-e.length),u=P.join(i,l);try{l.toLowerCase().endsWith(".json")?Yt(a):A.accessSync(a,A.constants.R_OK),t.push({backupPath:a,originalPath:u,fileName:c,dir:i})}catch(f){n.push(`${P.basename(i)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:r,fileName:c,dir:a}of t)try{Ns(i,r),o++}catch(l){s.push(`${P.basename(a)}/${c}: ${l.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function Ns(e,t){let n=t+".tmp";try{A.copyFileSync(e,n),Ds(n)}catch(o){try{A.unlinkSync(n)}catch{}throw o}try{A.renameSync(n,t)}catch(o){try{A.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=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 s.code=o.code,s}throw o}}nt();qe();async function Ea(e,t,n="op"){let o,s=new Promise((i,r)=>{o=setTimeout(()=>r(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function Fe(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let n=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(n)||/Target closed/i.test(n)||/Session closed/i.test(n)||/Connection closed/i.test(n)||/Most likely the page has been closed/i.test(n)||/Navigating frame was detached/i.test(n)||/Protocol error.*timed out/i.test(n)}async function Ms(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await Ea(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let r=await e.newPage();if(i)try{await i(r)}catch{}if(s)try{let c=s();Array.isArray(c)&&c.length>0&&await r.setCookie(...c)}catch{}if(n){await r.goto(n,{waitUntil:"domcontentloaded",timeout:o});let c=r.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(c))throw new Error(`Session expired after recovery \u2014 landed on ${c}. Run: ilml linkedin login`)}return r}await Os();var Qs="https://www.linkedin.com/messaging/",Fa=10,Hn=3,Ua=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},qa=()=>It(),Ue={pageRecoveries:0};async function zt(e,t){if(Ue.pageRecoveries>=Fa)throw new Error(`CDP unrecoverable: ${Ue.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
296
+ \u{1F504} CDP dead \u2014 recovering page (#${Ue.pageRecoveries+1}). Reason: ${t}`),e.page=await Ms(e.browser,e.page,{returnUrl:Qs,cookiesProvider:qa,setupPage:Ua}),Ue.pageRecoveries++,await k(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${Ue.pageRecoveries}).
297
+ `)}function et(e){return(e.messages||[]).find(t=>st.has(t.status))?.status}var X=process.argv.slice(2),Jn=X.includes("--full"),Y=X.includes("--dry-run"),Vs=X.includes("--report"),Ws=X.includes("--verbose"),Ys=X.includes("--backfill"),Gs=X.includes("--enrich"),zs=X.includes("--today"),Vn=X.includes("--read-unread"),Rt=parseInt(X.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),Ba=X.includes("--auto-enrich-replies"),Ks=parseInt(X.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),Ha=parseInt(X.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function Ja(e,t){if(!t)return"new";if(e.unread)return"unread";if(!t.profileUrl&&(t.messages?.length||t.lastMessagePreview))return"missing_url";let n=(t.lastMessagePreview||"").substring(0,50),o=(e.lastMessagePreview||"").substring(0,50);if(o&&n&&o!==n)return"preview_changed";if(e.lastMessageBy==="me"&&t.lastMessageBy!=="me")return"sender_changed";if(t.lastSynced&&e.lastMessageTime){let s=new Date(e.lastMessageTime).getTime(),i=new Date(t.lastSynced).getTime();if(Number.isFinite(s)&&Number.isFinite(i)&&s>i)return"activity_after_last_read"}return null}async function Va(e,t){console.log(`
297
298
  \u2550\u2550 PHASE 1: Inbox Scan \u2550\u2550
298
- `);let n=nn(),o=n.lastIncrementalSync?new Date(n.lastIncrementalSync):null,s=new Map,i=new Map,r=new Map,c=0,a=0,l=0,u=0,f=0,d=-1,m=0;for(;;){a++;let y=await ns(e),S=0;for(let p of y){if(!p.name||s.has(p.name))continue;s.set(p.name,p),S++,p.unread&&r.set(p.name,p);let v=t[p.name],C=Oa(p,v);C&&(!qn&&p.unread?c++:i.set(p.name,{card:p,reason:C})),v&&(C||(v.lastMessageBy=p.lastMessageBy,v.lastMessagePreview=p.lastMessagePreview||v.lastMessagePreview,v.lastMessageTime=p.lastMessageTime||v.lastMessageTime),v.unread=p.unread,p.lastMessageBy==="them"&&p.unread&&(v.conversationStatus="unanswered_by_us"))}if(qs?console.log(` Round #${a}: +${S} new | Total: ${s.size} | Need reading: ${i.size}`):process.stdout.write(`\r Scanned: ${s.size} conversations (page #${a}, ${i.size} need reading)`),S===0){if(f++,f>=3){console.log(`
299
- 3 rounds with no new items \u2014 end of visible list.`);break}}else f=0;if(!Un){if(i.size===u){if(l++,l>=3){console.log(`
300
- Caught up \u2014 3 screens with no new threads to read.`);break}}else l=0;u=i.size}let g=await pn(e);if(g){if(g.scrollTop===d){if(m++,m>=3){console.log(`
301
- Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;d=g.scrollTop}else{let p=await e.$(".msg-conversation-listitem");if(p){let v=await p.boundingBox();v&&(await e.mouse.move(v.x+v.width/2,v.y+v.height/2),await e.mouse.wheel({deltaY:600}))}}await k(2e3)}qs||process.stdout.write(`
302
- `);let w=new Date().toISOString(),h=0;for(let[y,{card:S}]of i)t[y]||(t[y]={profileUrl:null,lastSynced:w,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:S.unread||!1,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},h++);let b=0;for(let[y,S]of r)t[y]||(t[y]={profileUrl:null,lastSynced:w,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:!0,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},b++);if(console.log(`
303
- Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${h}`),console.log(` Need reading/re-reading: ${i.size}`),!qn&&c>0&&console.log(` Preserved unread (default): ${c} \u2014 kept bold in LinkedIn UI; pass --read-unread to vacuum them into the DB`),b>0&&console.log(` New unread stubs: ${b} \u2014 saved to DB so 'today' / 'report' can show them offline`),i.size>0){let y={};for(let{reason:S}of i.values())y[S]=(y[S]||0)+1;for(let[S,g]of Object.entries(y))console.log(` ${S}: ${g}`)}if(!W){let y=nn();y.lastIncrementalSync=new Date().toISOString(),Un&&(y.lastFullSync=y.lastIncrementalSync),Ro(y),be(t)}return{allCards:s,toReRead:i,unreadCards:r}}async function Ma(e,t,n,o){console.log(`
299
+ `);let n=rn(),o=n.lastIncrementalSync?new Date(n.lastIncrementalSync):null,s=new Map,i=new Map,r=new Map,c=0,a=0,l=0,u=0,f=0,d=-1,m=0;for(;;){a++;let y=await is(e),S=0;for(let p of y){if(!p.name||s.has(p.name))continue;s.set(p.name,p),S++,p.unread&&r.set(p.name,p);let v=t[p.name],C=Ja(p,v);C&&(!Vn&&p.unread?c++:i.set(p.name,{card:p,reason:C})),v&&(C||(v.lastMessageBy=p.lastMessageBy,v.lastMessagePreview=p.lastMessagePreview||v.lastMessagePreview,v.lastMessageTime=p.lastMessageTime||v.lastMessageTime),v.unread=p.unread,p.lastMessageBy==="them"&&p.unread&&(v.conversationStatus="unanswered_by_us"))}if(Ws?console.log(` Round #${a}: +${S} new | Total: ${s.size} | Need reading: ${i.size}`):process.stdout.write(`\r Scanned: ${s.size} conversations (page #${a}, ${i.size} need reading)`),S===0){if(f++,f>=3){console.log(`
300
+ 3 rounds with no new items \u2014 end of visible list.`);break}}else f=0;if(!Jn){if(i.size===u){if(l++,l>=3){console.log(`
301
+ Caught up \u2014 3 screens with no new threads to read.`);break}}else l=0;u=i.size}let h=await yn(e);if(h){if(h.scrollTop===d){if(m++,m>=3){console.log(`
302
+ Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;d=h.scrollTop}else{let p=await e.$(".msg-conversation-listitem");if(p){let v=await p.boundingBox();v&&(await e.mouse.move(v.x+v.width/2,v.y+v.height/2),await e.mouse.wheel({deltaY:600}))}}await k(2e3)}Ws||process.stdout.write(`
303
+ `);let w=new Date().toISOString(),g=0;for(let[y,{card:S}]of i)t[y]||(t[y]={profileUrl:null,lastSynced:w,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:S.unread||!1,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},g++);let b=0;for(let[y,S]of r)t[y]||(t[y]={profileUrl:null,lastSynced:w,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:!0,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},b++);if(console.log(`
304
+ Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${g}`),console.log(` Need reading/re-reading: ${i.size}`),!Vn&&c>0&&console.log(` Preserved unread (default): ${c} \u2014 kept bold in LinkedIn UI; pass --read-unread to vacuum them into the DB`),b>0&&console.log(` New unread stubs: ${b} \u2014 saved to DB so 'today' / 'report' can show them offline`),i.size>0){let y={};for(let{reason:S}of i.values())y[S]=(y[S]||0)+1;for(let[S,h]of Object.entries(y))console.log(` ${S}: ${h}`)}if(!Y){let y=rn();y.lastIncrementalSync=new Date().toISOString(),Jn&&(y.lastFullSync=y.lastIncrementalSync),No(y),Se(t)}return{allCards:s,toReRead:i,unreadCards:r}}async function Wa(e,t,n,o){console.log(`
304
305
  \u2550\u2550 PHASE 2: Read Changed Threads \u2550\u2550
305
- `);let s=Array.from(t.entries()),i=Math.min(s.length,Et);if(i===0)return console.log(" No threads to read \u2014 all up to date."),[];console.log(" Resetting inbox view...");try{await e.page.goto(Ws,{waitUntil:"domcontentloaded",timeout:6e4})}catch(f){if(!je(f))throw f;await Wt(e,"Phase 2 inbox reset")}await k(4e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}let r={unread:0,preview_changed:1,sender_changed:2,no_messages:3,new:4};s.sort((f,d)=>(r[f[1].reason]??5)-(r[d[1].reason]??5)),console.log(` Reading ${i} of ${s.length} threads (--max=${Et})
306
- `);let c=[],a=[],l=0,u=0;for(let f=0;f<i;f++){let[d,{card:m,reason:w}]=s[f];console.log(` [${f+1}/${i}] ${d} (${w})`);let h=e.page;try{let b={verified:!1,headerName:null};try{b=await bn(h,d)}catch(S){if(je(S))throw S;console.log(` searchAndOpenThread threw: ${(S.message||"").substring(0,80)}`)}if(!b.verified){console.log(" Sidebar fallback (scroll-to-find)...");try{b=await os(e.page,d)}catch(S){if(je(S))throw S;console.log(` Fallback threw: ${(S.message||"").substring(0,80)}`)}}if(!b.verified){console.log(" Could not open thread."),l++;try{await ke(e.page)}catch{}continue}let y=await gn(h);if(y&&y.length>0){if(!yn(y,d,a)){console.log(" Skipped \u2014 stale data."),l++,await ke(h);continue}let g=await hn(h),p=n[d]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},v=p.messages?.length||0;p.messages=wn(p.messages,y),p.lastSynced=new Date().toISOString(),g&&!p.profileUrl&&(p.profileUrl=g);let C=p.messages.filter(R=>!["draft","confirmed","rejected","needs_review"].includes(R.status));p.lastMessageBy=Ut(C,d),p.lastMessagePreview=m.lastMessagePreview||p.lastMessagePreview,p.lastMessageTime=m.lastMessageTime||p.lastMessageTime,p.unread=!1,n[d]=p,W||be(n);let x=p.messages.length-v;console.log(` ${p.messages.length} msgs (${x>=0?"+"+x:x} new)${g&&!p.profileUrl?" +url":""}`),c.push({name:d}),a=[...new Set(y.map(R=>R.sender).filter(R=>R&&R!=="Unknown"))]}else console.log(" No messages extracted."),l++;await ke(h),await k(500)}catch(b){if(!je(b))throw b;u++,o&&o.add(d),await Wt(e,`Phase 2 thread ${f+1}/${i} (${d})`)}}return console.log(`
307
- Phase 2 complete: ${c.length} read, ${l} failed${u?`, ${u} skipped on CDP recovery`:""}`),s.length>i&&console.log(` ${s.length-i} more threads pending (run again or increase --max)`),c}async function Pa(e,t,n){if(!Ia)return null;console.log(`
306
+ `);let s=Array.from(t.entries()),i=Math.min(s.length,Rt);if(i===0)return console.log(" No threads to read \u2014 all up to date."),[];console.log(" Resetting inbox view...");try{await e.page.goto(Qs,{waitUntil:"domcontentloaded",timeout:6e4})}catch(f){if(!Fe(f))throw f;await zt(e,"Phase 2 inbox reset")}await k(4e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}let r={unread:0,preview_changed:1,sender_changed:2,no_messages:3,new:4};s.sort((f,d)=>(r[f[1].reason]??5)-(r[d[1].reason]??5)),console.log(` Reading ${i} of ${s.length} threads (--max=${Rt})
307
+ `);let c=[],a=[],l=0,u=0;for(let f=0;f<i;f++){let[d,{card:m,reason:w}]=s[f];console.log(` [${f+1}/${i}] ${d} (${w})`);let g=e.page;try{let b={verified:!1,headerName:null};try{b=await kn(g,d)}catch(S){if(Fe(S))throw S;console.log(` searchAndOpenThread threw: ${(S.message||"").substring(0,80)}`)}if(!b.verified){console.log(" Sidebar fallback (scroll-to-find)...");try{b=await as(e.page,d)}catch(S){if(Fe(S))throw S;console.log(` Fallback threw: ${(S.message||"").substring(0,80)}`)}}if(!b.verified){console.log(" Could not open thread."),l++;try{await $e(e.page)}catch{}continue}let y=await bn(g);if(y&&y.length>0){if(!Sn(y,d,a)){console.log(" Skipped \u2014 stale data."),l++,await $e(g);continue}let h=await wn(g),p=n[d]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},v=p.messages?.length||0;p.messages=vn(p.messages,y),p.lastSynced=new Date().toISOString(),h&&!p.profileUrl&&(p.profileUrl=h);let C=p.messages.filter(R=>!["draft","confirmed","rejected","needs_review"].includes(R.status));p.lastMessageBy=Ht(C,d),p.lastMessagePreview=m.lastMessagePreview||p.lastMessagePreview,p.lastMessageTime=m.lastMessageTime||p.lastMessageTime,p.unread=!1,n[d]=p,Y||Se(n);let x=p.messages.length-v;console.log(` ${p.messages.length} msgs (${x>=0?"+"+x:x} new)${h&&!p.profileUrl?" +url":""}`),c.push({name:d,newMessages:Math.max(0,x)}),a=[...new Set(y.map(R=>R.sender).filter(R=>R&&R!=="Unknown"))]}else console.log(" No messages extracted."),l++;await $e(g),await k(500)}catch(b){if(!Fe(b))throw b;u++,o&&o.add(d),await zt(e,`Phase 2 thread ${f+1}/${i} (${d})`)}}return console.log(`
308
+ Phase 2 complete: ${c.length} read, ${l} failed${u?`, ${u} skipped on CDP recovery`:""}`),s.length>i&&console.log(` ${s.length-i} more threads pending (run again or increase --max)`),c}async function Ya(e,t,n){if(!Ba)return null;console.log(`
308
309
  \u2550\u2550 PHASE 2.5: Auto-enrich-replies \u2550\u2550
309
- `);let o=new Set(n.map(m=>m.name)),s=J(),i=Date.now(),r=Da*24*60*60*1e3,c=[];for(let m of o){let w=t[m];if(!w||w.lastMessageBy!=="them")continue;let h=w.profileUrl;if(!h)continue;let y=s[h]?._lastEnrichedAt;if(y){let S=i-new Date(y).getTime();if(Number.isFinite(S)&&S<r)continue}c.push({name:m,profileUrl:h,lastMessageTime:w.lastMessageTime||null})}if(c.length===0)return console.log(` No stale contacts to enrich. Skipping phase.
310
- `),{picked:0,enriched:0,skipped:0,errors:0,dryRun:W};c.sort((m,w)=>{let h=new Date(m.lastMessageTime||0).getTime();return new Date(w.lastMessageTime||0).getTime()-h});let a=c.slice(0,Vs),l=c.length-a.length;if(console.log(` Candidates: ${c.length} | picking ${a.length} (cap ${Vs}) | skipping ${l}`),l>0&&console.log(" (raise --auto-enrich-max=N to lift the cap, but be mindful of ban-risk)"),W){console.log(" [DRY RUN] Would enrich:");for(let m of a)console.log(` - ${m.name} ${m.profileUrl} (last msg: ${m.lastMessageTime||"unknown"})`);return console.log(""),{picked:a.length,enriched:0,skipped:l,errors:0,dryRun:!0}}let{viewProfile:u}=await Fs().then(()=>Ls),f=0,d=0;for(let m=0;m<a.length;m++){let w=a[m];console.log(`
311
- [${m+1}/${a.length}] Enriching ${w.name} ${w.profileUrl}`);try{let h=await u(e.page,w.profileUrl,{extractExperience:!0,extractFeatured:!0,extractEducation:!0,extractSkills:!0,extractRecommendations:!0,extractCertifications:!0});if(!h||!h.name){console.log(" \u2717 viewProfile returned no data \u2014 skipping save"),d++;continue}let b={name:h.name,title:h.title,location:h.location,about:h.about,currentCompany:h.currentCompany,currentSchool:h.currentSchool,topSkills:h.topSkills,availableSections:h.availableSections,connectionsLevel:h.connectionsLevel,mutualConnectionsCount:h.mutualConnectionsCount,followers:h.followers,openToWork:h.openToWork,hiring:h.hiring,hasVerifiedBadge:h.hasVerifiedBadge,photoUrl:h.photoUrl,source:"auto-enrich-replies"},y=!1;for(let[S,g]of[["experience",h.experience],["featured",h.featured],["education",h.education],["skillsFull",h.skillsFull],["recommendations",h.recommendations],["certifications",h.certifications]])Array.isArray(g)&&g.length>0&&(b[S]=g,y=!0);y&&(b._lastEnrichedAt=new Date().toISOString()),Re(w.profileUrl,b),h.resolvedUrl&&It(w.profileUrl,h.resolvedUrl),f++,console.log(` \u2713 saved (rich sections: ${y?"yes":"no \u2014 basic only"})`)}catch(h){if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(h.message||""))return console.log(" \u26A0 Session expired during auto-enrich. Stopping phase."),console.log(" Sync-all post-processing will still run on already-enriched data."),{picked:a.length,enriched:f,skipped:l,errors:d,authWall:!0};console.log(` \u2717 ${h.message?.slice(0,200)}`),d++}m+1<a.length&&await k(8e3)}return console.log(`
310
+ `);let o=new Set(n.map(m=>m.name)),s=V(),i=Date.now(),r=Ha*24*60*60*1e3,c=[];for(let m of o){let w=t[m];if(!w||w.lastMessageBy!=="them")continue;let g=w.profileUrl;if(!g)continue;let y=s[g]?._lastEnrichedAt;if(y){let S=i-new Date(y).getTime();if(Number.isFinite(S)&&S<r)continue}c.push({name:m,profileUrl:g,lastMessageTime:w.lastMessageTime||null})}if(c.length===0)return console.log(` No stale contacts to enrich. Skipping phase.
311
+ `),{picked:0,enriched:0,skipped:0,errors:0,dryRun:Y};c.sort((m,w)=>{let g=new Date(m.lastMessageTime||0).getTime();return new Date(w.lastMessageTime||0).getTime()-g});let a=c.slice(0,Ks),l=c.length-a.length;if(console.log(` Candidates: ${c.length} | picking ${a.length} (cap ${Ks}) | skipping ${l}`),l>0&&console.log(" (raise --auto-enrich-max=N to lift the cap, but be mindful of ban-risk)"),Y){console.log(" [DRY RUN] Would enrich:");for(let m of a)console.log(` - ${m.name} ${m.profileUrl} (last msg: ${m.lastMessageTime||"unknown"})`);return console.log(""),{picked:a.length,enriched:0,skipped:l,errors:0,dryRun:!0}}let{viewProfile:u}=await Js().then(()=>Hs),f=0,d=0;for(let m=0;m<a.length;m++){let w=a[m];console.log(`
312
+ [${m+1}/${a.length}] Enriching ${w.name} ${w.profileUrl}`);try{let g=await u(e.page,w.profileUrl,{extractExperience:!0,extractFeatured:!0,extractEducation:!0,extractSkills:!0,extractRecommendations:!0,extractCertifications:!0});if(!g||!g.name){console.log(" \u2717 viewProfile returned no data \u2014 skipping save"),d++;continue}let b={name:g.name,title:g.title,location:g.location,about:g.about,currentCompany:g.currentCompany,currentSchool:g.currentSchool,topSkills:g.topSkills,availableSections:g.availableSections,connectionsLevel:g.connectionsLevel,mutualConnectionsCount:g.mutualConnectionsCount,followers:g.followers,openToWork:g.openToWork,hiring:g.hiring,hasVerifiedBadge:g.hasVerifiedBadge,photoUrl:g.photoUrl,source:"auto-enrich-replies"},y=!1;for(let[S,h]of[["experience",g.experience],["featured",g.featured],["education",g.education],["skillsFull",g.skillsFull],["recommendations",g.recommendations],["certifications",g.certifications]])Array.isArray(h)&&h.length>0&&(b[S]=h,y=!0);y&&(b._lastEnrichedAt=new Date().toISOString()),Ie(w.profileUrl,b),g.resolvedUrl&&Nt(w.profileUrl,g.resolvedUrl),f++,console.log(` \u2713 saved (rich sections: ${y?"yes":"no \u2014 basic only"})`)}catch(g){if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(g.message||""))return console.log(" \u26A0 Session expired during auto-enrich. Stopping phase."),console.log(" Sync-all post-processing will still run on already-enriched data."),{picked:a.length,enriched:f,skipped:l,errors:d,authWall:!0};console.log(` \u2717 ${g.message?.slice(0,200)}`),d++}m+1<a.length&&await k(8e3)}return console.log(`
312
313
  Auto-enrich done: ${f} enriched, ${d} errors, ${l} skipped (over cap)
313
- `),{picked:a.length,enriched:f,skipped:l,errors:d}}function ja(e,t){console.log(`
314
+ `),{picked:a.length,enriched:f,skipped:l,errors:d}}function Ga(e,t){console.log(`
314
315
  \u2550\u2550 PHASE 3: Post-processing & Enrichment \u2550\u2550
315
- `);let n=J();for(let o of t){let{name:s}=o,i=e[s];if(!i?.messages?.length)continue;try{Ft(i,s,n)}catch(a){console.warn(` [!] Enrichment failed for ${s}: ${a.message}`)}i._cardSynced&&delete i._cardSynced;let r=i.profileUrl,c=null;if(r&&(c=n[r]||null),!c){let a=Object.entries(n).filter(([,l])=>l.name===s);a.length===1&&(r||(r=a[0][0],i.profileUrl=r),c=a[0][1])}!c&&r&&(c=Re(r,{name:s,source:"sync-all"})),c&&(i.category&&!c.category&&(c.category=i.category),c.conversationStatus=i.conversationStatus,c.lastUpdated=new Date().toISOString()),r&&c&&(i.isConnection=c.connectionStatus==="connected")}W||(Ie(n),be(e)),console.log(` Enriched ${t.length} conversations.`),Ys(e)}function Ys(e){let t=new Map;for(let[s,i]of Object.entries(e)){if(!i.profileUrl)continue;let r=i.profileUrl.toLowerCase().replace(/\/$/,"");t.has(r)||t.set(r,[]),t.get(r).push(s)}let n=[...t.entries()].filter(([,s])=>s.length===2);if(n.length===0)return;let o=0;for(let[,s]of n){let[i,r]=s.map(u=>({name:u,conv:e[u]})),c=(i.conv.messages?.length||0)>=(r.conv.messages?.length||0)?i:r,a=c===i?r:i,l=new Set((c.conv.messages||[]).map(u=>`${u.text?.slice(0,80)}|${u.time}`));for(let u of a.conv.messages||[]){let f=`${u.text?.slice(0,80)}|${u.time}`;l.has(f)||(c.conv.messages.push(u),l.add(f))}c.conv.messages.sort((u,f)=>(u.time||"").localeCompare(f.time||"")),a.conv.notes&&!c.conv.notes&&(c.conv.notes=a.conv.notes),a.conv.priority&&!c.conv.priority&&(c.conv.priority=a.conv.priority),a.conv.categorySource==="manual"&&c.conv.categorySource!=="manual"&&(c.conv.category=a.conv.category,c.conv.categorySource="manual"),(a.conv.lastSynced||"")>(c.conv.lastSynced||"")&&(c.conv.lastSynced=a.conv.lastSynced),delete e[a.name],console.log(` Merged: "${a.name}" \u2192 "${c.name}"`),o++}o>0&&(W||be(e),console.log(` ${o} duplicates merged.`))}function La(){let e=lt(),t=J(),n=Object.entries(e);console.log(`
316
+ `);let n=V();for(let o of t){let{name:s}=o,i=e[s];if(!i?.messages?.length)continue;try{Bt(i,s,n)}catch(a){console.warn(` [!] Enrichment failed for ${s}: ${a.message}`)}i._cardSynced&&delete i._cardSynced;let r=i.profileUrl,c=null;if(r&&(c=n[r]||null),!c){let a=Object.entries(n).filter(([,l])=>l.name===s);a.length===1&&(r||(r=a[0][0],i.profileUrl=r),c=a[0][1])}!c&&r&&(c=Ie(r,{name:s,source:"sync-all"})),c&&(i.category&&!c.category&&(c.category=i.category),c.conversationStatus=i.conversationStatus,c.lastUpdated=new Date().toISOString()),r&&c&&(i.isConnection=c.connectionStatus==="connected")}Y||(De(n),Se(e)),console.log(` Enriched ${t.length} conversations.`),Xs(e)}function Xs(e){let t=new Map;for(let[s,i]of Object.entries(e)){if(!i.profileUrl)continue;let r=i.profileUrl.toLowerCase().replace(/\/$/,"");t.has(r)||t.set(r,[]),t.get(r).push(s)}let n=[...t.entries()].filter(([,s])=>s.length===2);if(n.length===0)return;let o=0;for(let[,s]of n){let[i,r]=s.map(u=>({name:u,conv:e[u]})),c=(i.conv.messages?.length||0)>=(r.conv.messages?.length||0)?i:r,a=c===i?r:i,l=new Set((c.conv.messages||[]).map(u=>`${u.text?.slice(0,80)}|${u.time}`));for(let u of a.conv.messages||[]){let f=`${u.text?.slice(0,80)}|${u.time}`;l.has(f)||(c.conv.messages.push(u),l.add(f))}c.conv.messages.sort((u,f)=>(u.time||"").localeCompare(f.time||"")),a.conv.notes&&!c.conv.notes&&(c.conv.notes=a.conv.notes),a.conv.priority&&!c.conv.priority&&(c.conv.priority=a.conv.priority),a.conv.categorySource==="manual"&&c.conv.categorySource!=="manual"&&(c.conv.category=a.conv.category,c.conv.categorySource="manual"),(a.conv.lastSynced||"")>(c.conv.lastSynced||"")&&(c.conv.lastSynced=a.conv.lastSynced),delete e[a.name],console.log(` Merged: "${a.name}" \u2192 "${c.name}"`),o++}o>0&&(Y||Se(e),console.log(` ${o} duplicates merged.`))}function za(){let e=ut(),t=V(),n=Object.entries(e);console.log(`
316
317
  \u2550\u2550 ENRICHMENT: Re-processing all conversations \u2550\u2550
317
- `);let o=0,s=0,i=0;for(let[f,d]of n){if(!d.profileUrl){let m=Object.entries(t).filter(([,w])=>w.name===f);m.length===1&&(d.profileUrl=m[0][0],i++)}if(!d.messages||d.messages.length===0){s++;continue}try{Ft(d,f,t)}catch(m){console.warn(` [!] Enrichment failed for ${f}: ${m.message}`)}o++}Ys(e),W||be(e),console.log(` Enriched: ${o}`),console.log(` Skipped (no messages): ${s}`),i>0&&console.log(` Linked profileUrl from people.json: ${i}`),console.log(` Total: ${n.length}`);let r=new Set(Object.keys(e)),c=new Set(Object.values(e).map(f=>f.profileUrl).filter(Boolean)),a=Object.entries(t),l=0,u=0;for(let[f,d]of a){if(c.has(f)){u++;continue}if(d.name&&r.has(d.name)){u++;continue}if(d.connectionStatus!=="connected"){u++;continue}kn(d,f),l++}W||Ie(t),console.log(`
318
- People enriched: ${l}`),console.log(` People skipped (have conversation or not connected): ${u}`),console.log(` People total: ${a.length}`),Bn(e,null,null)}function Bn(e,t,n,o={}){let s=Object.entries(e),i=J(),{unreadCards:r=null,readUnread:c=!1}=o;console.log(`
318
+ `);let o=0,s=0,i=0;for(let[f,d]of n){if(!d.profileUrl){let m=Object.entries(t).filter(([,w])=>w.name===f);m.length===1&&(d.profileUrl=m[0][0],i++)}if(!d.messages||d.messages.length===0){s++;continue}try{Bt(d,f,t)}catch(m){console.warn(` [!] Enrichment failed for ${f}: ${m.message}`)}o++}Xs(e),Y||Se(e),console.log(` Enriched: ${o}`),console.log(` Skipped (no messages): ${s}`),i>0&&console.log(` Linked profileUrl from people.json: ${i}`),console.log(` Total: ${n.length}`);let r=new Set(Object.keys(e)),c=new Set(Object.values(e).map(f=>f.profileUrl).filter(Boolean)),a=Object.entries(t),l=0,u=0;for(let[f,d]of a){if(c.has(f)){u++;continue}if(d.name&&r.has(d.name)){u++;continue}if(d.connectionStatus!=="connected"){u++;continue}_n(d,f),l++}Y||De(t),console.log(`
319
+ People enriched: ${l}`),console.log(` People skipped (have conversation or not connected): ${u}`),console.log(` People total: ${a.length}`),Wn(e,null,null)}function Wn(e,t,n,o={}){let s=Object.entries(e),i=V(),{unreadCards:r=null,readUnread:c=!1}=o;console.log(`
319
320
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SYNC REPORT"),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
320
321
  `),t&&(console.log(" Inbox Scan:"),console.log(` Conversations seen: ${t.allCards.size}`),console.log(` Needed reading: ${t.toReRead.size}`)),n&&console.log(` Actually read: ${n.length}`);let a=s.length,l=s.filter(([,$])=>$.messages?.length>0).length,u=s.filter(([,$])=>!$.messages||$.messages.length===0).length,f=s.filter(([,$])=>$.profileUrl).length,d=s.filter(([,$])=>!$.profileUrl).length;console.log(`
321
322
  Database:`),console.log(` Total conversations: ${a}`),console.log(` With messages: ${l}`),console.log(` Without messages: ${u}`),console.log(` With profileUrl: ${f}`),console.log(` Without profileUrl: ${d}`);let m=0,w=0;for(let[,$]of s)for(let _ of $.messages||[])m++,(!_.sender||_.sender==="Unknown")&&w++;console.log(`
322
- Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${w} (${m>0?(w/m*100).toFixed(1):0}%)`);let h={};for(let[,$]of s){let _=$.conversationStatus||"null";h[_]=(h[_]||0)+1}console.log(`
323
- Statuses:`);for(let[$,_]of Object.entries(h).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${_}`);let b={};for(let[,$]of s){let _=$.category||"(none)";b[_]=(b[_]||0)+1}console.log(`
323
+ Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${w} (${m>0?(w/m*100).toFixed(1):0}%)`);let g={};for(let[,$]of s){let _=$.conversationStatus||"null";g[_]=(g[_]||0)+1}console.log(`
324
+ Statuses:`);for(let[$,_]of Object.entries(g).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${_}`);let b={};for(let[,$]of s){let _=$.category||"(none)";b[_]=(b[_]||0)+1}console.log(`
324
325
  Categories:`);for(let[$,_]of Object.entries(b).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${_}`);let y={};for(let[,$]of s){let _=$.actionNeeded||"(none)";y[_]=(y[_]||0)+1}if(Object.keys(y).length>1||!y["(none)"]){console.log(`
325
- Actions Needed:`);for(let[$,_]of Object.entries(y).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${_}`)}let S=new Map;for(let[$,_]of s){if(!_.profileUrl)continue;let T=_.profileUrl.toLowerCase().replace(/\/$/,"");S.has(T)||S.set(T,[]),S.get(T).push($)}let g=[...S.entries()].filter(([,$])=>$.length>1);if(g.length>0){console.log(`
326
- Duplicates (${g.length}):`);for(let[$,_]of g)console.log(` ${_.join(" | ")} \u2192 ${$}`)}let p=s.filter(([,$])=>$.conversationStatus==="unanswered_by_us").sort(($,_)=>(_[1].lastSynced||"").localeCompare($[1].lastSynced||"")),v=s.filter(([,$])=>Xe($));if(console.log(`
326
+ Actions Needed:`);for(let[$,_]of Object.entries(y).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${_}`)}let S=new Map;for(let[$,_]of s){if(!_.profileUrl)continue;let T=_.profileUrl.toLowerCase().replace(/\/$/,"");S.has(T)||S.set(T,[]),S.get(T).push($)}let h=[...S.entries()].filter(([,$])=>$.length>1);if(h.length>0){console.log(`
327
+ Duplicates (${h.length}):`);for(let[$,_]of h)console.log(` ${_.join(" | ")} \u2192 ${$}`)}let p=s.filter(([,$])=>$.conversationStatus==="unanswered_by_us").sort(($,_)=>(_[1].lastSynced||"").localeCompare($[1].lastSynced||"")),v=s.filter(([,$])=>et($));if(console.log(`
327
328
  \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(" ACTION NEEDED"),console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
328
329
  `),r&&!c&&r.size>0){let $=[...r.entries()];console.log(` STILL UNREAD ON LINKEDIN (${$.length}) \u2014 kept bold; read them in the LinkedIn UI:
329
- `);let _=30;for(let[T,N]of $.slice(0,_)){let H=e[T],ae=H?.category?` [${H.category}]`:"",le=N.lastMessageTime||H?.lastMessageTime||"",j=(N.lastMessagePreview||"").slice(0,80),L=H?.summary,U=H?.personContext?.title?`${H.personContext.title}${H.personContext.company?` at ${H.personContext.company}`:""}`:null;console.log(` ${T}${ae}${le?` \u2014 ${le}`:""}`),j&&console.log(` "${j}"`),L?console.log(` ${L}`):U&&console.log(` ${U}`)}$.length>_&&console.log(`
330
+ `);let _=30;for(let[T,N]of $.slice(0,_)){let J=e[T],ce=J?.category?` [${J.category}]`:"",ue=N.lastMessageTime||J?.lastMessageTime||"",j=(N.lastMessagePreview||"").slice(0,80),L=J?.summary,U=J?.personContext?.title?`${J.personContext.title}${J.personContext.company?` at ${J.personContext.company}`:""}`:null;console.log(` ${T}${ce}${ue?` \u2014 ${ue}`:""}`),j&&console.log(` "${j}"`),L?console.log(` ${L}`):U&&console.log(` ${U}`)}$.length>_&&console.log(`
330
331
  ... and ${$.length-_} more`),console.log(`
331
332
  To pull them into the local DB (will lose unread badges): npm run sync-all -- --read-unread
332
- `)}if(v.length>0){let $=v.filter(([,T])=>Xe(T)===V.CONFIRMED),_=v.filter(([,T])=>{let N=Xe(T);return N===V.DRAFT||N===V.NEEDS_REVIEW});console.log(` Drafts: ${v.length} total (${$.length} confirmed, ${_.length} pending)`),_.length>0&&console.log(" Review: npm run messages -- --review-drafts"),$.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let C=p.filter(([,$])=>$.actionNeeded==="schedule_call"),x=p.filter(([,$])=>$.actionNeeded!=="schedule_call");if(x.sort(($,_)=>{let T={high:0,medium:1,low:2}[$[1].suggestedPriority]??3,N={high:0,medium:1,low:2}[_[1].suggestedPriority]??3;return T-N}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
333
+ `)}if(v.length>0){let $=v.filter(([,T])=>et(T)===W.CONFIRMED),_=v.filter(([,T])=>{let N=et(T);return N===W.DRAFT||N===W.NEEDS_REVIEW});console.log(` Drafts: ${v.length} total (${$.length} confirmed, ${_.length} pending)`),_.length>0&&console.log(" Review: npm run messages -- --review-drafts"),$.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let C=p.filter(([,$])=>$.actionNeeded==="schedule_call"),x=p.filter(([,$])=>$.actionNeeded!=="schedule_call");if(x.sort(($,_)=>{let T={high:0,medium:1,low:2}[$[1].suggestedPriority]??3,N={high:0,medium:1,low:2}[_[1].suggestedPriority]??3;return T-N}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
333
334
  `);for(let[$,_]of C){let T=_.category||"",N=_.summary||"";console.log(` ${$}${T?` [${T}]`:""} \u2192 schedule_call`),N&&console.log(` ${N}`)}console.log()}if(x.length>0){console.log(` REPLY NEEDED (${x.length}):
334
- `);let $=20;for(let[_,T]of x.slice(0,$)){let N=T.category||"",H=T.suggestedPriority?`[${T.suggestedPriority}]`:"",ae=(T.autoTags||[]).slice(0,4).join(", "),le=T.summary||"",L=[...T.messages||[]].reverse().find(U=>U.sender!==z&&U.sender!=="Unknown")?.text?.slice(0,80)||T.lastMessagePreview?.slice(0,80)||"";console.log(` ${H} ${_}${N?` [${N}]`:""}`),console.log(le?` ${le}`:` "${L}"`),ae&&console.log(` #${ae.replace(/, /g," #")}`)}x.length>$&&console.log(`
335
- ... and ${x.length-$} more`)}p.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let R=new Set(Object.keys(e)),A=new Set(Object.values(e).map($=>$.profileUrl).filter(Boolean)),D=Object.entries(i).filter(([$,_])=>_.connectionStatus==="connected"&&_.personActionNeeded==="initiate_contact"&&!A.has($)&&!(_.name&&R.has(_.name))).sort(($,_)=>{let T={high:0,medium:1,low:2}[$[1].personPriority]??3,N={high:0,medium:1,low:2}[_[1].personPriority]??3;return T!==N?T-N:(_[1].connectionDate||"").localeCompare($[1].connectionDate||"")});if(D.length>0){console.log(`
336
- INITIATE CONTACT (${D.length}):
337
- `);let $=20;for(let[_,T]of D.slice(0,$)){let N=T.personPriority?`[${T.personPriority.toUpperCase()}]`:"",H=T.personSummary||T.title||"";console.log(` ${N} ${T.name||"Unknown"} \u2014 ${H}`)}D.length>$&&console.log(`
338
- ... and ${D.length-$} more`)}let K=s.filter(([,$])=>$.conversationStatus==="awaiting_reply");K.length>0&&console.log(`
339
- BALL IN THEIR COURT: ${K.length} conversations`),W&&console.log(`
335
+ `);let $=20;for(let[_,T]of x.slice(0,$)){let N=T.category||"",J=T.suggestedPriority?`[${T.suggestedPriority}]`:"",ce=(T.autoTags||[]).slice(0,4).join(", "),ue=T.summary||"",L=[...T.messages||[]].reverse().find(U=>U.sender!==K&&U.sender!=="Unknown")?.text?.slice(0,80)||T.lastMessagePreview?.slice(0,80)||"";console.log(` ${J} ${_}${N?` [${N}]`:""}`),console.log(ue?` ${ue}`:` "${L}"`),ce&&console.log(` #${ce.replace(/, /g," #")}`)}x.length>$&&console.log(`
336
+ ... and ${x.length-$} more`)}p.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let R=new Set(Object.keys(e)),E=new Set(Object.values(e).map($=>$.profileUrl).filter(Boolean)),O=Object.entries(i).filter(([$,_])=>_.connectionStatus==="connected"&&_.personActionNeeded==="initiate_contact"&&!E.has($)&&!(_.name&&R.has(_.name))).sort(($,_)=>{let T={high:0,medium:1,low:2}[$[1].personPriority]??3,N={high:0,medium:1,low:2}[_[1].personPriority]??3;return T!==N?T-N:(_[1].connectionDate||"").localeCompare($[1].connectionDate||"")});if(O.length>0){console.log(`
337
+ INITIATE CONTACT (${O.length}):
338
+ `);let $=20;for(let[_,T]of O.slice(0,$)){let N=T.personPriority?`[${T.personPriority.toUpperCase()}]`:"",J=T.personSummary||T.title||"";console.log(` ${N} ${T.name||"Unknown"} \u2014 ${J}`)}O.length>$&&console.log(`
339
+ ... and ${O.length-$} more`)}let H=s.filter(([,$])=>$.conversationStatus==="awaiting_reply");H.length>0&&console.log(`
340
+ BALL IN THEIR COURT: ${H.length} conversations`),Y&&console.log(`
340
341
  [DRY RUN \u2014 no changes written]`),console.log(`
341
342
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
342
- `)}async function Fa(e,t){console.log(`
343
+ `)}async function Ka(e,t){console.log(`
343
344
  \u2550\u2550 BACKFILL: Reading conversations with 0 messages \u2550\u2550
344
- `);let n=Object.entries(t).filter(([,a])=>!a.messages||a.messages.length===0).map(([a,l])=>({name:a,preview:l.lastMessagePreview||"",lastBy:l.lastMessageBy}));if(n.length===0)return console.log(" All conversations already have messages."),[];n.sort((a,l)=>a.lastBy==="them"&&l.lastBy!=="them"?-1:a.lastBy!=="them"&&l.lastBy==="them"?1:0);let o=Math.min(n.length,Et);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${Et})
345
- `);let s=[],i=0,r=0,c=[];for(let a=0;a<o;a++){let{name:l}=n[a];console.log(` [${a+1}/${o}] ${l}`);let u=e.page;try{if(await ao(u),!(await bn(u,l)).verified){console.log(" Not found or thread didn't load."),i++,await ke(u),await k(500);continue}let d=await gn(u);if(!d||d.length===0){console.log(" No messages extracted."),i++,await ke(u),await k(500);continue}if(!yn(d,l,c)){console.log(" Skipped \u2014 stale data."),i++,await ke(u),await k(500);continue}let w=await hn(u),h=t[l]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]};h.messages=wn(h.messages,d),h.lastSynced=new Date().toISOString(),w&&(h.profileUrl=w),t[l]=h,W||be(t),console.log(` \u2713 ${h.messages.length} msgs${w?" +url":""}`),s.push({name:l}),c=[...new Set(d.map(b=>b.sender).filter(b=>b&&b!=="Unknown"))],await ke(u),await k(500)}catch(f){if(!je(f))throw f;r++,await Wt(e,`Backfill thread ${a+1}/${o} (${l})`)}}return console.log(`
346
- Backfill complete: ${s.length} read, ${i} failed${r?`, ${r} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function Ua(e){let t=ct(),n=Object.values(e),o=n.filter(a=>a.sources?.includes("recruiters-from-jobs")&&!a.connectionStatus).length,s=n.filter(a=>a.connectionStatus==="modal_failed").length,i=o+s,r=n.filter(a=>a.connectionStatus==="connected"&&a.connectionMethod).length,c=n.filter(a=>a.connectionStatus==="pending"||a.connectionStatus==="sent_without_note").length;console.log("\u2550\u2550\u2550 CONNECTION QUOTA & QUEUE \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Today: ${t.daily.sent}/${t.daily.max} sent (${t.daily.remaining} remaining)`),console.log(` Week: ${t.weekly.sent}/${t.weekly.max} sent (${t.weekly.remaining} remaining)`),console.log(` Queue: ${i} profiles (${o} new, ${s} retry)`),console.log(` Funnel: ${r} accepted, ${c} pending`),i===0&&console.log(" \u26A0 Queue empty \u2014 need new job applications to feed funnel"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}function qa(e){let t=Object.values(e).filter(n=>n.jobCount>=2).sort((n,o)=>(o.jobCount||0)-(n.jobCount||0)).slice(0,10);if(t.length!==0){console.log("\u2550\u2550\u2550 TOP RECRUITERS (by job count) \u2550\u2550\u2550");for(let n=0;n<t.length;n++){let o=t[n],s=o.connectionStatus==="connected"?"connected":o.connectionStatus==="pending"||o.connectionStatus==="sent_without_note"?"pending":o.connectionStatus||"unknown",i=o.lastJobTitle?ge(o.lastJobTitle,25):"",r=o.lastJobDate||"",c=i?` (last: ${i}${r?", "+r:""})`:"";console.log(` ${String(n+1).padStart(2)}. ${ge(o.name||"?",25).padEnd(25)} ${String(o.jobCount).padStart(2)} jobs | ${s.padEnd(10)}${c}`)}console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function Ba(){let e=Ho(10);if(e.length!==0){console.log("\u2550\u2550\u2550 TOP JOBS TO APPLY \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let t=0;t<e.length;t++){let{score:n,job:o}=e[t],s=ge(o.title||"?",30),i=ge(o.company||"?",15),r=o.salary?` \u2014 ${ge(o.salary,12)}`:"",c=o.location?` \u2014 ${ge(o.location,15)}`:"",a=o.recruiterUrl?" \u{1F464}":"";console.log(` ${String(t+1).padStart(2)}. [${String(n).padStart(2)}] ${s} @ ${i}${r}${c}${a}`)}console.log(" Apply: npm run apply-queue"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function Ha(){let e=un();e.totalJobs===0&&e.totalVisited===0||(console.log("\u2550\u2550\u2550 MARKET RESEARCH \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Scouted jobs: ${e.totalJobs}${e.lastScoutDate?` (last: ${e.lastScoutDate})`:""}`),console.log(` Discovered people: ${e.totalRecruiters}`),console.log(` Profile visits: ${e.totalVisited} unique (${e.todayVisited} today)`),e.topTech.length>0&&console.log(` Top tech: ${e.topTech.slice(0,5).join(", ")}`),e.topCompanies.length>0&&console.log(` Top companies: ${e.topCompanies.slice(0,5).join(", ")}`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"))}function Ja(){let e=Io();if(e.totalApplications!==0){if(console.log(`\u2550\u2550\u2550 FAQ STATS (${e.totalApplications} applications) \u2550\u2550`),console.log(` Unique questions: ${e.uniqueQuestions}`),e.topQuestions.length>0){console.log(" Top questions:");for(let t of e.topQuestions.slice(0,8)){let n=ge(t.topAnswer,30);console.log(` "${ge(t.question,40)}" \u2014 ${t.count}x \u2192 ${n}`)}}if(e.inconsistent.length>0){console.log(` Inconsistent answers: ${e.inconsistent.length} \u26A0`);for(let t of e.inconsistent.slice(0,3))console.log(` "${ge(t.question,35)}" \u2014 ${t.answers.join(", ")}`)}console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function ge(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Va(){let e=lt(),t=J(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(g=>g.profileUrl).filter(Boolean));console.log(`
345
+ `);let n=Object.entries(t).filter(([,a])=>!a.messages||a.messages.length===0).map(([a,l])=>({name:a,preview:l.lastMessagePreview||"",lastBy:l.lastMessageBy}));if(n.length===0)return console.log(" All conversations already have messages."),[];n.sort((a,l)=>a.lastBy==="them"&&l.lastBy!=="them"?-1:a.lastBy!=="them"&&l.lastBy==="them"?1:0);let o=Math.min(n.length,Rt);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${Rt})
346
+ `);let s=[],i=0,r=0,c=[];for(let a=0;a<o;a++){let{name:l}=n[a];console.log(` [${a+1}/${o}] ${l}`);let u=e.page;try{if(await fo(u),!(await kn(u,l)).verified){console.log(" Not found or thread didn't load."),i++,await $e(u),await k(500);continue}let d=await bn(u);if(!d||d.length===0){console.log(" No messages extracted."),i++,await $e(u),await k(500);continue}if(!Sn(d,l,c)){console.log(" Skipped \u2014 stale data."),i++,await $e(u),await k(500);continue}let w=await wn(u),g=t[l]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]};g.messages=vn(g.messages,d),g.lastSynced=new Date().toISOString(),w&&(g.profileUrl=w),t[l]=g,Y||Se(t),console.log(` \u2713 ${g.messages.length} msgs${w?" +url":""}`),s.push({name:l}),c=[...new Set(d.map(b=>b.sender).filter(b=>b&&b!=="Unknown"))],await $e(u),await k(500)}catch(f){if(!Fe(f))throw f;r++,await zt(e,`Backfill thread ${a+1}/${o} (${l})`)}}return console.log(`
347
+ Backfill complete: ${s.length} read, ${i} failed${r?`, ${r} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function Qa(e){let t=dt(),n=Object.values(e),o=n.filter(a=>a.sources?.includes("recruiters-from-jobs")&&!a.connectionStatus).length,s=n.filter(a=>a.connectionStatus==="modal_failed").length,i=o+s,r=n.filter(a=>a.connectionStatus==="connected"&&a.connectionMethod).length,c=n.filter(a=>a.connectionStatus==="pending"||a.connectionStatus==="sent_without_note").length;console.log("\u2550\u2550\u2550 CONNECTION QUOTA & QUEUE \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Today: ${t.daily.sent}/${t.daily.max} sent (${t.daily.remaining} remaining)`),console.log(` Week: ${t.weekly.sent}/${t.weekly.max} sent (${t.weekly.remaining} remaining)`),console.log(` Queue: ${i} profiles (${o} new, ${s} retry)`),console.log(` Funnel: ${r} accepted, ${c} pending`),i===0&&console.log(" \u26A0 Queue empty \u2014 need new job applications to feed funnel"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}function Xa(e){let t=Object.values(e).filter(n=>n.jobCount>=2).sort((n,o)=>(o.jobCount||0)-(n.jobCount||0)).slice(0,10);if(t.length!==0){console.log("\u2550\u2550\u2550 TOP RECRUITERS (by job count) \u2550\u2550\u2550");for(let n=0;n<t.length;n++){let o=t[n],s=o.connectionStatus==="connected"?"connected":o.connectionStatus==="pending"||o.connectionStatus==="sent_without_note"?"pending":o.connectionStatus||"unknown",i=o.lastJobTitle?ye(o.lastJobTitle,25):"",r=o.lastJobDate||"",c=i?` (last: ${i}${r?", "+r:""})`:"";console.log(` ${String(n+1).padStart(2)}. ${ye(o.name||"?",25).padEnd(25)} ${String(o.jobCount).padStart(2)} jobs | ${s.padEnd(10)}${c}`)}console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function Za(){let e=Yo(10);if(e.length!==0){console.log("\u2550\u2550\u2550 TOP JOBS TO APPLY \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let t=0;t<e.length;t++){let{score:n,job:o}=e[t],s=ye(o.title||"?",30),i=ye(o.company||"?",15),r=o.salary?` \u2014 ${ye(o.salary,12)}`:"",c=o.location?` \u2014 ${ye(o.location,15)}`:"",a=o.recruiterUrl?" \u{1F464}":"";console.log(` ${String(t+1).padStart(2)}. [${String(n).padStart(2)}] ${s} @ ${i}${r}${c}${a}`)}console.log(" Apply: npm run apply-queue"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function el(){let e=mn();e.totalJobs===0&&e.totalVisited===0||(console.log("\u2550\u2550\u2550 MARKET RESEARCH \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Scouted jobs: ${e.totalJobs}${e.lastScoutDate?` (last: ${e.lastScoutDate})`:""}`),console.log(` Discovered people: ${e.totalRecruiters}`),console.log(` Profile visits: ${e.totalVisited} unique (${e.todayVisited} today)`),e.topTech.length>0&&console.log(` Top tech: ${e.topTech.slice(0,5).join(", ")}`),e.topCompanies.length>0&&console.log(` Top companies: ${e.topCompanies.slice(0,5).join(", ")}`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"))}function tl(){let e=Mo();if(e.totalApplications!==0){if(console.log(`\u2550\u2550\u2550 FAQ STATS (${e.totalApplications} applications) \u2550\u2550`),console.log(` Unique questions: ${e.uniqueQuestions}`),e.topQuestions.length>0){console.log(" Top questions:");for(let t of e.topQuestions.slice(0,8)){let n=ye(t.topAnswer,30);console.log(` "${ye(t.question,40)}" \u2014 ${t.count}x \u2192 ${n}`)}}if(e.inconsistent.length>0){console.log(` Inconsistent answers: ${e.inconsistent.length} \u26A0`);for(let t of e.inconsistent.slice(0,3))console.log(` "${ye(t.question,35)}" \u2014 ${t.answers.join(", ")}`)}console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function ye(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function nl(){let e=ut(),t=V(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(h=>h.profileUrl).filter(Boolean));console.log(`
347
348
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" TODAY'S PRIORITIES"),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
348
- `),console.log(ws()),console.log(""),Ua(t),console.log(""),qa(t),console.log(""),Ha(),console.log(""),Ba(),console.log(""),Ja(),console.log("");let s=Object.entries(e),i=s.filter(([,g])=>g.unread===!0).sort((g,p)=>(p[1].lastMessageTime||"").localeCompare(g[1].lastMessageTime||""));if(i.length>0){let g=i.slice(0,10);console.log(` UNREAD ON LINKEDIN (${i.length}) \u2014 bold in LinkedIn UI, not yet opened:
349
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],x=C.category?` [${C.category}]`:"",R=C.summary||(C.personContext?.title?`${C.personContext.title}${C.personContext.company?` at ${C.personContext.company}`:""}`:null)||C.lastMessagePreview?.slice(0,60)||null;console.log(` ${p+1}. ${v}${x}${R?` \u2014 ${R}`:""}`)}i.length>10&&console.log(` ... +${i.length-10} more`),console.log()}let r=new Date().toISOString().slice(0,10),c=s.filter(([,g])=>g.followUpNote),a=c.filter(([,g])=>!g.followUpDate||g.followUpDate<=r),l=c.filter(([,g])=>g.followUpDate&&g.followUpDate>r);if(c.length>0){console.log(` FOLLOW-UPS (${a.length} due, ${l.length} scheduled):
350
- `);for(let[g,p]of a){let v=p.followUpDate?` [due ${p.followUpDate}]`:" [no date]";console.log(` \u26A1 ${g}${v} \u2014 ${p.followUpNote}`)}for(let[g,p]of l.slice(0,5))console.log(` \u{1F4C5} ${g} [${p.followUpDate}] \u2014 ${p.followUpNote}`);l.length>5&&console.log(` ... +${l.length-5} more scheduled`),console.log()}let u=g=>g.actionNeeded&&g.actionNeeded!=="none"&&(!g.reviewedAtPreview||ze(g.lastMessagePreview)!==ze(g.reviewedAtPreview)),f=s.filter(([,g])=>u(g)).sort((g,p)=>(p[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(f.length>0){let g=f.slice(0,20);console.log(` UNREVIEWED \u2014 NEW MESSAGES (${f.length}):
351
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],x=C.priority||C.suggestedPriority||"",R=C.category?` [${C.category}]`:"",A=C.summary||"";console.log(` ${p+1}. ${x?`[${x}] `:""}${v}${R} \u2014 ${A}`)}f.length>20&&console.log(` ... +${f.length-20} more`),console.log()}let d=s.filter(([,g])=>g.actionNeeded==="schedule_call").sort((g,p)=>{let v={high:0,medium:1,low:2}[g[1].suggestedPriority]??3,C={high:0,medium:1,low:2}[p[1].suggestedPriority]??3;return v-C});if(d.length>0){let g=d.slice(0,5);console.log(` CALLS TO SCHEDULE (${d.length}):
352
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],x=C.summary||C.personContext?.title||"";console.log(` ${p+1}. ${v} \u2014 ${x}`)}d.length>5&&console.log(` ... +${d.length-5} more`),console.log()}let m=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&(g.suggestedPriority==="high"||g.priority==="high")&&!u(g)).sort((g,p)=>(p[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(m.length>0){let g=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
353
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],x=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${x} \u2014 ${R}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let w=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&g.suggestedPriority==="medium"&&g.priority!=="high"&&!u(g)).sort((g,p)=>(p[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(w.length>0){let g=w.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${w.length}):
354
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],x=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${x} \u2014 ${R}`)}w.length>5&&console.log(` ... +${w.length-5} more`),console.log()}let h=Object.entries(t).filter(([g,p])=>p.connectionStatus==="connected"&&p.personActionNeeded==="initiate_contact"&&!o.has(g)&&!(p.name&&n.has(p.name))).sort((g,p)=>{let v={high:0,medium:1,low:2}[g[1].personPriority]??3,C={high:0,medium:1,low:2}[p[1].personPriority]??3;return v!==C?v-C:(p[1].connectionDate||"").localeCompare(g[1].connectionDate||"")});if(h.length>0){let g=h.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${h.length}):
355
- `);for(let p=0;p<g.length;p++){let[,v]=g[p],C=v.personPriority?`[${v.personPriority.toUpperCase()}]`:"",x=v.connectionDate?Wa(v.connectionDate):"",R=v.title?`${v.title}${v.company?` at ${v.company}`:""}`:v.company||"";console.log(` ${p+1}. ${C} ${v.name||"Unknown"} \u2014 ${R}${x?` (${x})`:""}`)}h.length>10&&console.log(` ... +${h.length-10} more`),console.log()}let b=s.filter(([,g])=>Xe(g));if(b.length>0){let g=b.filter(([,v])=>Xe(v)===V.CONFIRMED).length,p=b.filter(([,v])=>{let C=Xe(v);return C===V.DRAFT||C===V.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${b.length} (${g} confirmed, ${p} pending)`),g>0&&console.log(" Send: npm run messages -- --push-drafts"),p>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let y=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us").length,S=s.filter(([,g])=>g.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${i.length} unread on LinkedIn, ${f.length} unreviewed, ${y} need reply, ${h.length} new connections, ${S} ball in their court`),console.log(`
349
+ `),console.log(ks()),console.log(""),Qa(t),console.log(""),Xa(t),console.log(""),el(),console.log(""),Za(),console.log(""),tl(),console.log("");let s=Object.entries(e),i=s.filter(([,h])=>h.unread===!0).sort((h,p)=>(p[1].lastMessageTime||"").localeCompare(h[1].lastMessageTime||""));if(i.length>0){let h=i.slice(0,10);console.log(` UNREAD ON LINKEDIN (${i.length}) \u2014 bold in LinkedIn UI, not yet opened:
350
+ `);for(let p=0;p<h.length;p++){let[v,C]=h[p],x=C.category?` [${C.category}]`:"",R=C.summary||(C.personContext?.title?`${C.personContext.title}${C.personContext.company?` at ${C.personContext.company}`:""}`:null)||C.lastMessagePreview?.slice(0,60)||null;console.log(` ${p+1}. ${v}${x}${R?` \u2014 ${R}`:""}`)}i.length>10&&console.log(` ... +${i.length-10} more`),console.log()}let r=new Date().toISOString().slice(0,10),c=s.filter(([,h])=>h.followUpNote),a=c.filter(([,h])=>!h.followUpDate||h.followUpDate<=r),l=c.filter(([,h])=>h.followUpDate&&h.followUpDate>r);if(c.length>0){console.log(` FOLLOW-UPS (${a.length} due, ${l.length} scheduled):
351
+ `);for(let[h,p]of a){let v=p.followUpDate?` [due ${p.followUpDate}]`:" [no date]";console.log(` \u26A1 ${h}${v} \u2014 ${p.followUpNote}`)}for(let[h,p]of l.slice(0,5))console.log(` \u{1F4C5} ${h} [${p.followUpDate}] \u2014 ${p.followUpNote}`);l.length>5&&console.log(` ... +${l.length-5} more scheduled`),console.log()}let u=h=>h.actionNeeded&&h.actionNeeded!=="none"&&(!h.reviewedAtPreview||Xe(h.lastMessagePreview)!==Xe(h.reviewedAtPreview)),f=s.filter(([,h])=>u(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(f.length>0){let h=f.slice(0,20);console.log(` UNREVIEWED \u2014 NEW MESSAGES (${f.length}):
352
+ `);for(let p=0;p<h.length;p++){let[v,C]=h[p],x=C.priority||C.suggestedPriority||"",R=C.category?` [${C.category}]`:"",E=C.summary||"";console.log(` ${p+1}. ${x?`[${x}] `:""}${v}${R} \u2014 ${E}`)}f.length>20&&console.log(` ... +${f.length-20} more`),console.log()}let d=s.filter(([,h])=>h.actionNeeded==="schedule_call").sort((h,p)=>{let v={high:0,medium:1,low:2}[h[1].suggestedPriority]??3,C={high:0,medium:1,low:2}[p[1].suggestedPriority]??3;return v-C});if(d.length>0){let h=d.slice(0,5);console.log(` CALLS TO SCHEDULE (${d.length}):
353
+ `);for(let p=0;p<h.length;p++){let[v,C]=h[p],x=C.summary||C.personContext?.title||"";console.log(` ${p+1}. ${v} \u2014 ${x}`)}d.length>5&&console.log(` ... +${d.length-5} more`),console.log()}let m=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us"&&h.actionNeeded!=="schedule_call"&&(h.suggestedPriority==="high"||h.priority==="high")&&!u(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(m.length>0){let h=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
354
+ `);for(let p=0;p<h.length;p++){let[v,C]=h[p],x=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${x} \u2014 ${R}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let w=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us"&&h.actionNeeded!=="schedule_call"&&h.suggestedPriority==="medium"&&h.priority!=="high"&&!u(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(w.length>0){let h=w.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${w.length}):
355
+ `);for(let p=0;p<h.length;p++){let[v,C]=h[p],x=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${x} \u2014 ${R}`)}w.length>5&&console.log(` ... +${w.length-5} more`),console.log()}let g=Object.entries(t).filter(([h,p])=>p.connectionStatus==="connected"&&p.personActionNeeded==="initiate_contact"&&!o.has(h)&&!(p.name&&n.has(p.name))).sort((h,p)=>{let v={high:0,medium:1,low:2}[h[1].personPriority]??3,C={high:0,medium:1,low:2}[p[1].personPriority]??3;return v!==C?v-C:(p[1].connectionDate||"").localeCompare(h[1].connectionDate||"")});if(g.length>0){let h=g.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${g.length}):
356
+ `);for(let p=0;p<h.length;p++){let[,v]=h[p],C=v.personPriority?`[${v.personPriority.toUpperCase()}]`:"",x=v.connectionDate?ol(v.connectionDate):"",R=v.title?`${v.title}${v.company?` at ${v.company}`:""}`:v.company||"";console.log(` ${p+1}. ${C} ${v.name||"Unknown"} \u2014 ${R}${x?` (${x})`:""}`)}g.length>10&&console.log(` ... +${g.length-10} more`),console.log()}let b=s.filter(([,h])=>et(h));if(b.length>0){let h=b.filter(([,v])=>et(v)===W.CONFIRMED).length,p=b.filter(([,v])=>{let C=et(v);return C===W.DRAFT||C===W.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${b.length} (${h} confirmed, ${p} pending)`),h>0&&console.log(" Send: npm run messages -- --push-drafts"),p>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let y=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us").length,S=s.filter(([,h])=>h.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${i.length} unread on LinkedIn, ${f.length} unreviewed, ${y} need reply, ${g.length} new connections, ${S} ball in their court`),console.log(`
356
357
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
357
- `)}function Wa(e){let t=new Date(e);if(isNaN(t))return"";let n=Math.floor((Date.now()-t.getTime())/864e5);return n===0?"today":n===1?"1d ago":`${n}d ago`}function Ya(){let e=lt();Bn(e,null,null)}async function Ga(){if(console.log(`
358
+ `)}function ol(e){let t=new Date(e);if(isNaN(t))return"";let n=Math.floor((Date.now()-t.getTime())/864e5);return n===0?"today":n===1?"1d ago":`${n}d ago`}function sl(){let e=ut();Wn(e,null,null)}async function rl(){if(console.log(`
358
359
  LinkedIn Sync-All
359
- `),Js){Va();return}if(Us){let n=Bt("sync-all","report");Ya(),vt(n,"success");return}if(Hs){let n=Bt("sync-all","enrich");try{La(),vt(n,"success")}catch(o){throw vt(n,"error",null,o.message),o}return}let e=Bs?"backfill":Un?"full":"incremental",t={scanned:0,toReRead:0,threadsRead:0,newMessages:0};W&&console.log(" [DRY RUN mode]"),console.log(` Mode: ${e} | Max threads to read: ${Et}`),await ys("sync-all",e,async()=>{let n=lt(),o=await ts(),s={browser:o.browser,page:o.page};try{await mn(s.page);let i=null,r=[];if(Bs)r=await Fa(s,n);else{let c=0;for(;;)try{i=await Na(s.page,n);break}catch(f){if(!je(f))throw f;if(c++,c>=Fn)throw new Error(`Phase 1 failed ${Fn} times on CDP death \u2014 giving up. Last: ${f.message}`);console.log(`
360
- \u26A0 Phase 1 CDP dead (attempt ${c}/${Fn}). Recovering and restarting Phase 1...`),await Wt(s,`Phase 1 attempt ${c}`)}let a=new Set;r=await Ma(s,i.toReRead,n,a),t.scanned=i.totalCards||0,t.toReRead=i.toReRead?.size||0;let l=new Set(r.map(f=>f.name)),u=0;for(let[f,{card:d}]of i.toReRead){if(l.has(f)||a.has(f))continue;let m=n[f];m&&(m.lastMessageBy=d.lastMessageBy,m.lastMessageTime=d.lastMessageTime||m.lastMessageTime,m.unread=d.unread,u++)}u>0&&(console.log(` Pending re-read: ${u} threads (raise --max or re-run to drain).`),W||be(n))}t.threadsRead=r.length,t.newMessages=r.reduce((c,a)=>c+(a.newMessages||0),0);try{let c=await Pa(s,n,r);c&&(t.autoEnriched=c.enriched,c.authWall&&(t.autoEnrichAuthWall=!0))}catch(c){console.log(`
360
+ `),zs){nl();return}if(Vs){let n=Vt("sync-all","report");sl(),$t(n,"success");return}if(Gs){let n=Vt("sync-all","enrich");try{za(),$t(n,"success")}catch(o){throw $t(n,"error",null,o.message),o}return}let e=Ys?"backfill":Jn?"full":"incremental",t={scanned:0,toReRead:0,threadsRead:0,newMessages:0};Y&&console.log(" [DRY RUN mode]"),console.log(` Mode: ${e} | Max threads to read: ${Rt}`),await vs("sync-all",e,async()=>{let n=ut(),o=await rs(),s={browser:o.browser,page:o.page};try{await hn(s.page);let i=null,r=[];if(Ys)r=await Ka(s,n);else{let c=0;for(;;)try{i=await Va(s.page,n);break}catch(f){if(!Fe(f))throw f;if(c++,c>=Hn)throw new Error(`Phase 1 failed ${Hn} times on CDP death \u2014 giving up. Last: ${f.message}`);console.log(`
361
+ \u26A0 Phase 1 CDP dead (attempt ${c}/${Hn}). Recovering and restarting Phase 1...`),await zt(s,`Phase 1 attempt ${c}`)}let a=new Set;r=await Wa(s,i.toReRead,n,a),t.scanned=i.allCards?.size||0,t.toReRead=i.toReRead?.size||0;let l=new Set(r.map(f=>f.name)),u=0;for(let[f,{card:d}]of i.toReRead){if(l.has(f)||a.has(f))continue;let m=n[f];m&&(m.lastMessageBy=d.lastMessageBy,m.lastMessageTime=d.lastMessageTime||m.lastMessageTime,m.unread=d.unread,u++)}u>0&&(console.log(` Pending re-read: ${u} threads (raise --max or re-run to drain).`),Y||Se(n))}t.threadsRead=r.length,t.newMessages=r.reduce((c,a)=>c+(a.newMessages||0),0);try{let c=await Ya(s,n,r);c&&(t.autoEnriched=c.enriched,c.authWall&&(t.autoEnrichAuthWall=!0))}catch(c){console.log(`
361
362
  \u26A0 Auto-enrich phase crashed: ${c.message?.slice(0,200)}`),console.log(` Continuing with post-processing \u2014 data integrity is unaffected.
362
- `)}r.length>0&&ja(n,r),Bn(n,i,r,{unreadCards:i?.unreadCards,readUnread:qn}),Le.pageRecoveries>0&&console.log(`
363
- CDP page recoveries this run: ${Le.pageRecoveries}`),W||on()}finally{if(!W&&!Us&&!Hs&&!Js)try{on()}catch{}await s.browser.close()}},()=>[`${t.scanned??0} cards scanned, ${t.threadsRead??0} threads read, ${t.newMessages??0} new messages`,t.toReRead?`Flagged to re-read: ${t.toReRead}`:null],{rethrow:!1})}Ga();
363
+ `)}r.length>0&&Ga(n,r),Wn(n,i,r,{unreadCards:i?.unreadCards,readUnread:Vn}),Ue.pageRecoveries>0&&console.log(`
364
+ CDP page recoveries this run: ${Ue.pageRecoveries}`),Y||an()}finally{if(!Y&&!Vs&&!Gs&&!zs)try{an()}catch{}await s.browser.close()}},()=>[`${t.scanned??0} cards scanned, ${t.threadsRead??0} threads read, ${t.newMessages??0} new messages`,t.toReRead?`Flagged to re-read: ${t.toReRead}`:null],{rethrow:!1})}rl();