ilml-plugin-linkedin 1.20.12 → 1.20.13

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,9 +1,9 @@
1
- var Gs=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{for(var n in t)Gs(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"):zs}function Ks(){let e=Gt(),t=fe.dirname(e);return t&&t!=="."&&!Y.existsSync(t)&&Y.mkdirSync(t,{recursive:!0}),e}function Qn(e){let t=Ks();return Y.writeFileSync(t,JSON.stringify(e)),t}function _t(){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 Qs(){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 Xs(){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||Xs()),o=fe.join(Qs(),"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 zs,to,tt=ce(()=>{zs="cookies.json";to=".ilml-seeded"});function nt(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=nt(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=Zs[o[1].toLowerCase()],a=nt(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=zt[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(s[2],10),l=parseInt(s[3],10),u=nt(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=zt[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(i[2],10),l=nt(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=zt[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let a=parseInt(r[2],10),l=nt(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 er(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 Kt(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 Xs=Object.defineProperty;var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{for(var n in t)Xs(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"):Zs}function er(){let e=Gt(),t=fe.dirname(e);return t&&t!=="."&&!Y.existsSync(t)&&Y.mkdirSync(t,{recursive:!0}),e}function Qn(e){let t=er();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 tr(){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 nr(){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||nr()),o=fe.join(tr(),"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 Zs,to,tt=Z(()=>{Zs="cookies.json";to=".ilml-seeded"});function nt(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=nt(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=or[o[1].toLowerCase()],a=nt(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=nt(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=nt(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=nt(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 sr(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(`
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 er(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 Kt(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 Kt(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 Kt(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 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 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 zt,Zs,io,Fe=ce(()=>{tt();zt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Zs={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};io=/\/authwall|\/login|\/checkpoint|\/uas\/login/});import{getPluginConfig as tr}from"@ilivemylife/graph-sdk";var nr,K,V,ot,Ue,st=ce(async()=>{nr=await tr();for(let[e,t]of Object.entries(nr))process.env[e]===void 0&&(process.env[e]=t);K=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ot=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 or}from"url";import{execSync as Xt}from"child_process";function wo(){qe=null,ir=null,me=null,_e=null,Be=null,xe=null}function pe(){F.existsSync(Z)||F.mkdirSync(Z,{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 at(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 lt(){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 fo(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=fo(n),r=fo(e[s].name);if(i&&r&&i===r)return s}return t}function cr(){F.existsSync(en)||F.mkdirSync(en,{recursive:!0})}function bo(e){let t=Te(e);return t?B.join(en,`${t}.json`):null}function ur(e){let t=bo(e);return t?at(t,`profile-history/${Te(e)}.json`)||[]:[]}function dr(e,t){let n=bo(e);if(!n)return;cr();let o=ur(e);o.unshift(t);try{Je(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Te(e)}: ${s.message}`)}}function mo(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function po(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function fr(e,t){if(!e)return[];let n=[];for(let o of lr){let s=e[o],i=t[o];mo(s)||mo(i)||po(s)!==po(i)&&n.push(o)}return n}function mr(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=at(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 ct(){return _e||(pe(),_e=at(Rt,"conversations.json")||{},pr(_e),_e)}function pr(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(),_e=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=lt(),s=new Date().toISOString(),i=He(n,e,t.name),r=n[i];if(r){let c=fr(r,t);c.length>0&&(dr(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:c,snapshot:mr(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 ar)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 So(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:lt(),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 vo(e){return e&&J()[e]?.connectionStatus||null}function ko(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=lt();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 $o(){return me||(pe(),me=at(ho,"quota.json"),(!me||!me.connections)&&(me={connections:[]}),me)}function hr(e){pe(),me=e;try{Je(ho,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Co(e,t="unknown"){let n=$o(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),hr(n)}function Eo(){let e=$o(),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=Eo(),t=lt(),n=e.filter(a=>a.date===t).length,o=e.length,s=n>=rt,i=o>=it,r=!s&&!i,c={allowed:r,daily:{sent:n,max:rt},weekly:{sent:o,max:it}};return r||(c.reason=s?`Daily limit reached (${n}/${rt})`:`Weekly limit reached (${o}/${it})`),c}function ut(){let e=Eo(),t=lt(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:rt,remaining:rt-n},weekly:{sent:o,max:it,remaining:it-o}}}function nn(){return Be||(pe(),Be=at(go,"sync-state.json")||{},Be)}function Ao(e){pe(),Be=e;try{Je(go,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function gr(){if(xe)return xe;pe();try{F.existsSync(uo)&&(xe=JSON.parse(F.readFileSync(uo,"utf-8")))}catch{}return xe||(xe={}),xe}function yr(e){return Array.isArray(e.applications)}function wr(){let e=gr();if(yr(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function xo(){let e=wr(),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(Z,".git")))try{let t={cwd:Z,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 sr,rr,Z,Zt,Xa,ho,Rt,go,uo,en,yo,rt,it,qe,ir,me,_e,Be,xe,ar,lr,Ve=ce(async()=>{await st();sr=or(import.meta.url),rr=B.dirname(B.dirname(sr)),Z=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(rr,"collected-profiles"),Zt=B.join(Z,"people.json"),Xa=B.join(Z,"jobs.json"),ho=B.join(Z,"quota.json"),Rt=B.join(Z,"conversations.json"),go=B.join(Z,"sync-state.json"),uo=B.join(Z,"application-questions.json"),en=B.join(Z,"profile-history"),yo=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},rt=yo(process.env.CONNECT_MAX_DAILY,20),it=yo(process.env.CONNECT_MAX_WEEKLY,100),qe=null,ir=null,me=null,_e=null,Be=null,xe=null;ar=["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"],lr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Io={};ue(Io,{BLOCK_MARKERS:()=>_o,dedupeAndCap:()=>Ro,extractSidePanelProfiles:()=>br,normalizeFundUrl:()=>Dt,normalizeProfileUrl:()=>We,scanRelatedBlocks:()=>To});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 To(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 y=0,h=new Set;for(let b of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let w=b.href||b.getAttribute("href")||"",S=s(w);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="",_=p.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(_&&(C=o(_[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:w,name:v,headline:C,block:d,rank:y++})}}return c}function Ro(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 br(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(To,_o)}catch{return[]}return Ro(n,t)}var _o,sn=ce(()=>{_o=[["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 jo={};ue(jo,{getJobDecision:()=>Er,getLastVisit:()=>Or,getScoutStats:()=>un,loadCompanies:()=>cn,loadDiscoveredPeople:()=>wt,loadJobDecisions:()=>yt,loadScoutedJobs:()=>gt,loadVisitLog:()=>Mt,recordCompany:()=>Rr,recordDiscoveredEdge:()=>_r,recordDiscoveredEdges:()=>Tr,recordVisit:()=>Dr,resetCaches:()=>ln,saveCompany:()=>Ir,saveDiscoveredPerson:()=>Ar,saveScoutedJob:()=>$r,setJobDecision:()=>Cr});import"dotenv/config";import*as ee from"fs";import*as Q from"path";import{fileURLToPath as Sr}from"url";function Se(){ee.existsSync(Oe)||ee.mkdirSync(Oe,{recursive:!0})}function ve(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ee.writeFileSync(o,n);for(let s=0;s<3;s++)try{ee.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(ee.existsSync(e))return JSON.parse(ee.readFileSync(e,"utf-8"))}catch{}return null}function ln(){dt=null,ft=null,mt=null,pt=null,De=null}function gt(){return dt||(dt=ht(Do)||{},dt)}function $r(e,t){if(!e)return;Se();let n=gt(),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(Do,n)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function yt(){return ft||(ft=ht(No)||{},ft)}function Cr(e,t,n={}){if(!e||!t)return;Se();let o=yt(),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(No,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Er(e){return yt()[e]||null}function wt(){return mt||(mt=ht(Nt)||{},mt)}function Ye(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Mo(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 Ar(e,t){if(!e)return;Se();let n=wt(),o=new Date().toISOString().slice(0,10),s=Mo(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 xr(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 Po(e,t,n={},o){if(!t)return;let s=Ye(t);t=Mo(e,t);let i=n.seedUrl?{...n,seedUrl:We(n.seedUrl)||n.seedUrl}:n,r=o.slice(0,10),{edge:c,match:a}=xr(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 _r(e,t={}){if(!e)return;Se();let n=wt();Po(n,e,t,new Date().toISOString());try{ve(Nt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Tr(e){if(!Array.isArray(e)||e.length===0)return;Se();let t=wt(),n=new Date().toISOString(),o=0;for(let s of e)!s||!s.url||(Po(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 Rr(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 pt||(pt=ht(an)||{},pt)}function Ir(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=ht(Oo)||{visits:[]},Array.isArray(De.visits)||(De.visits=[]),De)}function Dr(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(Oo,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function Or(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=gt(),t=wt(),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 vr,kr,Oe,Do,Nt,Oo,an,No,dt,ft,mt,rn,Ot,pt,De,bt=ce(()=>{sn();vr=Sr(import.meta.url),kr=Q.dirname(Q.dirname(vr)),Oe=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(kr,"market-research"),Do=Q.join(Oe,"scouted-jobs.json"),Nt=Q.join(Oe,"discovered-people.json"),Oo=Q.join(Oe,"visit-log.json"),an=Q.join(Oe,"companies.json"),No=Q.join(Oe,"job-decisions.json");dt=null;ft=null;mt=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)};pt=null;De=null});var cs={};ue(cs,{computeEngagement:()=>Sn,detectCategory:()=>ns,detectCategoryFromTitle:()=>Lt,determineAction:()=>as,determineLastMessageBy:()=>Ut,determineSituation:()=>os,enrichConversation:()=>Ft,enrichPerson:()=>kn,enrichPersonContext:()=>ls,extractAutoTags:()=>rs,generateSummary:()=>ss,normPreview:()=>Ke});function Ft(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(a=>!Ue.has(a.status)),i=Zr(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=ns(s,t,i);a&&(e.category=a,e.categorySource=e.categorySource||"message_content")}if(e.situation=os(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=Sn(s,t),e.personContext=ls(i),e.summary=ss(e,t,i),e.autoTags=rs(e,t,i);let c=as(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=Xr(e),e}function ns(e,t,n){if(!e||e.length===0)return n?.title?Lt(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(ts))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(ts))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function os(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 es.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 es.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===K)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function ss(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)}: ${ze(r,40)}`):r?s.push(ze(r,50)):s.push(t.split(" ")[0]);let l=o.filter(y=>y.sender!==K&&y.sender!=="Unknown").map(y=>y.text).join(" "),u=ei(l),f=ti(l),d=ni(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 rs(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!==K&&l.sender!=="Unknown").map(l=>l.text).join(" "),c=is(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=>ot.has(l.status))&&o.push("has-draft"),[...new Set(o)]}function is(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 as(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Ke(e.lastMessagePreview)===Ke(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(i=>ot.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===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 ls(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Xr(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 Zr(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 Ke(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function vn(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function ze(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function ei(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 ti(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 ni(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")}oi(e),e.personSummary=si(e),e.personAutoTags=ri(e);let n=ii(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=ai(e)),e}function oi(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 si(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(`${ze(o,40)} at ${ze(s,30)}`):o?t.push(ze(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: ${ze(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 ri(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=is("",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 ii(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 ai(e){let t=e.category;if(!t)return null;let n=li(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 li(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 ts,es,$n=ce(async()=>{await st();await Ve();ts={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]}};es=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var xs={};ue(xs,{extractCertificationsFromDetails:()=>da,extractEducationFromDetails:()=>ca,extractExperienceFromDetails:()=>aa,extractFeaturedFromDetails:()=>la,extractRecommendationsFromDetails:()=>fa,extractSkillsFromDetails:()=>ua});async function aa(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 y=m.filter(h=>(h.textContent||"").trim().length>50);y.length<3||(d.textContent||"").length<500||f.push({el:d,count:y.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 x=u[1].split("\xB7").map(D=>D.trim());d=x[0]||null,x[1]&&(m=x[1])}let y=u.findIndex(x=>/(\d{4}|present)/i.test(x)&&/(-|–|—)/i.test(x)&&x.length<80),h=null,b=null;if(y>=0){let x=u[y].split("\xB7").map(D=>D.trim());h=x[0]||null,x[1]&&(b=x[1])}let w=null,S=-1;if(y>=0&&u[y+1]){let x=u[y+1],D=/^[>*\-•]|^&gt;/.test(x),z=/https?:\/\//.test(x),$=/\d{4}/.test(x),E=/,/.test(x)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(x);!D&&!z&&!$&&x.length<100&&E&&(w=x,S=y+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 x=v.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);x&&(g={listed:x[1].split(",").map(D=>D.trim()),additional:parseInt(x[2],10)})}let C=new Set([0,1,y,S,p].filter(x=>x>=0)),_=u.filter((x,D)=>!C.has(D)),R=_.length>0?_.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 ro(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let s=await sr(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,or,io,Fe=Z(()=>{tt();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},or={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};io=/\/authwall|\/login|\/checkpoint|\/uas\/login/});function ir(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=ir(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",rr[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 rr,uo,mo=Z(()=>{rr={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 ar}from"@ilivemylife/graph-sdk";var lr,po,z,V,ot,Ue,st=Z(async()=>{mo();lr=await ar();for(let[e,t]of Object.entries(lr))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"}),ot=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 cr}from"url";import{execSync as Xt}from"child_process";function ko(){qe=null,fr=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 at(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 lt(){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 hr(){F.existsSync(en)||F.mkdirSync(en,{recursive:!0})}function $o(e){let t=Te(e);return t?B.join(en,`${t}.json`):null}function gr(e){let t=$o(e);return t?at(t,`profile-history/${Te(e)}.json`)||[]:[]}function yr(e,t){let n=$o(e);if(!n)return;hr();let o=gr(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 wr(e,t){if(!e)return[];let n=[];for(let o of pr){let s=e[o],i=t[o];yo(s)||yo(i)||wo(s)!==wo(i)&&n.push(o)}return n}function br(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=at(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 ct(){return xe||(pe(),xe=at(Rt,"conversations.json")||{},Sr(xe),xe)}function Sr(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=lt(),s=new Date().toISOString(),i=He(n,e,t.name),r=n[i];if(r){let c=wr(r,t);c.length>0&&(yr(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:c,snapshot:br(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 mr)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:lt(),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=lt();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=at(bo,"quota.json"),(!me||!me.connections)&&(me={connections:[]}),me)}function vr(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}),vr(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=lt(),n=e.filter(a=>a.date===t).length,o=e.length,s=n>=rt,i=o>=it,r=!s&&!i,c={allowed:r,daily:{sent:n,max:rt},weekly:{sent:o,max:it}};return r||(c.reason=s?`Daily limit reached (${n}/${rt})`:`Weekly limit reached (${o}/${it})`),c}function ut(){let e=To(),t=lt(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:rt,remaining:rt-n},weekly:{sent:o,max:it,remaining:it-o}}}function nn(){return Be||(pe(),Be=at(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 kr(){if(Ae)return Ae;pe();try{F.existsSync(ho)&&(Ae=JSON.parse(F.readFileSync(ho,"utf-8")))}catch{}return Ae||(Ae={}),Ae}function $r(e){return Array.isArray(e.applications)}function Cr(){let e=kr();if($r(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=Cr(),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 ur,dr,ee,Zt,il,bo,Rt,So,ho,en,vo,rt,it,qe,fr,me,xe,Be,Ae,mr,pr,Ve=Z(async()=>{await st();ur=cr(import.meta.url),dr=B.dirname(B.dirname(ur)),ee=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(dr,"collected-profiles"),Zt=B.join(ee,"people.json"),il=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},rt=vo(process.env.CONNECT_MAX_DAILY,20),it=vo(process.env.CONNECT_MAX_WEEKLY,100),qe=null,fr=null,me=null,xe=null,Be=null,Ae=null;mr=["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"],pr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Mo={};ue(Mo,{BLOCK_MARKERS:()=>Do,dedupeAndCap:()=>No,extractSidePanelProfiles:()=>_r,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 y=0,h=new Set;for(let b of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let w=b.href||b.getAttribute("href")||"",S=s(w);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:w,name:v,headline:C,block:d,rank:y++})}}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 _r(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:()=>Ir,getLastVisit:()=>Fr,getScoutStats:()=>un,loadCompanies:()=>cn,loadDiscoveredPeople:()=>wt,loadJobDecisions:()=>yt,loadScoutedJobs:()=>gt,loadVisitLog:()=>Mt,recordCompany:()=>Pr,recordDiscoveredEdge:()=>Nr,recordDiscoveredEdges:()=>Mr,recordVisit:()=>Lr,resetCaches:()=>ln,saveCompany:()=>jr,saveDiscoveredPerson:()=>Dr,saveScoutedJob:()=>Tr,setJobDecision:()=>Rr});import"dotenv/config";import*as te from"fs";import*as Q from"path";import{fileURLToPath as Er}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 ht(e){try{if(te.existsSync(e))return JSON.parse(te.readFileSync(e,"utf-8"))}catch{}return null}function ln(){dt=null,ft=null,mt=null,pt=null,De=null}function gt(){return dt||(dt=ht(Po)||{},dt)}function Tr(e,t){if(!e)return;Se();let n=gt(),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 yt(){return ft||(ft=ht(Lo)||{},ft)}function Rr(e,t,n={}){if(!e||!t)return;Se();let o=yt(),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 Ir(e){return yt()[e]||null}function wt(){return mt||(mt=ht(Nt)||{},mt)}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 Dr(e,t){if(!e)return;Se();let n=wt(),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 Or(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}=Or(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 Nr(e,t={}){if(!e)return;Se();let n=wt();Uo(n,e,t,new Date().toISOString());try{ve(Nt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Mr(e){if(!Array.isArray(e)||e.length===0)return;Se();let t=wt(),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 Pr(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 pt||(pt=ht(an)||{},pt)}function jr(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=ht(jo)||{visits:[]},Array.isArray(De.visits)||(De.visits=[]),De)}function Lr(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 Fr(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=gt(),t=wt(),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 Ar,xr,Oe,Po,Nt,jo,an,Lo,dt,ft,mt,rn,Ot,pt,De,bt=Z(()=>{sn();Ar=Er(import.meta.url),xr=Q.dirname(Q.dirname(Ar)),Oe=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(xr,"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");dt=null;ft=null;mt=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)};pt=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=ri(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=si(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(y=>y.sender!==z&&y.sender!=="Unknown").map(y=>y.text).join(" "),u=ii(l),f=ai(l),d=li(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=>ot.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=>ot.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 si(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 ri(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 ii(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 ai(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 li(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")}ci(e),e.personSummary=ui(e),e.personAutoTags=di(e);let n=fi(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=mi(e)),e}function ci(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 ui(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 di(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 fi(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 mi(e){let t=e.category;if(!t)return null;let n=pi(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 pi(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 st();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:()=>ya,extractEducationFromDetails:()=>ha,extractExperienceFromDetails:()=>ma,extractFeaturedFromDetails:()=>pa,extractRecommendationsFromDetails:()=>wa,extractSkillsFromDetails:()=>ga});async function ma(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 y=m.filter(h=>(h.textContent||"").trim().length>50);y.length<3||(d.textContent||"").length<500||f.push({el:d,count:y.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 y=u.findIndex(A=>/(\d{4}|present)/i.test(A)&&/(-|–|—)/i.test(A)&&A.length<80),h=null,b=null;if(y>=0){let A=u[y].split("\xB7").map(D=>D.trim());h=A[0]||null,A[1]&&(b=A[1])}let w=null,S=-1;if(y>=0&&u[y+1]){let A=u[y+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&&_&&(w=A,S=y+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,y,S,p].filter(A=>A>=0)),x=u.filter((A,D)=>!C.has(D)),R=x.length>0?x.join(`
4
4
 
5
5
  `):null;return{title:f,company:d,employmentType:m,dates:h,duration:b,location:w,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 la(e,t){return Ct(t,"featured","extractFeaturedFromDetails",async()=>(await kt(e,t,"featured"),await e.evaluate(`(() => {
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 pa(e,t){return Ct(t,"featured","extractFeaturedFromDetails",async()=>(await kt(e,t,"featured"),await e.evaluate(`(() => {
7
7
  ${$t}
8
8
 
9
9
  const main = document.querySelector('main');
@@ -44,7 +44,7 @@ var Gs=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{
44
44
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
45
45
  return true;
46
46
  });
47
- })()`)))}async function ca(e,t){return Ct(t,"education","extractEducationFromDetails",async()=>(await kt(e,t,"education"),await e.evaluate(`(() => {
47
+ })()`)))}async function ha(e,t){return Ct(t,"education","extractEducationFromDetails",async()=>(await kt(e,t,"education"),await e.evaluate(`(() => {
48
48
  ${$t}
49
49
 
50
50
  const main = document.querySelector('main');
@@ -81,7 +81,7 @@ var Gs=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{
81
81
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
82
82
  return true;
83
83
  });
84
- })()`)))}async function ua(e,t){return Ct(t,"skills","extractSkillsFromDetails",async()=>(await kt(e,t,"skills"),await e.evaluate(`(() => {
84
+ })()`)))}async function ga(e,t){return Ct(t,"skills","extractSkillsFromDetails",async()=>(await kt(e,t,"skills"),await e.evaluate(`(() => {
85
85
  ${$t}
86
86
 
87
87
  const main = document.querySelector('main');
@@ -113,7 +113,7 @@ var Gs=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{
113
113
  skills.push({ name, endorsements, _raw: lines });
114
114
  }
115
115
  return skills;
116
- })()`)))}async function da(e,t){return Ct(t,"certifications","extractCertificationsFromDetails",async()=>(await kt(e,t,"certifications"),await e.evaluate(`(() => {
116
+ })()`)))}async function ya(e,t){return Ct(t,"certifications","extractCertificationsFromDetails",async()=>(await kt(e,t,"certifications"),await e.evaluate(`(() => {
117
117
  ${$t}
118
118
 
119
119
  const main = document.querySelector('main');
@@ -138,7 +138,7 @@ var Gs=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{
138
138
 
139
139
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
140
140
  }).filter(e => e.name);
141
- })()`)))}async function fa(e,t){return Ct(t,"recommendations","extractRecommendationsFromDetails",async()=>(await kt(e,t,"recommendations"),await e.evaluate(`(() => {
141
+ })()`)))}async function wa(e,t){return Ct(t,"recommendations","extractRecommendationsFromDetails",async()=>(await kt(e,t,"recommendations"),await e.evaluate(`(() => {
142
142
  ${$t}
143
143
 
144
144
  const main = document.querySelector('main');
@@ -174,7 +174,7 @@ var Gs=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{
174
174
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
175
175
  return true;
176
176
  });
177
- })()`)))}var $t,_s=ce(()=>{Fe();$t=`
177
+ })()`)))}var $t,Ds=Z(()=>{Fe();$t=`
178
178
  function findEntryContainer(root) {
179
179
  const candidates = [];
180
180
  for (const div of root.querySelectorAll('div')) {
@@ -237,129 +237,129 @@ function findEntryContainer(root) {
237
237
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
238
238
  return candidates[0]?.el;
239
239
  }
240
- `});var Rs={};ue(Rs,{DEFAULT_PROFILE_INTERESTS:()=>Ts,computeFit:()=>ha,detectSectors:()=>pa});function pa(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,s]of Object.entries(ma))s.some(i=>i.test(t))&&n.push(o);return n}function ha(e,t=Ts){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 ma,Ts,Is=ce(()=>{ma={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/]};Ts={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});var Ns={};ue(Ns,{clickConnectButton:()=>Pn,default:()=>wa,detectConnectionStatus:()=>Ee,findConnectButton:()=>Et,runFunnel:()=>Os,sendConnectionRequest:()=>jn,shouldExcludeLocation:()=>Vt,viewProfile:()=>Mn});async function Ds(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 Mn(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 Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await Ds(e,t));let u=0;for(let p=0;p<2;p++){let v=await e.evaluate(()=>document.body.scrollHeight);for(let _=1;_<=6;_++)await e.evaluate(R=>window.scrollTo(0,R),v*_/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)},_={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 _;let x=[...Array.from(R.querySelectorAll("h1")),...Array.from(R.querySelectorAll("h2"))],D=Array.from(R.querySelectorAll("h2")),z=x.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)}),$=z?z.textContent.trim():null,E=z?z.parentElement:null;for(;E&&E!==R&&!Array.from(E.children).filter(O=>O.tagName==="P").some(O=>{let M=O.textContent&&O.textContent.trim();return M&&M.length>5&&!C(M)});)E=E.parentElement;let T=null,N=null,H=null,ie=null;if(E&&E!==R){let I=Array.from(E.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(E.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($))&&(ie=ye.split(/[·•]/)[0].trim(),ie))break}}let ae=null;if(E){let I=E.querySelectorAll("p, span, div");for(let O of I){let M=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){ae=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||"",le=null,Hn=q.match(/(\d+\+?)\s+connections\b/i);Hn&&(le=Hn[1]+" connections");let xt=null,Jn=q.match(/(\d+)\s+mutual connection/i),Vn=q.match(/and\s+(\d+)\s+other mutual/i),Hs=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Jn?xt=parseInt(Jn[1],10):Vn?xt=2+parseInt(Vn[1],10):Hs&&(xt=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(Ys=>Ys.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 zn=null,Kn=D.find(I=>I.textContent&&I.textContent.trim()==="Activity");if(Kn){let I=Kn.parentElement;for(;I&&I.tagName!=="SECTION";)I=I.parentElement;if(I){let O=(I.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);O&&(zn=parseInt(O[1].replace(/,/g,""),10))}}let Js=[...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)))],et=document.body.textContent||"",Vs=/#OpenToWork\b/i.test(et)||/\bOpen to work\b/.test(et),Ws=/#Hiring\b/i.test(et)||/\bI'?m hiring\b/i.test(et)||/\bWe are hiring\b/i.test(et);return{name:$,title:T,location:ie,currentCompany:N,currentSchool:H,connectionDegree:ae,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:le,mutualConnectionsCount:xt,followers:zn,openToWork:Vs,hiring:Ws,about:Wn,topSkills:Yn,availableSections:Js}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,y=null,h=null,b=null,w=null,S=null;if(o||s||i||r||c||a){let p=await Promise.resolve().then(()=>(_s(),xs));o&&(m=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(y=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${y.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&&(w=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.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},...y!==null&&{featured:y},...h!==null&&{education:h},...b!==null&&{skillsFull:b},...w!==null&&{recommendations:w},...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 Et(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],y='[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(y))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"),y=document.querySelectorAll("button[aria-label]");return Array.from(y).filter(b=>{let w=b.getAttribute("aria-label")||"";return(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&m.test(w)}).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]"),y='[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(y))continue;let w=b.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(w)&&(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&h.test(w))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"),y=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(),w=b.includes("invite"),S=d?b.includes(d):!0;return{isMuted:m,isStickyHeader:y,inRecommendations:h,hasInvite:w,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,y=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:y,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 y=m.innerText?.trim(),h=m.getAttribute("aria-label")||"",b=m.getBoundingClientRect();return b.top<100||b.top>600||b.width===0?!1:y==="Follow"||y==="Message"||y==="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 y of d.querySelectorAll("button"))if(y.innerText?.trim()==="More"&&y!==f)return y;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 y of m){let h=y.querySelector('a[href*="custom-invite"]');if(h)return h;for(let b of y.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 y of d)for(let h of y.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 y=d.getBoundingClientRect();if(!(y.width===0||y.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 Pn(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 ga(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 Et(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 Xe(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Xe(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 jn(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 ya(e,t,n);return r.connectionSent&&!i&&Co(t,o),r}async function ya(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 w=J()[t]?.location;if(Vt(w,c))return console.log(` \u26A0 Excluded location (stored): ${w}`),a.reason="excluded_location",a.profileInfo={location:w},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(w){if(w.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),a.reason="session_expired",a.fatal=!0,a;throw w}if(await k(2e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(2e3),await Ds(e,t),await k(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:w,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(sn(),Io)),{recordDiscoveredEdges:g}=await Promise.resolve().then(()=>(bt(),jo)),{detectCategoryFromTitle:p}=await $n().then(()=>cs),{detectSectors:v}=await Promise.resolve().then(()=>(Is(),Rs)),C=S(t)||t,_=await w(e,{seedUrl:C}),R=_.map(x=>{let D=x.headline?p(x.headline):null;return{url:x.url,seedUrl:C,block:x.block,rank:x.rank,name:x.name,headline:x.headline,categories:D?[D]:[],sectors:v(x.headline||"")}});g(R),_.length&&console.log(` \xB7 discovery: harvested ${_.length} related profiles`)}catch(w){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${w.message}`)}a.profileInfo=await e.evaluate(()=>{let w=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")),_=v.find(j=>{let L=j.textContent&&j.textContent.trim();return L&&L.length>1&&L.length<100&&!w.has(L)&&L!=="0 notifications"}),R=_?_.textContent.trim():null,x=_?_.parentElement:null;for(;x&&x!==p&&!Array.from(x.children).filter(U=>U.tagName==="P").some(U=>{let q=U.textContent&&U.textContent.trim();return q&&q.length>5&&!S(q)});)x=x.parentElement;let D=null,z=null,$=null;if(x&&x!==p){let j=Array.from(x.children),L=j.filter(q=>q.tagName==="P").filter(q=>{let le=q.textContent&&q.textContent.trim();return le&&le.length>5&&!S(le)});L[0]&&(D=L[0].textContent.trim()),L[1]&&(z=L[1].textContent.trim());let U=j.filter(q=>q.tagName==="DIV");for(let q=U.length-1;q>=0;q--){let le=U[q].textContent&&U[q].textContent.trim();if(le&&!(R&&le.startsWith(R))&&($=le.split(/[·•]/)[0].trim(),$))break}}let E=null;if(x){let j=x.querySelectorAll("p, span, div");for(let L of j){let U=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){E=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]'),ie=H&&H.src||null,ae=!!p.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:D,location:$,about:T,company:z,connectionDegree:E,connectionsCount:null,mutualConnections:null,photoUrl:ie,hasVerifiedBadge:ae}});try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(a.resolvedUrl=w.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let w=a.profileInfo?.location,S=J()[t]?.location,g=w||S;if(Vt(g,c))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${g}`),a.reason="excluded_location",a;!w&&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 Et(e);if(d||await Ae(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await k(2e3),d=await Et(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),a.reason="connected",a;if(!d){let w=await Ee(e,{detail:!0});return r&&(w.status==="connected"||w.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 Pn(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 w=await Ee(e);if(w==="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: ${w} \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 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 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(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 w=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of w){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 w=await e.$('button[aria-label="Dismiss"]');if(w)try{await w.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 w=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(w.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(w.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 ga(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 Xe(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 Xe(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 w=await e.$('button[aria-label="Send without a note"]');if(w)return await Xe(e,w)?(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 w=b;if(w)return await Xe(e,w)?(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"]'),g=null;for(let p of S){let v=await e.evaluate(C=>{let _=C.getBoundingClientRect();return{visible:_.width>0&&_.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 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 _=await e.$('button[aria-label="Send without a note"]');if(_)return console.log(" Modal appeared via More dropdown, sending without note..."),await Xe(e,_)?(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 Os(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(`
240
+ `});var Ns={};ue(Ns,{DEFAULT_PROFILE_INTERESTS:()=>Os,computeFit:()=>va,detectSectors:()=>Sa});function Sa(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,s]of Object.entries(ba))s.some(i=>i.test(t))&&n.push(o);return n}function va(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 ba,Os,Ms=Z(()=>{ba={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:()=>Pn,default:()=>Ca,detectConnectionStatus:()=>_e,findConnectButton:()=>_t,runFunnel:()=>js,sendConnectionRequest:()=>jn,shouldExcludeLocation:()=>Vt,viewProfile:()=>Mn});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 Mn(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),Ys=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):Ys&&(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(Qs=>Qs.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 Gs=[...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)))],et=document.body.textContent||"",Ks=/#OpenToWork\b/i.test(et)||/\bOpen to work\b/.test(et),zs=/#Hiring\b/i.test(et)||/\bI'?m hiring\b/i.test(et)||/\bWe are hiring\b/i.test(et);return{name:$,title:T,location:ae,currentCompany:N,currentSchool:H,connectionDegree:le,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:ce,mutualConnectionsCount:At,followers:Kn,openToWork:Ks,hiring:zs,about:Wn,topSkills:Yn,availableSections:Gs}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,y=null,h=null,b=null,w=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&&(y=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${y.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&&(w=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.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},...y!==null&&{featured:y},...h!==null&&{education:h},...b!==null&&{skillsFull:b},...w!==null&&{recommendations:w},...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],y='[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(y))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"),y=document.querySelectorAll("button[aria-label]");return Array.from(y).filter(b=>{let w=b.getAttribute("aria-label")||"";return(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&m.test(w)}).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]"),y='[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(y))continue;let w=b.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(w)&&(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&h.test(w))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"),y=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(),w=b.includes("invite"),S=d?b.includes(d):!0;return{isMuted:m,isStickyHeader:y,inRecommendations:h,hasInvite:w,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,y=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:y,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 y=m.innerText?.trim(),h=m.getAttribute("aria-label")||"",b=m.getBoundingClientRect();return b.top<100||b.top>600||b.width===0?!1:y==="Follow"||y==="Message"||y==="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 y of d.querySelectorAll("button"))if(y.innerText?.trim()==="More"&&y!==f)return y;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 y of m){let h=y.querySelector('a[href*="custom-invite"]');if(h)return h;for(let b of y.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 y of d)for(let h of y.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 y=d.getBoundingClientRect();if(!(y.width===0||y.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 Pn(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 ka(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 Xe(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Xe(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 jn(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 $a(e,t,n);return r.connectionSent&&!i&&xo(t,o),r}async function $a(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 w=J()[t]?.location;if(Vt(w,c))return console.log(` \u26A0 Excluded location (stored): ${w}`),a.reason="excluded_location",a.profileInfo={location:w},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(w){if(w.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),a.reason="session_expired",a.fatal=!0,a;throw w}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:w,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(sn(),Mo)),{recordDiscoveredEdges:g}=await Promise.resolve().then(()=>(bt(),qo)),{detectCategoryFromTitle:p}=await $n().then(()=>ms),{detectSectors:v}=await Promise.resolve().then(()=>(Ms(),Ns)),C=S(t)||t,x=await w(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(w){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${w.message}`)}a.profileInfo=await e.evaluate(()=>{let w=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&&!w.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 w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(a.resolvedUrl=w.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let w=a.profileInfo?.location,S=J()[t]?.location,g=w||S;if(Vt(g,c))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${g}`),a.reason="excluded_location",a;!w&&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 w=await _e(e,{detail:!0});return r&&(w.status==="connected"||w.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 Pn(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 w=await _e(e);if(w==="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: ${w} \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 w=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of w){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 w=await e.$('button[aria-label="Dismiss"]');if(w)try{await w.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 w=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(w.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(w.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 ka(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 Xe(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 Xe(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 w=await e.$('button[aria-label="Send without a note"]');if(w)return await Xe(e,w)?(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 w=b;if(w)return await Xe(e,w)?(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 Xe(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
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=ut();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 y=t[m];try{if(e.isClosed()){console.log(`
243
243
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
244
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let h=vo(y.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}] ${y.name||y.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(y,f,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl}`);let b=null;if(r){let w=await Mn(e,y.profileUrl);w?(Re(y.profileUrl,{...w,source:u}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w,resolvedUrl:w.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 w=tn();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(b=await jn(e,y.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(`
244
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let h=_o(y.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}] ${y.name||y.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(y,f,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl}`);let b=null;if(r){let w=await Mn(e,y.profileUrl);w?(Re(y.profileUrl,{...w,source:u}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w,resolvedUrl:w.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 w=tn();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(b=await jn(e,y.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
245
  \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&&(ko(y.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&It(y.profileUrl,b.resolvedUrl),So(y.profileUrl,{source:u||"funnel",jobId:y.jobId||y.fromJob?.jobId||null,jobTitle:y.fromJob?.title||null,jobCompany:y.fromJob?.company||null,action:b.reason})),a&&await a(y,f,b),m<t.length-1){let w=c+Math.random()*2e3;await k(w)}}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=ut();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}var wa,Ms=ce(async()=>{Fe();await Ve();wa={viewProfile:Mn,detectConnectionStatus:Ee,findConnectButton:Et,clickConnectButton:Pn,sendConnectionRequest:jn,runFunnel:Os,shouldExcludeLocation:Vt}});Fe();await Ve();bt();await Ve();bt();var Nr=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"]),Mr=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Lo=["vancouver","british columbia"],Pr=["canada","montreal","quebec","alberta","calgary","ottawa"],jr=["toronto","ontario"],Lr=["india","pakistan","nigeria","philippines"];function Fr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)Nr.has(u)&&s++,Mr.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=Ur(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";Lr.some(u=>r.includes(u))?n-=30:c&&/united states|usa|\bus\b/i.test(r)?n+=25:c&&Lo.some(u=>r.includes(u))?n+=22:c?n+=20:Lo.some(u=>r.includes(u))?n+=18:Pr.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 Fo(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=gt(),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=yt(),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:Fr(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 Ur(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 st();import Yr from"puppeteer";import{addExtra as Gr}from"puppeteer-extra";import zr from"puppeteer-extra-plugin-stealth";Fe();await st();tt();tt();import dn from"fs";import qr from"path";var Br={headless:!1,defaultViewport:null,protocolTimeout:3e5},vt=new Set,Uo=!1;async function Pt(){let e=[...vt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});vt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Hr(){if(Uo)return;Uo=!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 vt)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function fn(e){return qr.join(e,".ilml-browser-session.json")}function Jo(e,t={}){try{dn.writeFileSync(fn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Jr(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Jo(e,n?{wsEndpoint:n}:{})}catch{}}function Vr(e){let t=Vo(e);t&&t.ownerPid===process.pid&&St(e)}function St(e){try{dn.rmSync(fn(e),{force:!0})}catch{}}function Vo(e){try{return JSON.parse(dn.readFileSync(fn(e),"utf-8"))}catch{return null}}function qo(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Bo(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 Ho(e,t,{probeTimeoutMs:n=4e3}={}){let o=Vo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&qo(o.ownerPid)?"live":(St(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await Bo(i,n,s);if(r===s)return i.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!r)return St(t),"free";if(qo(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Bo(r.close().then(()=>!0).catch(()=>!1),n,!1))return St(t),"free";try{r.disconnect()}catch{}return"live"}function Wr(e,t){e&&(Hr(),vt.add(e),e.on("disconnected",()=>{vt.delete(e),t&&St(t)}))}async function Wo(e,t={}){let n=eo(),o={...Br,...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 Ho(e,n)==="live")throw new Error(s);Jo(n);let i;try{i=await e.launch(o)}catch{if(await Ho(e,n)==="live")throw new Error(s);so(n);try{i=await e.launch(o)}catch(c){throw Vr(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 Wr(i,n),Jr(n,i),{browser:i,profileDir:n,needsSeed:no(n)}}async function Yo(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(..._t()),oo(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Ko=Gr(Yr);Ko.use(zr());async function Qo(){let{browser:e,profileDir:t,needsSeed:n}=await Wo(Ko),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Yo(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 Xo(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 y=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:f,lastMessageBy:d,x:y.x+y.width/2,y:y.y+y.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 Kr(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 Go(e,t){let n=await Kr(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 Go(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(y=>y.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 Go(e,t);return r?{verified:!0,headerName:c}:{verified:!1,headerName:c}}async function Qr(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 Qr(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 y=atob(d[1]).match(/^(\d{13})/);if(!y)return null;let h=Number(y[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 w=b.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!w)return null;let S=m?new Date(m).toISOString():d?`${d} ${h}`.trim():h;return{sender:f,text:w,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 y=m.querySelector(".msg-s-message-group__name");y&&(s=y.textContent?.trim()||s);let h=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let w of b){let S=l(w,h,a);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let y of m){let h=y.querySelector(".msg-s-message-group__name");h&&(s=h.textContent?.trim()||s);let w=l(y,s||"Unknown",a);w&&o.push(w)}}}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=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(y=>y===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),y=Ge(d.sender),h=!1;for(let b=0;b<u.length;b++){let w=u[b];if(Ge(w.sender)!==y)continue;let S=Ge(w.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 Zo(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 w=h.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=w.toLowerCase();if(S.includes(l)){let g=h.getBoundingClientRect();if(g.height>0){let p=w.includes(",")||/\d+ other/.test(w),v=S===u?3:S.includes(u)?2:1,C={text:w,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 y=[...d,...m];return a&&y.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 te from"fs";import*as $e from"path";import{fileURLToPath as pi}from"url";import"dotenv/config";import{createGraphClient as ci,resolveToken as ui}from"@ilivemylife/graph-sdk";import{config as di}from"dotenv";di();var us=ui()||process.env.TOKEN;us||(console.error(`
246
+ \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(b&&b.reason&&(Eo(y.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&It(y.profileUrl,b.resolvedUrl),Co(y.profileUrl,{source:u||"funnel",jobId:y.jobId||y.fromJob?.jobId||null,jobTitle:y.fromJob?.title||null,jobCompany:y.fromJob?.company||null,action:b.reason})),a&&await a(y,f,b),m<t.length-1){let w=c+Math.random()*2e3;await k(w)}}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=ut();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}var Ca,Fs=Z(async()=>{Fe();await Ve();Ca={viewProfile:Mn,detectConnectionStatus:_e,findConnectButton:_t,clickConnectButton:Pn,sendConnectionRequest:jn,runFunnel:js,shouldExcludeLocation:Vt}});Fe();await Ve();bt();await Ve();bt();var Ur=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"]),qr=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Bo=["vancouver","british columbia"],Br=["canada","montreal","quebec","alberta","calgary","ottawa"],Hr=["toronto","ontario"],Jr=["india","pakistan","nigeria","philippines"];function Vr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)Ur.has(u)&&s++,qr.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=Wr(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";Jr.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:Br.some(u=>r.includes(u))?n+=10:Hr.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=gt(),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=yt(),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:Vr(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 Wr(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 st();import Zr from"puppeteer";import{addExtra as ei}from"puppeteer-extra";import ti from"puppeteer-extra-plugin-stealth";Fe();await st();tt();tt();import dn from"fs";import Yr from"path";var Gr={headless:!1,defaultViewport:null,protocolTimeout:3e5},vt=new Set,Jo=!1;async function Pt(){let e=[...vt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});vt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Kr(){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 vt)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function fn(e){return Yr.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 zr(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Go(e,n?{wsEndpoint:n}:{})}catch{}}function Qr(e){let t=Ko(e);t&&t.ownerPid===process.pid&&St(e)}function St(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":(St(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 St(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 St(t),"free";try{r.disconnect()}catch{}return"live"}function Xr(e,t){e&&(Kr(),vt.add(e),e.on("disconnected",()=>{vt.delete(e),t&&St(t)}))}async function zo(e,t={}){let n=eo(),o={...Gr,...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 Qr(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 Xr(i,n),zr(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=ei(Zr);es.use(ti());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 y=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:f,lastMessageBy:d,x:y.x+y.width/2,y:y.y+y.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 ni(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 ni(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(y=>y.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 oi(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 oi(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 y=atob(d[1]).match(/^(\d{13})/);if(!y)return null;let h=Number(y[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 w=b.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!w)return null;let S=m?new Date(m).toISOString():d?`${d} ${h}`.trim():h;return{sender:f,text:w,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 y=m.querySelector(".msg-s-message-group__name");y&&(s=y.textContent?.trim()||s);let h=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let w of b){let S=l(w,h,a);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let y of m){let h=y.querySelector(".msg-s-message-group__name");h&&(s=h.textContent?.trim()||s);let w=l(y,s||"Unknown",a);w&&o.push(w)}}}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(y=>y===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),y=Ge(d.sender),h=!1;for(let b=0;b<u.length;b++){let w=u[b];if(Ge(w.sender)!==y)continue;let S=Ge(w.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 w=h.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=w.toLowerCase();if(S.includes(l)){let g=h.getBoundingClientRect();if(g.height>0){let p=w.includes(",")||/\d+ other/.test(w),v=S===u?3:S.includes(u)?2:1,C={text:w,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 y=[...d,...m];return a&&y.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 Si}from"url";import"dotenv/config";import{createGraphClient as hi,resolveToken as gi}from"@ilivemylife/graph-sdk";import{config as yi}from"dotenv";yi();var ps=gi()||process.env.TOKEN;ps||(console.error(`
248
248
  [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
249
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
250
250
  `),console.error(` Or add ILML_TOKEN=... to .env
251
- `),process.exit(1));var ds=ci({token:us});function fi(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function mi({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",r=new Date().toISOString().slice(0,16).replace("T"," "),c=s?` ${fi(s)}`:"",a=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",l=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${l} \u2014 ${a} \u2014 ${r}${c}`}async function fs({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 a=`**${mi({scriptName:e,mode:t,status:n,error:s,duration:i})}**
251
+ `),process.exit(1));var hs=hi({token:ps});function wi(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function bi({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",r=new Date().toISOString().slice(0,16).replace("T"," "),c=s?` ${wi(s)}`:"",a=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",l=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${l} \u2014 ${a} \u2014 ${r}${c}`}async function gs({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 a=`**${bi({scriptName:e,mode:t,status:n,error:s,duration:i})}**
252
252
 
253
253
  ${o.join(`
254
- `)}`;try{await ds.addMessage(r,a)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var hi=pi(import.meta.url),gi=$e.dirname($e.dirname(hi)),Cn=process.env.DATA_DIR?$e.resolve(process.env.DATA_DIR,"collected-profiles"):$e.join(gi,"collected-profiles"),En=$e.join(Cn,"run-log.json");function yi(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 qt(){try{if(!te.existsSync(En))return{runs:[]};let e=JSON.parse(te.readFileSync(En,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ms(e){te.existsSync(Cn)||te.mkdirSync(Cn,{recursive:!0});try{yi(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),ms(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Qe(e,t,n=null,o=null){if(!e)return;let s=null;try{let r=qt(),c=r.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,s=c.duration;else{let a=r.runs.find(l=>l.script===e.script&&l.status==="running"&&l.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration)}ms(r)}catch(r){console.error(`[runLog] Failed to end run: ${r.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let r=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";fs({scriptName:e.script,mode:e.mode,status:r,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}function wi(){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 bi(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 ps(){let e=["sync-all","messages","funnel","sync","apply"],t=qt(),n=wi(),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?bi(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(([,w])=>typeof w=="number"&&w>0).slice(0,3).map(([w,S])=>`${S} ${w}`);b.length&&(m=` (${b.join(", ")})`)}let y=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${u.padEnd(16)}${y}${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 On from"os";import*as P from"path";import{fileURLToPath as Hi}from"url";var _n={};ue(_n,{NAME:()=>vi,VERSION:()=>Si,up:()=>Ci});import*as ne from"fs";import*as Ht from"path";var Si=1,vi="normalize-jobs-and-questions",ki=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],$i=50;function An(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function xn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(s){try{ne.unlinkSync(o)}catch{}throw s}try{ne.renameSync(o,e)}catch(s){try{ne.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 Ci(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 ki)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 y=(d.questions||[]).map(h=>{let b={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=$i?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||y.length,questions:y})}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 Tn={};ue(Tn,{NAME:()=>Ai,VERSION:()=>Ei,up:()=>Ti});import*as oe from"fs";import*as hs from"path";var Ei=2,Ai="reset-unread-flags";function xi(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function _i(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 Ti(e){let t=hs.join(e,"conversations.json"),n=xi(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}_i(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Rn={};ue(Rn,{NAME:()=>Ii,VERSION:()=>Ri,up:()=>Pi});import*as se from"fs";import*as gs from"path";var Ri=3,Ii="recompute-last-message-by",Di=new Set(["draft","confirmed","rejected","needs_review"]);function Oi(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Ni(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}}function Mi(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Di.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 Pi(e){let t=gs.join(e,"conversations.json"),n=Oi(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=Mi(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}Ni(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 In={};ue(In,{NAME:()=>Li,VERSION:()=>ji,up:()=>Bi});import*as re from"fs";import*as ys from"path";var ji=4,Li="split-connection-timestamps",Fi=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ui(e){if(!re.existsSync(e))return null;let t=re.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function qi(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 Bi(e){let t=ys.join(e,"people.json"),n=Ui(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++,Fi.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}qi(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();bt();var Ji=Hi(import.meta.url),Vi=P.dirname(Ji),Wi=P.dirname(P.dirname(Vi));function Yi(e){return e&&(e==="~"?On.homedir():e.startsWith("~/")||e.startsWith("~\\")?P.join(On.homedir(),e.slice(2)):e)}var de=process.env.DATA_DIR?P.resolve(Yi(process.env.DATA_DIR)):Wi,Me=P.join(de,"collected-profiles"),Pe=P.join(de,"market-research"),G=P.join(de,".schema-version"),ws=[P.join(Me,".schema-version"),P.join(Pe,".schema-version")],Ce=4,he=[{version:1,module:_n},{version:2,module:Tn},{version:3,module:Rn},{version:4,module:In}];(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 ks(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
254
+ `)}`;try{await hs.addMessage(r,a)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var vi=Si(import.meta.url),ki=$e.dirname($e.dirname(vi)),Cn=process.env.DATA_DIR?$e.resolve(process.env.DATA_DIR,"collected-profiles"):$e.join(ki,"collected-profiles"),_n=$e.join(Cn,"run-log.json");function $i(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(_n))return{runs:[]};let e=JSON.parse(ne.readFileSync(_n,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ys(e){ne.existsSync(Cn)||ne.mkdirSync(Cn,{recursive:!0});try{$i(_n,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),ys(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Qe(e,t,n=null,o=null){if(!e)return;let s=null;try{let r=qt(),c=r.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,s=c.duration;else{let a=r.runs.find(l=>l.script===e.script&&l.status==="running"&&l.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration)}ys(r)}catch(r){console.error(`[runLog] Failed to end run: ${r.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let r=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";gs({scriptName:e.script,mode:e.mode,status:r,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}function Ci(){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 _i(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=Ci(),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?_i(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(([,w])=>typeof w=="number"&&w>0).slice(0,3).map(([w,S])=>`${S} ${w}`);b.length&&(m=` (${b.join(", ")})`)}let y=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${u.padEnd(16)}${y}${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 E from"fs";import*as On from"os";import*as P from"path";import{fileURLToPath as Ki}from"url";var xn={};ue(xn,{NAME:()=>Ai,VERSION:()=>Ei,up:()=>Ri});import*as oe from"fs";import*as Ht from"path";var Ei=1,Ai="normalize-jobs-and-questions",xi=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ti=50;function En(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function An(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 Ri(e,t){let n=Ht.join(e,"jobs.json"),o=Ht.join(t,"scouted-jobs.json"),s=Ht.join(e,"application-questions.json"),i=En(n)||{},r=En(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 xi)f[m]!=null&&d[m]==null&&(d[m]=f[m]);a.push(u),c++}c>0?(An(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=En(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 y=(d.questions||[]).map(h=>{let b={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=Ti?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||y.length,questions:y})}An(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];An(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 Tn={};ue(Tn,{NAME:()=>Di,VERSION:()=>Ii,up:()=>Mi});import*as se from"fs";import*as bs from"path";var Ii=2,Di="reset-unread-flags";function Oi(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Ni(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 Mi(e){let t=bs.join(e,"conversations.json"),n=Oi(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}Ni(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Rn={};ue(Rn,{NAME:()=>ji,VERSION:()=>Pi,up:()=>Bi});import*as re from"fs";import*as Ss from"path";var Pi=3,ji="recompute-last-message-by",Li=new Set(["draft","confirmed","rejected","needs_review"]);function Fi(e){return re.existsSync(e)?JSON.parse(re.readFileSync(e,"utf-8")):null}function Ui(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 qi(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Li.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 Bi(e){let t=Ss.join(e,"conversations.json"),n=Fi(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=qi(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}Ui(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 In={};ue(In,{NAME:()=>Ji,VERSION:()=>Hi,up:()=>Gi});import*as ie from"fs";import*as vs from"path";var Hi=4,Ji="split-connection-timestamps",Vi=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Wi(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 Yi(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 Gi(e){let t=vs.join(e,"people.json"),n=Wi(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++,Vi.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}Yi(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();bt();var zi=Ki(import.meta.url),Qi=P.dirname(zi),Xi=P.dirname(P.dirname(Qi));function Zi(e){return e&&(e==="~"?On.homedir():e.startsWith("~/")||e.startsWith("~\\")?P.join(On.homedir(),e.slice(2)):e)}var de=process.env.DATA_DIR?P.resolve(Zi(process.env.DATA_DIR)):Xi,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:xn},{version:2,module:Tn},{version:3,module:Rn},{version:4,module:In}];(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(`
256
256
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
257
- `),process.exit(1));try{A.mkdirSync(de,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
257
+ `),process.exit(1));try{E.mkdirSync(de,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
258
258
  [FATAL] Cannot create DATA_DIR (${de}): ${t.message}`),console.error(` Fix the path or permissions and try again.
259
- `),process.exit(1))}let e;try{e=A.statSync(de)}catch(t){console.error(`
259
+ `),process.exit(1))}let e;try{e=E.statSync(de)}catch(t){console.error(`
260
260
  [FATAL] DATA_DIR (${de}) is not accessible: ${t.message}
261
261
  `),process.exit(1)}e.isDirectory()||(console.error(`
262
262
  [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.
263
- `),process.exit(1));for(let t of[Me,Pe]){let n;try{n=A.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
263
+ `),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(`
264
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.
265
- `),process.exit(1))}}var Ne=P.join(de,".migration-lock");function Gi(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return A.writeFileSync(Ne,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(A.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
+ `),process.exit(1))}}var Ne=P.join(de,".migration-lock");function ea(){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(`
266
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: ${Ne}
267
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.
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=Ne+".tmp";try{return A.writeFileSync(n,e),A.renameSync(n,Ne),!0}catch(o){try{A.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Nn(){try{if(JSON.parse(A.readFileSync(Ne,"utf-8")).pid!==process.pid)return;A.unlinkSync(Ne)}catch{}}var bs=!1;function zi(){if(bs)return;bs=!0;let e=()=>{try{Nn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ki(){if(A.existsSync(G))return;let e=[],t=[];for(let i of ws)if(A.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=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 Nn(){try{if(JSON.parse(E.readFileSync(Ne,"utf-8")).pid!==process.pid)return;E.unlinkSync(Ne)}catch{}}var $s=!1;function ta(){if($s)return;$s=!0;let e=()=>{try{Nn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function na(){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(`
269
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(`
270
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.
271
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(`
272
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.
273
- `),process.exit(1)}let o=e[0].schema,s=G+".tmp";try{A.writeFileSync(s,JSON.stringify(o,null,2)),A.renameSync(s,G)}catch(i){try{A.unlinkSync(s)}catch{}throw i}for(let i of ws)if(A.existsSync(i))try{A.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${G}`)}function Qi(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=A.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ss(){if(Ki(),!A.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
+ `),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 oa(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(na(),!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(`
274
274
  [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.
275
- `),process.exit(1)}let t=Qi(e);return t===null&&(console.error(`
275
+ `),process.exit(1)}let t=oa(e);return t===null&&(console.error(`
276
276
  [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.
277
- `),process.exit(1)),t}function $s(e){try{A.chmodSync(e,384)}catch{}}function Xi(e){if(ks(),A.existsSync(G))try{if(A.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{A.writeFileSync(t,JSON.stringify(e,null,2)),$s(t),A.renameSync(t,G)}catch(n){try{A.unlinkSync(t)}catch{}throw n}}function vs(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{Es(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 Dn=!1;async function Cs(){if(Dn)return;ks(),oa();let t=Ss().version;if(t===Ce){Dn=!0;return}zi(),Gi(),process.on("exit",Nn),t>Ce&&(console.error(`
277
+ `),process.exit(1)),t}function As(e){try{E.chmodSync(e,384)}catch{}}function sa(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 Dn=!1;async function xs(){if(Dn)return;Es(),ca();let t=Cs().version;if(t===Ce){Dn=!0;return}ta(),ea(),process.on("exit",Nn),t>Ce&&(console.error(`
278
278
  [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.
279
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${Ce}.
280
280
  `),process.exit(1)),console.log(`
281
- \u{1F4E6} Schema migration: v${t} \u2192 v${Ce}`);let n=sa();if(!n.ok){console.error(`
281
+ \u{1F4E6} Schema migration: v${t} \u2192 v${Ce}`);let n=ua();if(!n.ok){console.error(`
282
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(`
283
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'.
284
284
  `),process.exit(1)}let o=he.filter(s=>s.version>t);for(let s of o){console.log(`
285
- Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{vs(Me,s.version),vs(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{_s(Me,s.version),_s(Pe,s.version)}catch(a){console.error(`
286
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.
287
287
  `),process.exit(1)}let c=s.module;try{await c.up(Me,Pe)}catch(a){console.error(`
288
- [FATAL] Migration ${i} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let l=ra(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
+ [FATAL] Migration ${i} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let l=da(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.
289
289
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${l.error}`),console.error(` Manual recovery: copy *${r} files back over the originals.
290
290
  `))}catch(l){console.error(` [!] Auto-rollback CRASHED while restoring: ${l.message}`),console.error(` Manual recovery: copy *${r} files back over the originals.
291
- `)}process.exit(1)}try{let a=new Date().toISOString(),l={version:s.version,name:c.NAME||i,appliedAt:a},u=Ss();u.version=s.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(l),Xi(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=Cs();u.version=s.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(l),sa(u)}catch(a){console.error(`
292
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.
293
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{wo()}catch{}try{ln()}catch{}Dn=!0,Nn(),console.log(`
293
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{ko()}catch{}try{ln()}catch{}Dn=!0,Nn(),console.log(`
294
294
  \u2713 Schema is now at v${Ce}
295
- `)}var Zi=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ea(e){let t=e.toLowerCase();return Zi.some(n=>n.test(t))}var ta=6e4;function na(){let e=Date.now(),t=[];for(let n of[de,Me,Pe]){if(!A.existsSync(n))continue;let o;try{o=A.readdirSync(n)}catch{continue}for(let s of o){if(!ea(s))continue;let i=P.join(n,s);try{let r=A.statSync(i);if(!r.isFile()||e-r.mtimeMs<ta)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function oa({verbose:e=!1}={}){let t=na();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 sa(){let e=[];for(let t of[Me,Pe]){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{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 ra(e){let t=[],n=[];for(let i of[Me,Pe]){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")?Jt(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{Es(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 Es(e,t){let n=t+".tmp";try{A.copyFileSync(e,n),$s(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}}tt();Fe();async function ia(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 As(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await ia(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 Cs();var qs="https://www.linkedin.com/messaging/",ba=10,Ln=3,Sa=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},va=()=>_t(),Le={pageRecoveries:0};async function Wt(e,t){if(Le.pageRecoveries>=ba)throw new Error(`CDP unrecoverable: ${Le.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
296
- \u{1F504} CDP dead \u2014 recovering page (#${Le.pageRecoveries+1}). Reason: ${t}`),e.page=await As(e.browser,e.page,{returnUrl:qs,cookiesProvider:va,setupPage:Sa}),Le.pageRecoveries++,await k(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${Le.pageRecoveries}).
297
- `)}function Ze(e){return(e.messages||[]).find(t=>ot.has(t.status))?.status}var X=process.argv.slice(2),Fn=X.includes("--full"),W=X.includes("--dry-run"),Ps=X.includes("--report"),Un=X.includes("--verbose"),js=X.includes("--backfill"),Ls=X.includes("--enrich"),Fs=X.includes("--today"),qn=X.includes("--read-unread"),At=parseInt(X.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),ka=X.includes("--auto-enrich-replies"),Us=parseInt(X.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),$a=parseInt(X.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function Ca(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 Ea(e,t){console.log(`
295
+ `)}var ra=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ia(e){let t=e.toLowerCase();return ra.some(n=>n.test(t))}var aa=6e4;function la(){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(!ia(s))continue;let i=P.join(n,s);try{let r=E.statSync(i);if(!r.isFile()||e-r.mtimeMs<aa)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function ca({verbose:e=!1}={}){let t=la();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 ua(){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 da(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}}tt();Fe();async function fa(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 fa(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 Vs="https://www.linkedin.com/messaging/",_a=10,Ln=3,Ea=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},Aa=()=>xt(),Le={pageRecoveries:0};async function Wt(e,t){if(Le.pageRecoveries>=_a)throw new Error(`CDP unrecoverable: ${Le.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
296
+ \u{1F504} CDP dead \u2014 recovering page (#${Le.pageRecoveries+1}). Reason: ${t}`),e.page=await Rs(e.browser,e.page,{returnUrl:Vs,cookiesProvider:Aa,setupPage:Ea}),Le.pageRecoveries++,await k(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${Le.pageRecoveries}).
297
+ `)}function Ze(e){return(e.messages||[]).find(t=>ot.has(t.status))?.status}var X=process.argv.slice(2),Fn=X.includes("--full"),W=X.includes("--dry-run"),Us=X.includes("--report"),Un=X.includes("--verbose"),qs=X.includes("--backfill"),Bs=X.includes("--enrich"),Hs=X.includes("--today"),qn=X.includes("--read-unread"),Et=parseInt(X.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),xa=X.includes("--auto-enrich-replies"),Js=parseInt(X.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),Ta=parseInt(X.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function Ra(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 Ia(e,t){console.log(`
298
298
  \u2550\u2550 PHASE 1: Inbox Scan \u2550\u2550
299
- `);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 w=await Xo(e),S=0;for(let p of w){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=Ca(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(Un?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
+ `);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 w=await ns(e),S=0;for(let p of w){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=Ra(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(Un?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
300
  3 rounds with no new items \u2014 end of visible list.`);break}}else f=0;if(!Fn){if(i.size===u){if(l++,l>=3){console.log(`
301
301
  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(`
302
302
  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)}Un||process.stdout.write(`
303
303
  `);let y=new Date().toISOString(),h=0;for(let[w,{card:S}]of i)t[w]||(t[w]={profileUrl:null,lastSynced:y,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[w,S]of r)t[w]||(t[w]={profileUrl:null,lastSynced:y,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: ${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 w={};for(let{reason:S}of i.values())w[S]=(w[S]||0)+1;for(let[S,g]of Object.entries(w))console.log(` ${S}: ${g}`)}if(!W){let w=nn();w.lastIncrementalSync=new Date().toISOString(),Fn&&(w.lastFullSync=w.lastIncrementalSync),Ao(w),be(t)}return{allCards:s,toReRead:i,unreadCards:r}}async function Aa(e,t,n,o){console.log(`
304
+ 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 w={};for(let{reason:S}of i.values())w[S]=(w[S]||0)+1;for(let[S,g]of Object.entries(w))console.log(` ${S}: ${g}`)}if(!W){let w=nn();w.lastIncrementalSync=new Date().toISOString(),Fn&&(w.lastFullSync=w.lastIncrementalSync),Ro(w),be(t)}return{allCards:s,toReRead:i,unreadCards:r}}async function Da(e,t,n,o){console.log(`
305
305
  \u2550\u2550 PHASE 2: Read Changed Threads \u2550\u2550
306
- `);let s=Array.from(t.entries()),i=Math.min(s.length,At);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(!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=${At})
307
- `);let c=[],a=[],l=0,u=0;for(let f=0;f<i;f++){let[d,{card:m,reason:y}]=s[f];console.log(` [${f+1}/${i}] ${d} (${y})`);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 Zo(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 w=await gn(h);if(w&&w.length>0){if(!yn(w,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,w),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 _=p.messages.length-v;console.log(` ${p.messages.length} msgs (${_>=0?"+"+_:_} new)${g&&!p.profileUrl?" +url":""}`),c.push({name:d}),a=[...new Set(w.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(`
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 xa(e,t,n){if(!ka)return null;console.log(`
306
+ `);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(Vs,{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})
307
+ `);let c=[],a=[],l=0,u=0;for(let f=0;f<i;f++){let[d,{card:m,reason:y}]=s[f];console.log(` [${f+1}/${i}] ${d} (${y})`);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 w=await gn(h);if(w&&w.length>0){if(!yn(w,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,w),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(w.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(`
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 Oa(e,t,n){if(!xa)return null;console.log(`
309
309
  \u2550\u2550 PHASE 2.5: Auto-enrich-replies \u2550\u2550
310
- `);let o=new Set(n.map(m=>m.name)),s=J(),i=Date.now(),r=$a*24*60*60*1e3,c=[];for(let m of o){let y=t[m];if(!y||y.lastMessageBy!=="them")continue;let h=y.profileUrl;if(!h)continue;let w=s[h]?._lastEnrichedAt;if(w){let S=i-new Date(w).getTime();if(Number.isFinite(S)&&S<r)continue}c.push({name:m,profileUrl:h,lastMessageTime:y.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:W};c.sort((m,y)=>{let h=new Date(m.lastMessageTime||0).getTime();return new Date(y.lastMessageTime||0).getTime()-h});let a=c.slice(0,Us),l=c.length-a.length;if(console.log(` Candidates: ${c.length} | picking ${a.length} (cap ${Us}) | 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 Ms().then(()=>Ns),f=0,d=0;for(let m=0;m<a.length;m++){let y=a[m];console.log(`
310
+ `);let o=new Set(n.map(m=>m.name)),s=J(),i=Date.now(),r=Ta*24*60*60*1e3,c=[];for(let m of o){let y=t[m];if(!y||y.lastMessageBy!=="them")continue;let h=y.profileUrl;if(!h)continue;let w=s[h]?._lastEnrichedAt;if(w){let S=i-new Date(w).getTime();if(Number.isFinite(S)&&S<r)continue}c.push({name:m,profileUrl:h,lastMessageTime:y.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:W};c.sort((m,y)=>{let h=new Date(m.lastMessageTime||0).getTime();return new Date(y.lastMessageTime||0).getTime()-h});let a=c.slice(0,Js),l=c.length-a.length;if(console.log(` Candidates: ${c.length} | picking ${a.length} (cap ${Js}) | 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 y=a[m];console.log(`
312
312
  [${m+1}/${a.length}] Enriching ${y.name} ${y.profileUrl}`);try{let h=await u(e.page,y.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"},w=!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,w=!0);w&&(b._lastEnrichedAt=new Date().toISOString()),Re(y.profileUrl,b),h.resolvedUrl&&It(y.profileUrl,h.resolvedUrl),f++,console.log(` \u2713 saved (rich sections: ${w?"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(`
313
313
  Auto-enrich done: ${f} enriched, ${d} errors, ${l} skipped (over cap)
314
- `),{picked:a.length,enriched:f,skipped:l,errors:d}}function _a(e,t){console.log(`
314
+ `),{picked:a.length,enriched:f,skipped:l,errors:d}}function Na(e,t){console.log(`
315
315
  \u2550\u2550 PHASE 3: Post-processing & Enrichment \u2550\u2550
316
- `);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.`),Bs(e)}function Bs(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 Ta(){let e=ct(),t=J(),n=Object.entries(e);console.log(`
316
+ `);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.`),Ws(e)}function Ws(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 Ma(){let e=ct(),t=J(),n=Object.entries(e);console.log(`
317
317
  \u2550\u2550 ENRICHMENT: Re-processing all conversations \u2550\u2550
318
- `);let o=0,s=0,i=0;for(let[f,d]of n){if(!d.profileUrl){let m=Object.entries(t).filter(([,y])=>y.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++}Bs(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
+ `);let o=0,s=0,i=0;for(let[f,d]of n){if(!d.profileUrl){let m=Object.entries(t).filter(([,y])=>y.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++}Ws(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(`
319
319
  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(`
320
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
321
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(`
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,y=0;for(let[,$]of s)for(let E of $.messages||[])m++,(!E.sender||E.sender==="Unknown")&&y++;console.log(`
323
- Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${y} (${m>0?(y/m*100).toFixed(1):0}%)`);let h={};for(let[,$]of s){let E=$.conversationStatus||"null";h[E]=(h[E]||0)+1}console.log(`
324
- Statuses:`);for(let[$,E]of Object.entries(h).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${E}`);let b={};for(let[,$]of s){let E=$.category||"(none)";b[E]=(b[E]||0)+1}console.log(`
325
- Categories:`);for(let[$,E]of Object.entries(b).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${E}`);let w={};for(let[,$]of s){let E=$.actionNeeded||"(none)";w[E]=(w[E]||0)+1}if(Object.keys(w).length>1||!w["(none)"]){console.log(`
326
- Actions Needed:`);for(let[$,E]of Object.entries(w).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${E}`)}let S=new Map;for(let[$,E]of s){if(!E.profileUrl)continue;let T=E.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(`
327
- Duplicates (${g.length}):`);for(let[$,E]of g)console.log(` ${E.join(" | ")} \u2192 ${$}`)}let p=s.filter(([,$])=>$.conversationStatus==="unanswered_by_us").sort(($,E)=>(E[1].lastSynced||"").localeCompare($[1].lastSynced||"")),v=s.filter(([,$])=>Ze($));if(console.log(`
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,y=0;for(let[,$]of s)for(let _ of $.messages||[])m++,(!_.sender||_.sender==="Unknown")&&y++;console.log(`
323
+ Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${y} (${m>0?(y/m*100).toFixed(1):0}%)`);let h={};for(let[,$]of s){let _=$.conversationStatus||"null";h[_]=(h[_]||0)+1}console.log(`
324
+ 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(`
325
+ Categories:`);for(let[$,_]of Object.entries(b).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${_}`);let w={};for(let[,$]of s){let _=$.actionNeeded||"(none)";w[_]=(w[_]||0)+1}if(Object.keys(w).length>1||!w["(none)"]){console.log(`
326
+ Actions Needed:`);for(let[$,_]of Object.entries(w).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(`
327
+ 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(([,$])=>Ze($));if(console.log(`
328
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
329
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:
330
- `);let E=30;for(let[T,N]of $.slice(0,E)){let H=e[T],ie=H?.category?` [${H.category}]`:"",ae=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}${ie}${ae?` \u2014 ${ae}`:""}`),j&&console.log(` "${j}"`),L?console.log(` ${L}`):U&&console.log(` ${U}`)}$.length>E&&console.log(`
331
- ... and ${$.length-E} more`),console.log(`
330
+ `);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(`
331
+ ... and ${$.length-_} more`),console.log(`
332
332
  To pull them into the local DB (will lose unread badges): npm run sync-all -- --read-unread
333
- `)}if(v.length>0){let $=v.filter(([,T])=>Ze(T)===V.CONFIRMED),E=v.filter(([,T])=>{let N=Ze(T);return N===V.DRAFT||N===V.NEEDS_REVIEW});console.log(` Drafts: ${v.length} total (${$.length} confirmed, ${E.length} pending)`),E.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"),_=p.filter(([,$])=>$.actionNeeded!=="schedule_call");if(_.sort(($,E)=>{let T={high:0,medium:1,low:2}[$[1].suggestedPriority]??3,N={high:0,medium:1,low:2}[E[1].suggestedPriority]??3;return T-N}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
334
- `);for(let[$,E]of C){let T=E.category||"",N=E.summary||"";console.log(` ${$}${T?` [${T}]`:""} \u2192 schedule_call`),N&&console.log(` ${N}`)}console.log()}if(_.length>0){console.log(` REPLY NEEDED (${_.length}):
335
- `);let $=20;for(let[E,T]of _.slice(0,$)){let N=T.category||"",H=T.suggestedPriority?`[${T.suggestedPriority}]`:"",ie=(T.autoTags||[]).slice(0,4).join(", "),ae=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(` ${H} ${E}${N?` [${N}]`:""}`),console.log(ae?` ${ae}`:` "${L}"`),ie&&console.log(` #${ie.replace(/, /g," #")}`)}_.length>$&&console.log(`
336
- ... and ${_.length-$} more`)}p.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let R=new Set(Object.keys(e)),x=new Set(Object.values(e).map($=>$.profileUrl).filter(Boolean)),D=Object.entries(i).filter(([$,E])=>E.connectionStatus==="connected"&&E.personActionNeeded==="initiate_contact"&&!x.has($)&&!(E.name&&R.has(E.name))).sort(($,E)=>{let T={high:0,medium:1,low:2}[$[1].personPriority]??3,N={high:0,medium:1,low:2}[E[1].personPriority]??3;return T!==N?T-N:(E[1].connectionDate||"").localeCompare($[1].connectionDate||"")});if(D.length>0){console.log(`
333
+ `)}if(v.length>0){let $=v.filter(([,T])=>Ze(T)===V.CONFIRMED),_=v.filter(([,T])=>{let N=Ze(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}):
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}):
335
+ `);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(`
336
+ ... 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(`
337
337
  INITIATE CONTACT (${D.length}):
338
- `);let $=20;for(let[E,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(`
339
- ... and ${D.length-$} more`)}let z=s.filter(([,$])=>$.conversationStatus==="awaiting_reply");z.length>0&&console.log(`
340
- BALL IN THEIR COURT: ${z.length} conversations`),W&&console.log(`
338
+ `);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(`
339
+ ... and ${D.length-$} more`)}let K=s.filter(([,$])=>$.conversationStatus==="awaiting_reply");K.length>0&&console.log(`
340
+ BALL IN THEIR COURT: ${K.length} conversations`),W&&console.log(`
341
341
  [DRY RUN \u2014 no changes written]`),console.log(`
342
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
343
- `)}async function Ra(e,t){console.log(`
343
+ `)}async function Pa(e,t){console.log(`
344
344
  \u2550\u2550 BACKFILL: Reading conversations with 0 messages \u2550\u2550
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,At);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${At})
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,Et);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${Et})
346
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 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 y=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(),y&&(h.profileUrl=y),t[l]=h,W||be(t),console.log(` \u2713 ${h.messages.length} msgs${y?" +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(`
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 Ia(e){let t=ut(),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 Da(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 Oa(){let e=Fo(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 Na(){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 Ma(){let e=xo();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 Pa(){let e=ct(),t=J(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(g=>g.profileUrl).filter(Boolean));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 ja(e){let t=ut(),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 La(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 Fa(){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 Ua(){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 qa(){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 Ba(){let e=ct(),t=J(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(g=>g.profileUrl).filter(Boolean));console.log(`
348
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
349
- `),console.log(ps()),console.log(""),Ia(t),console.log(""),Da(t),console.log(""),Na(),console.log(""),Oa(),console.log(""),Ma(),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:
350
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=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}${_}${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):
351
- `);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||Ke(g.lastMessagePreview)!==Ke(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}):
352
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=C.priority||C.suggestedPriority||"",R=C.category?` [${C.category}]`:"",x=C.summary||"";console.log(` ${p+1}. ${_?`[${_}] `:""}${v}${R} \u2014 ${x}`)}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}):
353
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=C.summary||C.personContext?.title||"";console.log(` ${p+1}. ${v} \u2014 ${_}`)}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}):
354
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${_} \u2014 ${R}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let y=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(y.length>0){let g=y.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${y.length}):
355
- `);for(let p=0;p<g.length;p++){let[v,C]=g[p],_=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${_} \u2014 ${R}`)}y.length>5&&console.log(` ... +${y.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}):
356
- `);for(let p=0;p<g.length;p++){let[,v]=g[p],C=v.personPriority?`[${v.personPriority.toUpperCase()}]`:"",_=v.connectionDate?ja(v.connectionDate):"",R=v.title?`${v.title}${v.company?` at ${v.company}`:""}`:v.company||"";console.log(` ${p+1}. ${C} ${v.name||"Unknown"} \u2014 ${R}${_?` (${_})`:""}`)}h.length>10&&console.log(` ... +${h.length-10} more`),console.log()}let b=s.filter(([,g])=>Ze(g));if(b.length>0){let g=b.filter(([,v])=>Ze(v)===V.CONFIRMED).length,p=b.filter(([,v])=>{let C=Ze(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 w=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, ${w} need reply, ${h.length} new connections, ${S} ball in their court`),console.log(`
349
+ `),console.log(ws()),console.log(""),ja(t),console.log(""),La(t),console.log(""),Ua(),console.log(""),Fa(),console.log(""),qa(),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:
350
+ `);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):
351
+ `);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}):
352
+ `);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}):
353
+ `);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}):
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}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let y=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(y.length>0){let g=y.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${y.length}):
355
+ `);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}`)}y.length>5&&console.log(` ... +${y.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}):
356
+ `);for(let p=0;p<g.length;p++){let[,v]=g[p],C=v.personPriority?`[${v.personPriority.toUpperCase()}]`:"",x=v.connectionDate?Ha(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])=>Ze(g));if(b.length>0){let g=b.filter(([,v])=>Ze(v)===V.CONFIRMED).length,p=b.filter(([,v])=>{let C=Ze(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 w=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, ${w} need reply, ${h.length} new connections, ${S} ball in their court`),console.log(`
357
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
358
- `)}function ja(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 La(){let e=ct();Bn(e,null,null)}async function Fa(){if(console.log(`
358
+ `)}function Ha(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 Ja(){let e=ct();Bn(e,null,null)}async function Va(){if(console.log(`
359
359
  LinkedIn Sync-All
360
- `),Fs){Pa();return}if(Ps){let r=Bt("sync-all","report");La(),Qe(r,"success");return}if(Ls){let r=Bt("sync-all","enrich");try{Ta(),Qe(r,"success")}catch(c){throw Qe(r,"error",null,c.message),c}return}let e=js?"backfill":Fn?"full":"incremental",t=Bt("sync-all",e),n={scanned:0,toReRead:0,threadsRead:0,newMessages:0};W&&console.log(" [DRY RUN mode]"),console.log(` Mode: ${e} | Max threads to read: ${At}`);let o=ct(),s=await Qo(),i={browser:s.browser,page:s.page};try{await mn(i.page);let r=null,c=[];if(js)c=await Ra(i,o);else{let a=0;for(;;)try{r=await Ea(i.page,o);break}catch(d){if(!je(d))throw d;if(a++,a>=Ln)throw new Error(`Phase 1 failed ${Ln} times on CDP death \u2014 giving up. Last: ${d.message}`);console.log(`
361
- \u26A0 Phase 1 CDP dead (attempt ${a}/${Ln}). Recovering and restarting Phase 1...`),await Wt(i,`Phase 1 attempt ${a}`)}let l=new Set;c=await Aa(i,r.toReRead,o,l),n.scanned=r.totalCards||0,n.toReRead=r.toReRead?.size||0;let u=new Set(c.map(d=>d.name)),f=0;for(let[d,{card:m}]of r.toReRead){if(u.has(d)||l.has(d))continue;let y=o[d];y&&(y.lastMessageBy=m.lastMessageBy,y.lastMessageTime=m.lastMessageTime||y.lastMessageTime,y.unread=m.unread,f++)}f>0&&(console.log(` Pending re-read: ${f} threads (raise --max or re-run to drain).`),W||be(o))}n.threadsRead=c.length,n.newMessages=c.reduce((a,l)=>a+(l.newMessages||0),0);try{let a=await xa(i,o,c);a&&(n.autoEnriched=a.enriched,a.authWall&&(n.autoEnrichAuthWall=!0))}catch(a){console.log(`
360
+ `),Hs){Ba();return}if(Us){let r=Bt("sync-all","report");Ja(),Qe(r,"success");return}if(Bs){let r=Bt("sync-all","enrich");try{Ma(),Qe(r,"success")}catch(c){throw Qe(r,"error",null,c.message),c}return}let e=qs?"backfill":Fn?"full":"incremental",t=Bt("sync-all",e),n={scanned:0,toReRead:0,threadsRead:0,newMessages:0};W&&console.log(" [DRY RUN mode]"),console.log(` Mode: ${e} | Max threads to read: ${Et}`);let o=ct(),s=await ts(),i={browser:s.browser,page:s.page};try{await mn(i.page);let r=null,c=[];if(qs)c=await Pa(i,o);else{let a=0;for(;;)try{r=await Ia(i.page,o);break}catch(d){if(!je(d))throw d;if(a++,a>=Ln)throw new Error(`Phase 1 failed ${Ln} times on CDP death \u2014 giving up. Last: ${d.message}`);console.log(`
361
+ \u26A0 Phase 1 CDP dead (attempt ${a}/${Ln}). Recovering and restarting Phase 1...`),await Wt(i,`Phase 1 attempt ${a}`)}let l=new Set;c=await Da(i,r.toReRead,o,l),n.scanned=r.totalCards||0,n.toReRead=r.toReRead?.size||0;let u=new Set(c.map(d=>d.name)),f=0;for(let[d,{card:m}]of r.toReRead){if(u.has(d)||l.has(d))continue;let y=o[d];y&&(y.lastMessageBy=m.lastMessageBy,y.lastMessageTime=m.lastMessageTime||y.lastMessageTime,y.unread=m.unread,f++)}f>0&&(console.log(` Pending re-read: ${f} threads (raise --max or re-run to drain).`),W||be(o))}n.threadsRead=c.length,n.newMessages=c.reduce((a,l)=>a+(l.newMessages||0),0);try{let a=await Oa(i,o,c);a&&(n.autoEnriched=a.enriched,a.authWall&&(n.autoEnrichAuthWall=!0))}catch(a){console.log(`
362
362
  \u26A0 Auto-enrich phase crashed: ${a.message?.slice(0,200)}`),console.log(` Continuing with post-processing \u2014 data integrity is unaffected.
363
- `)}c.length>0&&_a(o,c),Bn(o,r,c,{unreadCards:r?.unreadCards,readUnread:qn}),Le.pageRecoveries>0&&console.log(`
363
+ `)}c.length>0&&Na(o,c),Bn(o,r,c,{unreadCards:r?.unreadCards,readUnread:qn}),Le.pageRecoveries>0&&console.log(`
364
364
  CDP page recoveries this run: ${Le.pageRecoveries}`),W||on(),Qe(t,"success",n)}catch(r){console.error(`
365
- Error:`,r.message),Un&&console.error(r.stack),Qe(t,"error",n,r.message)}finally{if(!W&&!Ps&&!Ls&&!Fs)try{on()}catch{}await i.browser.close()}}Fa();
365
+ Error:`,r.message),Un&&console.error(r.stack),Qe(t,"error",n,r.message)}finally{if(!W&&!Us&&!Bs&&!Hs)try{on()}catch{}await i.browser.close()}}Va();