ilml-plugin-linkedin 1.13.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,325 @@
1
+ var qn=Object.defineProperty;var ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var ce=(e,t)=>{for(var n in t)qn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Bn}from"@ilivemylife/graph-sdk";var Un,Wr,ge,Gr,Yr,at=ne(async()=>{Un=await Bn();for(let[e,t]of Object.entries(Un))process.env[e]===void 0&&(process.env[e]=t);Wr=process.env.LINKEDIN_NAME,ge=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Gr=Object.freeze(new Set([ge.DRAFT,ge.CONFIRMED,ge.NEEDS_REVIEW])),Yr=Object.freeze(new Set([ge.DRAFT,ge.CONFIRMED,ge.REJECTED,ge.NEEDS_REVIEW]))});import"dotenv/config";import*as j from"fs";import*as B from"path";import{fileURLToPath as Vn}from"url";function qt(){xe=null,Wn=null,oe=null,Gn=null,Yn=null,Qn=null}function Ye(){j.existsSync(re)||j.mkdirSync(re,{recursive:!0})}function _e(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";j.writeFileSync(o,n);for(let r=0;r<3;r++)try{j.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw i}}function Oe(e,t){if(!j.existsSync(e))return null;try{let n=JSON.parse(j.readFileSync(e,"utf-8"));try{j.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(j.existsSync(o))try{let r=JSON.parse(j.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{j.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{j.copyFileSync(e,e+".corrupted")}catch{}return null}}function je(){return new Date().toISOString().split("T")[0]}function W(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Xn(){j.existsSync(ut)||j.mkdirSync(ut,{recursive:!0})}function Bt(e){let t=W(e);return t?B.join(ut,`${t}.json`):null}function Zn(e){let t=Bt(e);return t?Oe(t,`profile-history/${W(e)}.json`)||[]:[]}function eo(e,t){let n=Bt(e);if(!n)return;Xn();let o=Zn(e);o.unshift(t);try{_e(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${W(e)}: ${r.message}`)}}function Lt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Mt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function to(e,t){if(!e)return[];let n=[];for(let o of zn){let r=e[o],i=t[o];Lt(r)||Lt(i)||Mt(r)!==Mt(i)&&n.push(o)}return n}function no(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function H(){return xe||(Ye(),xe=Oe(ct,"people.json")||{},xe)}function dt(e){Ye(),xe=e;try{_e(ct,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(ct)}`)}}function Ge(e,t={}){if(!e)return null;let n=H(),o=je(),r=new Date().toISOString(),i=n[e];if(i){let a=to(i,t);a.length>0&&(eo(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:a,snapshot:no(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let u of Kn)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(i[u])&&i[u].length>0)continue;i[u]=t[u]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return dt(n),n[e]}function Ut(e,t){if(!e||!t)return;let n=H(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:je(),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(u=>u.date===i.date&&u.source===i.source&&u.action===i.action&&(u.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),dt(n))}function Vt(e){return e&&H()[e]?.connectionStatus||null}function Qe(e,t,n={}){if(!e)return;n.profileInfo?Ge(e,n.profileInfo):H()[e]||Ge(e,{});let o=H(),r=o[e];r&&(r.connectionStatus=t,r.connectionDate=je(),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),dt(o))}function Jt(){return oe||(Ye(),oe=Oe(Pt,"quota.json"),(!oe||!oe.connections)&&(oe={connections:[]}),oe)}function oo(e){Ye(),oe=e;try{_e(Pt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Ht(e,t="unknown"){let n=Jt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),oo(n)}function Wt(){let e=Jt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Fe(){let e=Wt(),t=je(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Te,i=o>=Ne,a=!r&&!i,u={allowed:a,daily:{sent:n,max:Te},weekly:{sent:o,max:Ne}};return a||(u.reason=r?`Daily limit reached (${n}/${Te})`:`Weekly limit reached (${o}/${Ne})`),u}function ye(){let e=Wt(),t=je(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Te,remaining:Te-n},weekly:{sent:o,max:Ne,remaining:Ne-o}}}var Jn,Hn,re,ct,Zr,Pt,es,ts,ns,ut,Te,Ne,xe,Wn,oe,Gn,Yn,Qn,Kn,zn,Le=ne(async()=>{await at();Jn=Vn(import.meta.url),Hn=B.dirname(B.dirname(Jn)),re=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Hn,"collected-profiles"),ct=B.join(re,"people.json"),Zr=B.join(re,"jobs.json"),Pt=B.join(re,"quota.json"),es=B.join(re,"conversations.json"),ts=B.join(re,"sync-state.json"),ns=B.join(re,"application-questions.json"),ut=B.join(re,"profile-history"),Te=20,Ne=100,xe=null,Wn=null,oe=null,Gn=null,Yn=null,Qn=null;Kn=["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"],zn=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var cn={};ce(cn,{cookiesExist:()=>nr,getCookiesPath:()=>et,loadCookies:()=>tr,saveCookies:()=>er});import Ee from"fs";import an from"path";function et(){let e=process.env.ILML_SCOPE_DIR;return e?an.join(e,"plugins-state","linkedin","cookies.json"):Xo}function Zo(){let e=et(),t=an.dirname(e);return t&&t!=="."&&!Ee.existsSync(t)&&Ee.mkdirSync(t,{recursive:!0}),e}function er(e){let t=Zo();return Ee.writeFileSync(t,JSON.stringify(e)),t}function tr(){let e=et();if(!Ee.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Ee.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 nr(){return Ee.existsSync(et())}var Xo,un=ne(()=>{Xo="cookies.json"});var dn={};ce(dn,{cleanSearchName:()=>ar,delayed:()=>S,dismissPremiumOverlay:()=>me,ensureInboxPage:()=>ir,parseLinkedInTime:()=>sr,safeParseInt:()=>lr,stripDesignations:()=>cr,utilityFunction:()=>or});function or(){console.log("Utility function called...")}function qe(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),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function sr(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 u=qe(n),s=new Date(t);return u?s.setHours(u.hours,u.minutes,0,0):s.setHours(0,0,0,0),s.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let u=rr[o[1].toLowerCase()],s=qe(o[2]||""),l=new Date(t),d=l.getDay()-u;return d<=0&&(d+=7),l.setDate(l.getDate()-d),s?l.setHours(s.hours,s.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let u=$t[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(r[2],10),l=parseInt(r[3],10),c=qe(r[4]||"");return new Date(l,u,s,c?.hours||0,c?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let u=$t[i[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(i[2],10),l=qe(i[3]||""),c=t.getFullYear(),d=new Date(c,u,s,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}let a=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(a){let u=$t[a[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(a[2],10),l=qe(a[3]||""),c=t.getFullYear(),d=new Date(c,u,s,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}return null}async function S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ir(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");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 S(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function lr(e){return parseInt(e,10)||0}async function me(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),a=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),u=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||a||u){let s=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:r.substring(0,80)};let l=o.querySelectorAll("button");for(let c of l){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function ar(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 cr(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 $t,rr,tt=ne(()=>{$t={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},rr={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var fn={};ce(fn,{extractCertificationsFromDetails:()=>mr,extractEducationFromDetails:()=>fr,extractExperienceFromDetails:()=>ur,extractFeaturedFromDetails:()=>dr,extractRecommendationsFromDetails:()=>hr,extractSkillsFromDetails:()=>pr});async function ur(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)r++,await S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function a(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(h=>h.tagName==="DIV");if(p.length<3)continue;let g=p.filter(h=>(h.textContent||"").trim().length>50);g.length<3||(f.textContent||"").length<500||d.push({el:f,count:g.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let u=a(i);if(!u)return[];let s=Array.from(u.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function l(c){let d=c[0]||null,f=null,p=null;if(c[1]){let $=c[1].split("\xB7").map(_=>_.trim());f=$[0]||null,$[1]&&(p=$[1])}let g=c.findIndex($=>/(\d{4}|present)/i.test($)&&/(-|–|—)/i.test($)&&$.length<80),h=null,w=null;if(g>=0){let $=c[g].split("\xB7").map(_=>_.trim());h=$[0]||null,$[1]&&(w=$[1])}let m=null,y=-1;if(g>=0&&c[g+1]){let $=c[g+1],_=/^[>*\-•]|^&gt;/.test($),O=/https?:\/\//.test($),I=/\d{4}/.test($),q=/,/.test($)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test($);!_&&!O&&!I&&$.length<100&&q&&(m=$,y=g+1)}let k=null,C=-1,v=c[c.length-1];if(v&&/and\s+\+\d+\s+skills?$/i.test(v)){C=c.length-1;let $=v.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);$&&(k={listed:$[1].split(",").map(_=>_.trim()),additional:parseInt($[2],10)})}let T=new Set([0,1,g,y,C].filter($=>$>=0)),A=c.filter(($,_)=>!T.has(_)),U=A.length>0?A.join(`
2
+
3
+ `):null;return{title:d,company:f,employmentType:p,dates:h,duration:w,location:m,description:U,skills:k,_raw:c}}return s.map(c=>{let f=(c.innerText||"").trim().split(`
4
+ `).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return l(f)}).filter(c=>c.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Be(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let a=0;a<4;a++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);await S(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let u of document.querySelectorAll("button"))if(/^Load more$/i.test((u.textContent||"").trim()))return u.click(),!0;return!1});)i++,await S(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(600)}async function Ve(e,t,n,o){try{return await o()}catch(r){let i=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw r;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 dr(e,t){return Ve(t,"featured","extractFeaturedFromDetails",async()=>(await Be(e,t,"featured"),await e.evaluate(`(() => {
5
+ ${Ue}
6
+
7
+ const main = document.querySelector('main');
8
+ if (!main) return [];
9
+ const container = findEntryContainer(main);
10
+ if (!container) return [];
11
+
12
+ const entries = Array.from(container.children)
13
+ .filter(c => c.tagName === 'DIV')
14
+ .filter(c => (c.textContent || '').trim().length > 30);
15
+
16
+ return entries.map(entry => {
17
+ const raw = (entry.innerText || '').trim();
18
+ const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 2000);
19
+
20
+ // External link from any anchor inside the card (filter LinkedIn-internal)
21
+ const anchors = Array.from(entry.querySelectorAll('a[href]'));
22
+ const externalAnchor = anchors.find(a => {
23
+ const h = a.href || '';
24
+ return h.startsWith('http') &&
25
+ !h.includes('linkedin.com/in/') &&
26
+ !h.includes('linkedin.com/posts/') &&
27
+ !h.includes('#');
28
+ });
29
+ const url = externalAnchor?.href || anchors[0]?.href || null;
30
+
31
+ const title = lines[0] || null;
32
+ const caption = lines[1] && lines[1] !== title ? lines[1] : null;
33
+
34
+ return { title, caption, url, _raw: lines };
35
+ }).filter(e => {
36
+ if (!e.title) return false;
37
+ // Reject "People You May Know" sidebar cards: signature is
38
+ // exactly [title, "View"] with no url/caption beyond "View".
39
+ if (e._raw.length === 2 && e._raw[1] === 'View') return false;
40
+ // Reject "Other profiles you may know" widget cards: caption is
41
+ // just a connection-degree marker (e.g. "\xB7 3rd", "\xB7 2nd").
42
+ if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
43
+ return true;
44
+ });
45
+ })()`)))}async function fr(e,t){return Ve(t,"education","extractEducationFromDetails",async()=>(await Be(e,t,"education"),await e.evaluate(`(() => {
46
+ ${Ue}
47
+
48
+ const main = document.querySelector('main');
49
+ if (!main) return [];
50
+ const container = findEntryContainer(main);
51
+ if (!container) return [];
52
+
53
+ const entries = Array.from(container.children)
54
+ .filter(c => c.tagName === 'DIV')
55
+ .filter(c => (c.textContent || '').trim().length > 30);
56
+
57
+ return entries.map(entry => {
58
+ const raw = (entry.innerText || '').trim();
59
+ const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 5000);
60
+
61
+ const school = lines[0] || null;
62
+ const degree = lines[1] || null;
63
+ const dates = lines.find(l =>
64
+ /(\\d{4})/.test(l) &&
65
+ /(-|\u2013|\u2014)/i.test(l) &&
66
+ l.length < 80
67
+ ) || null;
68
+ const used = new Set([0, 1, dates ? lines.indexOf(dates) : -1].filter(i => i >= 0));
69
+ const descLines = lines.filter((_, i) => !used.has(i));
70
+ const description = descLines.length > 0 ? descLines.join(' / ') : null;
71
+
72
+ return { school, degree, dates, description, _raw: lines };
73
+ }).filter(e => {
74
+ if (!e.school) return false;
75
+ // Reject "People You May Know" sidebar cards: [title, "View"].
76
+ if (e._raw.length === 2 && e._raw[1] === 'View') return false;
77
+ // Reject related-profile widget: "degree" parsed as the
78
+ // connection-degree marker ("\xB7 3rd") instead of a real degree.
79
+ if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
80
+ return true;
81
+ });
82
+ })()`)))}async function pr(e,t){return Ve(t,"skills","extractSkillsFromDetails",async()=>(await Be(e,t,"skills"),await e.evaluate(`(() => {
83
+ ${Ue}
84
+
85
+ const main = document.querySelector('main');
86
+ if (!main) return [];
87
+ const container = findEntryContainer(main);
88
+ if (!container) return [];
89
+
90
+ const entries = Array.from(container.children)
91
+ .filter(c => c.tagName === 'DIV')
92
+ .filter(c => (c.textContent || '').trim().length > 1);
93
+
94
+ const seen = new Set();
95
+ const skills = [];
96
+ for (const entry of entries) {
97
+ const raw = (entry.innerText || '').trim();
98
+ const lines = raw.split('\\n').map(l => l.trim()).filter(Boolean);
99
+ if (lines.length === 0) continue;
100
+
101
+ const name = lines[0];
102
+ if (!name || name.length > 100 || seen.has(name.toLowerCase())) continue;
103
+ seen.add(name.toLowerCase());
104
+
105
+ let endorsements = null;
106
+ for (const l of lines.slice(1)) {
107
+ const m = l.match(/(\\d+)\\s+endorsement/i);
108
+ if (m) { endorsements = parseInt(m[1], 10); break; }
109
+ }
110
+
111
+ skills.push({ name, endorsements, _raw: lines });
112
+ }
113
+ return skills;
114
+ })()`)))}async function mr(e,t){return Ve(t,"certifications","extractCertificationsFromDetails",async()=>(await Be(e,t,"certifications"),await e.evaluate(`(() => {
115
+ ${Ue}
116
+
117
+ const main = document.querySelector('main');
118
+ if (!main) return [];
119
+ const container = findEntryContainer(main);
120
+ if (!container) return [];
121
+
122
+ const entries = Array.from(container.children)
123
+ .filter(c => c.tagName === 'DIV')
124
+ .filter(c => (c.textContent || '').trim().length > 20);
125
+
126
+ return entries.map(entry => {
127
+ const raw = (entry.innerText || '').trim();
128
+ const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 2000);
129
+
130
+ const name = lines[0] || null;
131
+ const issuer = lines[1] || null;
132
+ const issueDate = lines.find(l => /^Issued\\b/i.test(l)) || null;
133
+ const expiryDate = lines.find(l => /Expir(es|ed)\\b/i.test(l)) || null;
134
+ const credentialId = (lines.find(l => /credential id/i.test(l)) || '')
135
+ .replace(/^.*credential id[:\\s]*/i, '').trim() || null;
136
+
137
+ return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
138
+ }).filter(e => e.name);
139
+ })()`)))}async function hr(e,t){return Ve(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Be(e,t,"recommendations"),await e.evaluate(`(() => {
140
+ ${Ue}
141
+
142
+ const main = document.querySelector('main');
143
+ if (!main) return [];
144
+ const container = findEntryContainer(main);
145
+ if (!container) return [];
146
+
147
+ const entries = Array.from(container.children)
148
+ .filter(c => c.tagName === 'DIV')
149
+ .filter(c => (c.textContent || '').trim().length > 50);
150
+
151
+ return entries.map(entry => {
152
+ const raw = (entry.innerText || '').trim();
153
+ const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 5000);
154
+
155
+ const recommender = lines[0] || null;
156
+ const recommenderTitle = lines[1] || null;
157
+ const relationship = lines.find(l =>
158
+ /\\b(was |worked |reported |managed |taught |studied )\\b/i.test(l) &&
159
+ l.length < 200
160
+ ) || null;
161
+ const date = lines.find(l => /(January|February|March|April|May|June|July|August|September|October|November|December)\\s+\\d{1,2}.*\\d{4}/i.test(l)) || null;
162
+ // Recommendation text is the longest non-meta line
163
+ const text = [...lines].sort((a, b) => b.length - a.length)[0] || '';
164
+
165
+ return { recommender, recommenderTitle, relationship, date, text, _raw: lines };
166
+ }).filter(e => {
167
+ if (!e.recommender || !e.text) return false;
168
+ // Reject "People You May Know" sidebar cards: [title, "View"].
169
+ if (e._raw.length === 2 && e._raw[1] === 'View') return false;
170
+ // Reject related-profile widget: recommenderTitle is the
171
+ // connection-degree marker, not a real job title.
172
+ if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
173
+ return true;
174
+ });
175
+ })()`)))}var Ue,pn=ne(()=>{tt();Ue=`
176
+ function findEntryContainer(root) {
177
+ const candidates = [];
178
+ for (const div of root.querySelectorAll('div')) {
179
+ const directDivs = Array.from(div.children).filter(c => c.tagName === 'DIV');
180
+ if (directDivs.length < 2) continue;
181
+ const substantial = directDivs.filter(c => (c.textContent || '').trim().length > 30);
182
+ if (substantial.length < 2) continue;
183
+ if ((div.textContent || '').length < 200) continue;
184
+
185
+ // Reject "People You May Know" suggestion containers: every substantial
186
+ // child is exactly [title, "View"] (a tiny suggestion card with a single
187
+ // "View" CTA). Real section entries always have richer per-child content
188
+ // (multiple text lines per entry).
189
+ const allLookLikePYMK = substantial.every(c => {
190
+ const lines = (c.innerText || '').trim().split('\\n').map(l => l.trim()).filter(Boolean);
191
+ return lines.length === 2 && lines[1] === 'View';
192
+ });
193
+ if (allLookLikePYMK) continue;
194
+
195
+ // Reject "Other profiles you may know" / related-profile widget:
196
+ // LinkedIn shows this when /details/<section>/ has no real data
197
+ // (e.g. profile has no Featured at all). Every entry is a short
198
+ // [name, "\xB7 Nth"] card with a connection-degree marker as the only
199
+ // metadata. Real Featured / Education / Recommendations entries
200
+ // NEVER consist solely of name + degree.
201
+ const DEGREE_RE = /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i;
202
+ const allLookLikeRelatedProfiles = substantial.every(c => {
203
+ const lines = (c.innerText || '').trim().split('\\n').map(l => l.trim()).filter(Boolean);
204
+ if (lines.length > 4) return false;
205
+ return lines.some(l => DEGREE_RE.test(l));
206
+ });
207
+ if (allLookLikeRelatedProfiles) continue;
208
+
209
+ // Reject LinkedIn footer/legal blocks: when a /details/<section>/ page
210
+ // renders empty, LinkedIn falls back to "Questions? Visit our Help
211
+ // Center", "Select language" (35+ languages), "Recommendation
212
+ // transparency" and similar nav cards inside <main>. These are unique
213
+ // marker strings that never appear inside real section entries.
214
+ const containerText = div.textContent || '';
215
+ const FOOTER_MARKERS = [
216
+ 'Visit our Help Center',
217
+ 'Select language',
218
+ 'Recommendation transparency',
219
+ 'Manage your account and privacy',
220
+ 'Go to your Settings',
221
+ 'Who your viewers also viewed', // "Private to you" PYMK block on empty pages
222
+ 'People also viewed',
223
+ 'People you may know',
224
+ 'More profiles for you', // LinkedIn related-profiles widget shown
225
+ 'Other profiles you may know', // when /details/<section>/ is empty
226
+ ];
227
+ if (FOOTER_MARKERS.some(m => containerText.includes(m))) continue;
228
+
229
+ candidates.push({ el: div, count: substantial.length, totalText: (div.textContent || '').length });
230
+ }
231
+ // Sort: most children first, then RICHER children (larger totalText) \u2014 real
232
+ // section entries dominate via content density, not just child count. The
233
+ // previous "smaller totalText wins" tie-break gave PYMK sidebars priority
234
+ // over the real Education / Recommendations lists.
235
+ candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
236
+ return candidates[0]?.el;
237
+ }
238
+ `});var gn={};ce(gn,{clickConnectButton:()=>xt,default:()=>wr,detectConnectionStatus:()=>$e,findConnectButton:()=>Je,runFunnel:()=>hn,sendConnectionRequest:()=>Et,shouldExcludeLocation:()=>nt,viewProfile:()=>Ct});async function mn(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function nt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Ct(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:a=!1,extractRecommendations:u=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await me(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await mn(e,t));let c=0;for(let k=0;k<2;k++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await e.evaluate(A=>window.scrollTo(0,A),C*T/6),await S(900);let v=await e.evaluate(()=>document.body.scrollHeight);if(v===c)break;c=v}await S(800);let d=await e.evaluate(()=>{let k=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"]),C=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"]),v=x=>{let E=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(E)},T={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:[]},A=document.querySelector("main");if(!A)return T;let U=[...Array.from(A.querySelectorAll("h1")),...Array.from(A.querySelectorAll("h2"))],$=Array.from(A.querySelectorAll("h2")),_=U.find(x=>{let E=x.textContent&&x.textContent.trim(),D=(E||"").replace(/\s*\(\d+\)$/,"").trim();return E&&E.length>1&&E.length<100&&!k.has(D)&&!C.has(D)}),O=_?_.textContent.trim():null,I=_?_.parentElement:null;for(;I&&I!==A&&!Array.from(I.children).filter(E=>E.tagName==="P").some(E=>{let D=E.textContent&&E.textContent.trim();return D&&D.length>5&&!v(D)});)I=I.parentElement;let q=null,V=null,X=null,Ce=null;if(I&&I!==A){let x=Array.from(I.children).filter(D=>D.tagName==="P").filter(D=>{let ae=D.textContent&&D.textContent.trim();return ae&&ae.length>5&&!v(ae)});if(x[0]&&(q=x[0].textContent.trim()),x[1]){let D=x[1].textContent.trim().split(/\s*[·•]\s*/);V=D[0]||null,D.length>1&&(X=D.slice(1).join(" \xB7 "))}let E=Array.from(I.children).filter(D=>D.tagName==="DIV");for(let D=E.length-1;D>=0;D--){let ae=E[D].textContent&&E[D].textContent.trim();if(ae&&!(O&&ae.startsWith(O))&&(Ce=ae.split(/[·•]/)[0].trim(),Ce))break}}let He=null;if(I){let x=I.querySelectorAll("p, span, div");for(let E of x){let D=(E.textContent||"").trim().replace(/^[·•]\s*/,"");if(D==="1st"||D==="2nd"||D==="3rd"){He=D;break}}}let it=!!A.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),N=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),L=N&&N.src||null,M=A.textContent||"",P=null,Z=M.match(/(\d+\+?)\s+connections\b/i);Z&&(P=Z[1]+" connections");let We=null,Rt=M.match(/(\d+)\s+mutual connection/i),Tt=M.match(/and\s+(\d+)\s+other mutual/i),jn=M.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Rt?We=parseInt(Rt[1],10):Tt?We=2+parseInt(Tt[1],10):jn&&(We=2);let Nt=null,_t=null,Ot=$.find(x=>x.textContent&&x.textContent.trim()==="About");if(Ot){let x=Ot.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let E=(x.textContent||"").trim();E=E.replace(/^About\s*/,"").trim();let D=E.match(/Top skills\s*(.+?)$/i);if(D){let lt=D[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Pn=>Pn.trim()).filter(Boolean);lt.length>0&&lt.length<10&&(_t=lt)}E=E.split(/\n?…\s*more/i)[0].trim(),E=E.split(/\n?\.\.\.\s*more/i)[0].trim(),E=E.split(/\bTop skills\b/i)[0].trim(),E=E.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Nt=E||null}}let jt=null,Ft=$.find(x=>x.textContent&&x.textContent.trim()==="Activity");if(Ft){let x=Ft.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let E=(x.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);E&&(jt=parseInt(E[1].replace(/,/g,""),10))}}let Fn=[...new Set($.map(x=>(x.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(x=>x&&x.length>1&&x.length<60&&x!==O).filter(x=>k.has(x)))],Re=document.body.textContent||"",Ln=/#OpenToWork\b/i.test(Re)||/\bOpen to work\b/.test(Re),Mn=/#Hiring\b/i.test(Re)||/\bI'?m hiring\b/i.test(Re)||/\bWe are hiring\b/i.test(Re);return{name:O,title:q,location:Ce,currentCompany:V,currentSchool:X,connectionDegree:He,hasVerifiedBadge:it,photoUrl:L,connectionsLevel:P,mutualConnectionsCount:We,followers:jt,openToWork:Ln,hiring:Mn,about:Nt,topSkills:_t,availableSections:Fn}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,g=null,h=null,w=null,m=null;if(o||r||i||a||u||s){let k=await Promise.resolve().then(()=>(pn(),fn));o&&(f=await k.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(p=await k.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(g=await k.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),a&&(h=await k.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),u&&(w=await k.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.length} entries`)),s&&(m=await k.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${m.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...g!==null&&{education:g},...h!==null&&{skillsFull:h},...w!==null&&{recommendations:w},...m!==null&&{certifications:m}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function $e(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(s=>s.getAttribute("aria-label")),r=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),a={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!r,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:a}:r&&!i?{status:"connected",debug:a}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:a}:{status:"not_connected",debug:a}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Je(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let l=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(l&&(s=l.textContent?.trim(),s&&!s.includes("notification")))return s;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p=null,g=null;for(let h of d){let w=h.getBoundingClientRect();if(w.width===0||w.height===0)continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=h;break}g||(g=h)}return p||g||null},n);let l=t?.asElement?.()||null;if(l||await t?.dispose?.().catch(()=>{}),l)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:l,method:"connect_link"}}if(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let l=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(h=>{let w=h.getAttribute("aria-label")||"";return(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&f.test(w)}).map(h=>h.getAttribute("aria-label")?.slice(0,50))},s);l.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(l)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of f){let h=g.getAttribute("aria-label")||"";if((h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&p.test(h))return g}return null},s);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,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 s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),l=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(l)&&(console.log(` Skipping primary button: wrong person (${s})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of o){let l=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),g=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(c.getAttribute("aria-label")||"").toLowerCase(),w=h.includes("invite"),m=d?h.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:g,hasInvite:w,matchesName:m,ariaLabel:h}},s,r);if(!l.isMuted&&!l.isStickyHeader&&!l.inRecommendations){if(l.hasInvite&&!l.matchesName){console.log(` Skipping secondary button: wrong person (${l.ariaLabel})`);continue}i=s;break}}for(let s of o)s!==i&&await s.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 a=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let s of u){let l=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},s);if(l.isVisible&&!l.isInStickyHeader){a=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of u)s!==a&&await s.dispose().catch(()=>{});if(!a&&u.length>0&&(a=u[u.length-1],console.log(" Found More button by ID pattern (last)")),a||(a=await e.$('button[aria-label="More actions"]'),a&&console.log(" Found More button by aria-label")),!a){let s=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),g=f.getAttribute("aria-label")||"",h=f.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});a=s?.asElement?.()||null,a||await s?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),a),await S(500),await e.evaluate(c=>c.click(),a),await S(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let l=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(l||(l=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),l||(l=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),l||(l=await e.$('div[role="button"][aria-label*="Invite"]')),l||(l=await e.$('div[role="button"][aria-label*="connect"]')),!l){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let g of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});l=c?.asElement?.()||null,l||await c?.dispose?.().catch(()=>{})}if(!l){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let g of p.querySelectorAll('[role="menuitem"], a, div')){let h=g.innerText?.trim();h&&h.length<40&&f.push(h)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(l)return console.log(" Found: More dropdown"),{button:l,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),l=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(l)&&(console.log(` Skipping generic button: wrong person (${s})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function xt(e,t){await e.evaluate(l=>l.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let n=await e.evaluate(l=>({tag:l.tagName,ariaLabel:l.getAttribute("aria-label"),href:l.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV";if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(c=>c.click(),t)]),await S(2e3);let l=e.url();if(l.includes("premium")||l.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await S(2e3),"premium_redirect"}else i?(await e.evaluate(l=>l.click(),t),await S(3e3)):(await e.evaluate(l=>l.click(),t),await S(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let u=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),s=e.url();return console.log(u?` \u2713 Connect sent \u2014 ${s}`:` \u26A0 No modal after connect click \u2014 ${s}`),"success"}async function gr(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await S(1500);let n=await Je(e);if(n){await e.evaluate(r=>r.click(),n),await S(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Et(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let u=Fe();if(!u.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${u.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:u.reason,profileInfo:null}}let a=await yr(e,t,n);return a.connectionSent&&!i&&Ht(t,o),a}async function yr(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:a=!0,excludeLocations:u=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
239
+ --- Connecting: ${l} ---`),u.length>0){let m=H()[t]?.location;if(nt(m,u))return console.log(` \u26A0 Excluded location (stored): ${m}`),s.reason="excluded_location",s.profileInfo={location:m},s}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),await me(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await mn(e,t),await S(2e3)),s.profileInfo=await e.evaluate(()=>{let m=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"]),y=N=>{let L=(N||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},k={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},C=document.querySelector("main");if(!C)return k;let v=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],T=Array.from(C.querySelectorAll("h2")),A=v.find(N=>{let L=N.textContent&&N.textContent.trim();return L&&L.length>1&&L.length<100&&!m.has(L)&&L!=="0 notifications"}),U=A?A.textContent.trim():null,$=A?A.parentElement:null;for(;$&&$!==C&&!Array.from($.children).filter(M=>M.tagName==="P").some(M=>{let P=M.textContent&&M.textContent.trim();return P&&P.length>5&&!y(P)});)$=$.parentElement;let _=null,O=null,I=null;if($&&$!==C){let N=Array.from($.children),L=N.filter(P=>P.tagName==="P").filter(P=>{let Z=P.textContent&&P.textContent.trim();return Z&&Z.length>5&&!y(Z)});L[0]&&(_=L[0].textContent.trim()),L[1]&&(O=L[1].textContent.trim());let M=N.filter(P=>P.tagName==="DIV");for(let P=M.length-1;P>=0;P--){let Z=M[P].textContent&&M[P].textContent.trim();if(Z&&!(U&&Z.startsWith(U))&&(I=Z.split(/[·•]/)[0].trim(),I))break}}let q=null;if($){let N=$.querySelectorAll("p, span, div");for(let L of N){let M=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){q=M;break}}}let V=null,X=T.find(N=>N.textContent&&N.textContent.trim()==="About");if(X){let N=X.parentElement;for(;N&&N.tagName!=="SECTION";)N=N.parentElement;N&&(V=(N.textContent||"").trim().replace(/^About\s*/,"").trim()||null,V&&(V=V.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Ce=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),He=Ce&&Ce.src||null,it=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:U,title:_,location:I,about:V,company:O,connectionDegree:q,connectionsCount:null,mutualConnections:null,photoUrl:He,hasVerifiedBadge:it}}),u.length>0){let m=s.profileInfo?.location,y=H()[t]?.location,k=m||y;if(nt(k,u))return console.log(` \u26A0 Excluded location (${m?"live":"stored"}): ${k}`),s.reason="excluded_location",s;!m&&y==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await $e(e);if(d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await me(e);let f=await Je(e);if(!f&&(await me(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),f=await Je(e)),!f))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;if(s.method=f.method,await xt(e,f.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let m=await $e(e);if(m==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${m} \u2014 trying More dropdown...`),await me(e),await S(1e3);let y=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(y)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),y),await S(500),await y.click().catch(()=>e.evaluate(C=>C.click(),y)),await S(2e3);let k=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(k){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(T=>T.click(),k),await S(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),s.reason="premium_required",s;if(await $e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await S(500),s.reason="premium_required",s}catch(k){return console.log(" More dropdown failed:",k.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let m=await e.$('button[aria-label="Dismiss"]');return m&&await m.click(),await S(500),s.reason="email_required",s}let h=await e.$('button[aria-label="Add a note"]'),w=await e.$('button[aria-label="Send without a note"]');if(!h&&!w){let m=await e.evaluate(()=>{let y=document.querySelector("#interop-outlet")?.shadowRoot;if(!y)return{addNote:!1,sendWithout:!1};let k=y.querySelector('button[aria-label="Add a note"]'),C=y.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!C}});if(m.addNote){let y=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=y?.asElement?.()||null,h||await y.dispose().catch(()=>{})}if(m.sendWithout){let y=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));w=y?.asElement?.()||null,w||await y.dispose().catch(()=>{})}}if(r){if(h&&o){if(console.log(" Adding personalized note..."),await h.click(),await S(1500),await e.$("div.modal-upsell")){let k=await gr(e);return s.success=k,s.connectionSent=k,s.reason=k?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let y=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(y){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",k);await y.type(C,{delay:20}),await S(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v){try{await v.evaluate(T=>T.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=C,s}}}else if(w){console.log(" Sending without note...");try{await w.evaluate(m=>m.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(h&&!o){console.log(" No message provided, sending without note...");let m=await e.$('button[aria-label="Send without a note"]');if(m){try{await m.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let m=w;if(m){try{await m.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3)),await me(e),await S(500);let y=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let C of y){let v=await e.evaluate(T=>{let A=T.getBoundingClientRect();return{visible:A.width>0&&A.height>0,inSticky:!!T.closest('.sticky-header, [class*="sticky"]')}},C);if(v.visible&&!v.inSticky){k=C;break}}!k&&y.length>0&&(k=y[y.length-1]);for(let C of y)C!==k&&await C.dispose().catch(()=>{});if(k)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),k),await S(500),await k.click().catch(()=>e.evaluate(v=>v.click(),k)),await S(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(C){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(U=>U.click(),C),await S(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 S(3e3),await $e(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await $e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let A=await e.$('button[aria-label="Send without a note"]');if(A){console.log(" Modal appeared via More dropdown, sending without note...");try{await A.evaluate(U=>U.click())}catch{}return await S(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(l){console.error(` \u2717 Error: ${l.message}`),s.reason="error",s.error=l.message;let c=l.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{s.fatal=!0}return s}}async function hn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:a=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:s=null,excludeLocations:l=[],source:c="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
240
+ === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${a?"View Only":`Connect (max ${i})`}`),a||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!a){let p=ye();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let f=0;for(let p=0;p<t.length;p++){let g=t[p];try{if(e.isClosed()){console.log(`
241
+ \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
242
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=Vt(g.profileUrl);if(h==="pending"||h==="connected"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${h})`),h==="pending"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,s&&await s(g,d,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl}`);let w=null;if(a){let m=await Ct(e,g.profileUrl);m?(Ge(g.profileUrl,{...m,source:c}),d.viewed++,w={success:!0,reason:"viewed",connectionSent:!1,profileInfo:m}):(d.errors++,w={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let m=Fe();if(!m.allowed){console.log(` \u26A0 Global quota exhausted: ${m.reason}`);break}if(w=await Et(e,g.profileUrl,{message:o,useCustomMessage:r,excludeLocations:l,source:c,skipQuotaGate:!0}),w.success)d.connectionsSent++;else switch(w.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(w?.fatal){console.log(`
243
+ \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(w?.reason==="error"){if(f++,f>=3){console.log(`
244
+ \u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(w&&w.reason&&(Qe(g.profileUrl,w.reason,{method:w.method,messageSent:w.messageSent,profileInfo:w.profileInfo}),Ut(g.profileUrl,{source:c||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:w.reason})),s&&await s(g,d,w),p<t.length-1){let m=u+Math.random()*2e3;await S(m)}}if(console.log(`
245
+ === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!a){let p=ye();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}var wr,yn=ne(async()=>{tt();await Le();wr={viewProfile:Ct,detectConnectionStatus:$e,findConnectButton:Je,clickConnectButton:xt,sendConnectionRequest:Et,runFunnel:hn,shouldExcludeLocation:nt}});import{createGraphClient as Sr,resolveToken as br}from"@ilivemylife/graph-sdk";import{config as kr}from"dotenv";var wn,Sn,bn=ne(()=>{kr();wn=br()||process.env.TOKEN;wn||(console.error(`
246
+ [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.
247
+ `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
248
+ `),console.error(` Or add ILML_TOKEN=... to .env
249
+ `),process.exit(1));Sn=Sr({token:wn})});import"dotenv/config";function vr(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 $r({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",a=new Date().toISOString().slice(0,16).replace("T"," "),u=r?` ${vr(r)}`:"",s=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 ${s} \u2014 ${a}${u}`}async function kn({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let a=process.env.NODE_RUN_REPORTS;if(!a||!Array.isArray(o)||o.length===0)return;let s=`**${$r({scriptName:e,mode:t,status:n,error:r,duration:i})}**
250
+
251
+ ${o.join(`
252
+ `)}`;try{await Sn.addMessage(a,s)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var vn=ne(()=>{bn()});var En={};ce(En,{endRun:()=>Dr,formatScriptStatus:()=>Nr,getLastRun:()=>Tr,getRunHistory:()=>Rr,getTodayRunSummary:()=>Cn,startRun:()=>Ir,timeAgo:()=>xn});import"dotenv/config";import*as z from"fs";import*as he from"path";import{fileURLToPath as Cr}from"url";function Ar(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";z.writeFileSync(o,n);for(let r=0;r<3;r++)try{z.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw i}}function Ae(){try{if(!z.existsSync(It))return{runs:[]};let e=JSON.parse(z.readFileSync(It,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function $n(e){z.existsSync(At)||z.mkdirSync(At,{recursive:!0});try{Ar(It,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ir(e,t="default"){let n=Ae();for(let a of n.runs)a.status==="running"&&(a.status="interrupted",a.result="interrupted",a.timestamp&&(a.duration=Date.now()-new Date(a.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(a=>new Date(a.timestamp).getTime()>i),$n(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Dr(e,t,n=null,o=null){if(!e)return;let r=null;try{let a=Ae(),u=a.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=n,u.error=o,r=u.duration;else{let s=a.runs.find(l=>l.script===e.script&&l.status==="running"&&l.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=o,r=s.duration)}$n(a)}catch(a){console.error(`[runLog] Failed to end run: ${a.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let a=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";kn({scriptName:e.script,mode:e.mode,status:a,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}function Rr(e=7){let t=Ae(),n=Date.now()-e*24*60*60*1e3;return t.runs.filter(o=>new Date(o.timestamp).getTime()>n).sort((o,r)=>r.timestamp.localeCompare(o.timestamp))}function Tr(e=null){let t=Ae(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function Cn(){let e=new Date().toISOString().slice(0,10),t=Ae(),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 r=n[o.script];r.total++,o.status==="success"?r.success++:o.status==="error"?r.error++:o.status==="interrupted"?r.interrupted++:o.status==="partial"?r.partial++:o.status==="running"&&r.running++,r.lastRun=o}return n}function xn(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),r=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:r===1?"yesterday":`${r} days ago`}function Nr(){let e=["sync-all","messages","funnel","sync","apply"],t=Ae(),n=Cn(),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 a=t.runs.filter(h=>h.script===i),u=[...a].reverse().find(h=>h.status==="success"),s=a[a.length-1],l=u||s,c=l?xn(l.timestamp):"never",f=(l?Math.floor((Date.now()-new Date(l.timestamp).getTime())/864e5):1/0)>1?" \u26A0":l?.status==="error"?" \u2717":" \u2713",p="";if(l?.stats){let h=l.stats,w=Object.entries(h).filter(([,m])=>typeof m=="number"&&m>0).slice(0,3).map(([m,y])=>`${y} ${m}`);w.length&&(p=` (${w.join(", ")})`)}let g=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${c.padEnd(16)}${g}${p}${f}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[i,a]of r){let u=[];a.success&&u.push(`${a.success} success`),a.error&&u.push(`${a.error} error`),a.interrupted&&u.push(`${a.interrupted} interrupted`),a.running&&u.push(`${a.running} running`),o.push(` Today: ${i} \xD7${a.total} (${u.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(`
253
+ `)}var xr,Er,At,It,An=ne(()=>{vn();xr=Cr(import.meta.url),Er=he.dirname(he.dirname(xr)),At=process.env.DATA_DIR?he.resolve(process.env.DATA_DIR,"collected-profiles"):he.join(Er,"collected-profiles"),It=he.join(At,"run-log.json")});await at();await Le();import"dotenv/config";import*as Ke from"fs";import*as ue from"path";import{fileURLToPath as ro}from"url";var so=ro(import.meta.url),io=ue.dirname(ue.dirname(so)),ft=process.env.DATA_DIR?ue.resolve(process.env.DATA_DIR,"collected-profiles"):ue.join(io,"collected-profiles"),Yt=ue.join(ft,"connect-queue.json"),lo=1,we=300,ze=["queued","approved","sent","skipped","failed"],de=["high","normal","low"],Gt={high:0,normal:1,low:2};function ao(){Ke.existsSync(ft)||Ke.mkdirSync(ft,{recursive:!0})}function pt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=we?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:de.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:ze.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function ee(){let e=Oe(Yt,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(pt).filter(n=>n.url):[]}function fe(e){ao(),_e(Yt,{version:lo,entries:e.map(pt)})}function se(e){return W(e)||(e||"").trim().toLowerCase()}function Me(e,t){let n=se(t);return e.find(o=>se(o.url)===n)||null}function mt(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:i=()=>!1,nowIso:a}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},s=new Set(e.map(l=>se(l.url)));for(let l of t){let c=l?.url;if(!c){u.skippedNoUrl++;continue}let d=se(c);if(s.has(d)){u.skippedDup++;continue}if(i(c)){u.skippedEngaged++;continue}let f=typeof l.note=="string"?l.note.trim():"";f.length>we&&u.notesTooLong++;let p=f.length>0&&f.length<=we;e.push(pt({url:c,tag:l.tag||o,priority:l.priority||r,withNote:p,note:p?f:null,status:"queued",addedAt:a||null})),s.add(d),u.added++}return u}function Qt(e){return[...e].sort((t,n)=>{let o=(Gt[t.priority]??1)-(Gt[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function Se(e,t){return e.filter(n=>n.status===t)}await Le();import"dotenv/config";import*as b from"fs";import*as kt from"os";import*as R from"path";import{fileURLToPath as jo}from"url";var yt={};ce(yt,{NAME:()=>uo,VERSION:()=>co,up:()=>mo});import*as Y from"fs";import*as Xe from"path";var co=1,uo="normalize-jobs-and-questions",fo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],po=50;function ht(e){return Y.existsSync(e)?JSON.parse(Y.readFileSync(e,"utf-8")):null}function gt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function mo(e,t){let n=Xe.join(e,"jobs.json"),o=Xe.join(t,"scouted-jobs.json"),r=Xe.join(e,"application-questions.json"),i=ht(n)||{},a=ht(o)||{},u=0,s=[];for(let c of Object.keys(i)){if(!a[c])continue;let d=a[c],f=i[c];for(let p of fo)d[p]!=null&&f[p]==null&&(f[p]=d[p]);s.push(c),u++}u>0?(gt(n,i),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=ht(r);if(l&&Array.isArray(l.applications)){let c={},d=0;for(let f of l.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let g=(f.questions||[]).map(h=>{let w={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=po?w.options=h.options:(w.optionsOmitted=!0,d++)),h.page&&(w.page=h.page),h.wasPreFilled&&(w.wasPreFilled=!0),h.wasRetry&&(w.wasRetry=!0),w});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||g.length,questions:g})}gt(r,c),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} 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(s.length>0){for(let c of s)delete a[c];gt(o,a),console.log(` Phase 3: Removed ${s.length} merged entries from scouted-jobs.json (${Object.keys(a).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var wt={};ce(wt,{NAME:()=>go,VERSION:()=>ho,up:()=>So});import*as Q from"fs";import*as Kt from"path";var ho=2,go="reset-unread-flags";function yo(e){return Q.existsSync(e)?JSON.parse(Q.readFileSync(e,"utf-8")):null}function wo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Q.writeFileSync(o,n)}catch(r){try{Q.unlinkSync(o)}catch{}throw r}try{Q.renameSync(o,e)}catch(r){try{Q.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function So(e){let t=Kt.join(e,"conversations.json"),n=yo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}wo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var St={};ce(St,{NAME:()=>ko,VERSION:()=>bo,up:()=>Eo});import*as K from"fs";import*as zt from"path";var bo=3,ko="recompute-last-message-by",vo=new Set(["draft","confirmed","rejected","needs_review"]);function $o(e){return K.existsSync(e)?JSON.parse(K.readFileSync(e,"utf-8")):null}function Co(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{K.writeFileSync(o,n)}catch(r){try{K.unlinkSync(o)}catch{}throw r}try{K.renameSync(o,e)}catch(r){try{K.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function xo(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!vo.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,a)=>a.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let a=i.sender;if(a===t)return"me";if(a!=="Unknown"&&a!=="")return"them"}return"them"}async function Eo(e){let t=zt.join(e,"conversations.json"),n=$o(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,a=0;for(let u of Object.keys(n)){let s=n[u];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let l=Array.isArray(s.messages)?s.messages:[],c=xo(l,o),d=c==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==c&&a++,s.lastMessageBy=c,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}Co(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${a} 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.")}await Le();import"dotenv/config";import*as G from"path";import{fileURLToPath as Ao}from"url";var Io=Ao(import.meta.url),Do=G.dirname(G.dirname(Io)),Pe=process.env.DATA_DIR?G.resolve(process.env.DATA_DIR,"market-research"):G.join(Do,"market-research"),ds=G.join(Pe,"scouted-jobs.json"),fs=G.join(Pe,"discovered-people.json"),ps=G.join(Pe,"visit-log.json"),ms=G.join(Pe,"companies.json"),hs=G.join(Pe,"job-decisions.json");function Xt(){Ro=null,To=null,No=null,_o=null,Oo=null}var Ro=null;var To=null;var No=null;var _o=null;var Oo=null;var Fo=jo(import.meta.url),Lo=R.dirname(Fo),Mo=R.dirname(R.dirname(Lo));function Po(e){return e&&(e==="~"?kt.homedir():e.startsWith("~/")||e.startsWith("~\\")?R.join(kt.homedir(),e.slice(2)):e)}var te=process.env.DATA_DIR?R.resolve(Po(process.env.DATA_DIR)):Mo,ke=R.join(te,"collected-profiles"),ve=R.join(te,"market-research"),J=R.join(te,".schema-version"),Zt=[R.join(ke,".schema-version"),R.join(ve,".schema-version")],pe=3,ie=[{version:1,module:yt},{version:2,module:wt},{version:3,module:St}];(function(){ie.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ie){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ie.length?ie[ie.length-1].version:0;if(n!==pe)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${pe}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ie.length;o++){let r=o+1;if(ie[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ie[o].version}`)}})();function on(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
254
+ [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
255
+ `),process.exit(1));try{b.mkdirSync(te,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
256
+ [FATAL] Cannot create DATA_DIR (${te}): ${t.message}`),console.error(` Fix the path or permissions and try again.
257
+ `),process.exit(1))}let e;try{e=b.statSync(te)}catch(t){console.error(`
258
+ [FATAL] DATA_DIR (${te}) is not accessible: ${t.message}
259
+ `),process.exit(1)}e.isDirectory()||(console.error(`
260
+ [FATAL] DATA_DIR (${te}) 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.
261
+ `),process.exit(1));for(let t of[ke,ve]){let n;try{n=b.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
262
+ [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.
263
+ `),process.exit(1))}}var be=R.join(te,".migration-lock");function qo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return b.writeFileSync(be,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(b.readFileSync(be,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(a){a.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let a=Date.parse(t.startedAt);Number.isNaN(a)||(i=Date.now()-a)}o&&i<r&&(console.error(`
264
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${be}
265
+ `),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.
266
+ `),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=be+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,be),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function vt(){try{if(JSON.parse(b.readFileSync(be,"utf-8")).pid!==process.pid)return;b.unlinkSync(be)}catch{}}var en=!1;function Bo(){if(en)return;en=!0;let e=()=>{try{vt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Uo(){if(b.existsSync(J))return;let e=[],t=[];for(let i of Zt)if(b.existsSync(i))try{e.push({file:i,schema:Ze(i)})}catch(a){t.push({file:i,err:a.message})}if(t.length>0){console.error(`
267
+ [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(`
268
+ 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.
269
+ `),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
270
+ [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.
271
+ `),process.exit(1)}let o=e[0].schema,r=J+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,J)}catch(i){try{b.unlinkSync(r)}catch{}throw i}for(let i of Zt)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${J}`)}function Vo(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 Ze(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function tn(){if(Uo(),!b.existsSync(J))return{version:0,migrations:[]};let e;try{e=Ze(J)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
272
+ [FATAL] ${J} 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.
273
+ `),process.exit(1)}let t=Vo(e);return t===null&&(console.error(`
274
+ [FATAL] ${J} 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.
275
+ `),process.exit(1)),t}function rn(e){try{b.chmodSync(e,384)}catch{}}function Jo(e){if(on(),b.existsSync(J))try{if(b.lstatSync(J).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${J}. 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=J+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),rn(t),b.renameSync(t,J)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function nn(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(u=>{let s=u.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return b.statSync(R.join(e,u)).isFile()}catch{return!1}}),r=0,i=0,a=[];for(let u of o){let s=R.join(e,u),l=R.join(e,u+n);if(b.existsSync(l)){i++;continue}try{ln(s,l),r++}catch(c){a.push({file:u,err:c.message})}}if(a.length>0){let u=new Error(`Failed to back up ${a.length} file(s) in ${R.basename(e)}/: `+a.map(s=>`${s.file} (${s.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||i>0){let u=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${R.basename(e)}/ (${n})${u}`)}}var bt=!1;async function sn(){if(bt)return;on(),Qo();let t=tn().version;if(t===pe){bt=!0;return}Bo(),qo(),process.on("exit",vt),t>pe&&(console.error(`
276
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${pe}.`),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.
277
+ `),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${pe}.
278
+ `),process.exit(1)),console.log(`
279
+ \u{1F4E6} Schema migration: v${t} \u2192 v${pe}`);let n=Ko();if(!n.ok){console.error(`
280
+ [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
281
+ 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'.
282
+ `),process.exit(1)}let o=ie.filter(r=>r.version>t);for(let r of o){console.log(`
283
+ Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,a=`.pre-${i}.backup`;try{nn(ke,r.version),nn(ve,r.version)}catch(s){console.error(`
284
+ [FATAL] Pre-migration backup failed for ${i}: ${s.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
285
+ `),process.exit(1)}let u=r.module;try{await u.up(ke,ve)}catch(s){console.error(`
286
+ [FATAL] Migration ${i} failed: ${s.message}`),console.error(` Attempting auto-rollback from ${a} files...`);try{let l=zo(a);l.ok?(console.error(` \u2713 Auto-rollback restored ${l.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
287
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${l.error}`),console.error(` Manual recovery: copy *${a} files back over the originals.
288
+ `))}catch(l){console.error(` [!] Auto-rollback CRASHED while restoring: ${l.message}`),console.error(` Manual recovery: copy *${a} files back over the originals.
289
+ `)}process.exit(1)}try{let s=new Date().toISOString(),l={version:r.version,name:u.NAME||i,appliedAt:s},c=tn();c.version=r.version,c.migratedAt=s,c.migrations=c.migrations||[],c.migrations.push(l),Jo(c)}catch(s){console.error(`
290
+ [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${s.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
291
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{qt()}catch{}try{Xt()}catch{}bt=!0,vt(),console.log(`
292
+ \u2713 Schema is now at v${pe}
293
+ `)}var Ho=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Wo(e){let t=e.toLowerCase();return Ho.some(n=>n.test(t))}var Go=6e4;function Yo(){let e=Date.now(),t=[];for(let n of[te,ke,ve]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!Wo(r))continue;let i=R.join(n,r);try{let a=b.statSync(i);if(!a.isFile()||e-a.mtimeMs<Go)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function Qo({verbose:e=!1}={}){let t=Yo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{b.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${R.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Ko(){let e=[];for(let t of[ke,ve]){if(!b.existsSync(t))continue;let n=b.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=R.join(t,o);try{Ze(r)}catch(i){e.push({dir:R.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function zo(e){let t=[],n=[];for(let i of[ke,ve]){if(!b.existsSync(i))continue;let a=b.readdirSync(i).filter(u=>u.endsWith(e));for(let u of a){let s=R.join(i,u),l=u.slice(0,-e.length),c=R.join(i,l);try{l.toLowerCase().endsWith(".json")?Ze(s):b.accessSync(s,b.constants.R_OK),t.push({backupPath:s,originalPath:c,fileName:u,dir:i})}catch(d){n.push(`${R.basename(i)}/${u}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:a,fileName:u,dir:s}of t)try{ln(i,a),o++}catch(l){r.push(`${R.basename(s)}/${u}: ${l.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function ln(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),rn(n)}catch(o){try{b.unlinkSync(n)}catch{}throw o}try{b.renameSync(n,t)}catch(o){try{b.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}var Rn=new Set(["connected"]),Tn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),In=new Set(["pending","connected","excluded_location","email_required","premium_required"]),Ie=process.argv.slice(2),Nn=Ie[0],De=Ie.filter(e=>!e.startsWith("--")),rt=e=>Ie.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),le=e=>{let t=Ie.find(o=>o===`--${e}`||o.startsWith(`--${e}=`));if(t===void 0)return;let n=t.indexOf("=");return n===-1&&F(`--${e} needs a value \u2014 write --${e}=value (no space).`),t.slice(n+1)},Dt=()=>new Date().toISOString();function st(){let e=H(),t=new Map;for(let[n,o]of Object.entries(e)){let r=W(o.profileUrl||n);r&&t.set(r,o)}return t}function _n(e,t){let n=e.get(W(t));return n?Rn.has(n.connectionStatus)||Tn.has(n.connectionStatus):!1}async function _r(){let e=De[1];if(!e)return F("Usage: connect add <file.json> [--tag=X] [--priority=high]");let t;try{t=JSON.parse((await import("fs")).readFileSync(e,"utf-8"))}catch(l){return F(`Could not read/parse ${e}: ${l.message}`)}if(!Array.isArray(t))return F("File must be a JSON array of { url, note?, name? }.");let n=le("tag")||"untagged",o=le("priority");if(o&&!de.includes(o))return F(`--priority must be one of: ${de.join(", ")}`);let r=o||"normal",i=ee(),a=st(),u=mt(i,t,{tag:n,priority:r,nowIso:Dt(),alreadyEngaged:l=>_n(a,l)});fe(i),console.log(`
294
+ Added ${u.added} to queue (tag=${n}, priority=${r}).`),u.skippedDup&&console.log(` ${u.skippedDup} already in queue \u2014 skipped.`),u.skippedEngaged&&console.log(` ${u.skippedEngaged} already connected/pending \u2014 skipped.`),u.skippedNoUrl&&console.log(` ${u.skippedNoUrl} had no url \u2014 skipped.`),u.notesTooLong&&console.log(` ${u.notesTooLong} had notes over ${we} chars \u2014 added WITHOUT a note (LinkedIn's limit); set a shorter one with \`connect note\`.`);let s=i.filter(l=>l.status==="queued"&&l.withNote).length;console.log(`
295
+ Queue now: ${Se(i,"queued").length} queued, ${Se(i,"approved").length} approved.`),s&&console.log(` ${s} queued entries carry a custom note (scarce \u2014 review with \`connect list\`).`),console.log(`Next: review with \`connect list\`, approve with \`connect approve --tag=${n}\`, send with \`connect run\`.`)}var Dn=["founder","investor","hiring_manager","peer"];function Or(){let e=le("category");if(e===void 0&&rt("valuable")&&(e=Dn.join(",")),!e)return F(`Usage: connect fill --category=founder,investor,hiring_manager[,peer,recruiter] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
296
+ (shortcut: --valuable = ${Dn.join(",")})`);let t=e.split(",").map(m=>m.trim()).filter(Boolean),n=m=>{let y=le(m);if(y===void 0)return;let k=parseInt(y,10);return!Number.isInteger(k)||k<0?F(`--${m} must be a non-negative integer.`):k},o=n("min-posts")??0,r=n("max"),i=le("priority");if(i&&!de.includes(i))return F(`--priority must be one of: ${de.join(", ")}`);let a=le("tag"),u=(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map(m=>m.trim().toLowerCase()).filter(Boolean),s=m=>{if(!m)return!1;let y=String(m).toLowerCase();return u.some(k=>y.includes(k))},l=H(),c=[],d=0;for(let[m,y]of Object.entries(l))if(t.includes(y.category)&&!(Rn.has(y.connectionStatus)||Tn.has(y.connectionStatus))&&y.connectionDegree!=="1st"&&!((y.jobIds?.length||0)<o)){if(s(y.location)){d++;continue}c.push({url:y.profileUrl||m,p:y})}let f={high:0,medium:1,low:2};c.sort((m,y)=>(f[m.p.personPriority]??1)-(f[y.p.personPriority]??1)||(y.p.mutualConnections||0)-(m.p.mutualConnections||0)||(y.p.jobIds?.length||0)-(m.p.jobIds?.length||0)),r!==void 0&&(c=c.slice(0,r));let p=c.map(m=>({url:m.url,tag:a||m.p.category,priority:i||(m.p.personPriority==="high"?"high":"normal")})),g=ee(),h=st(),w=mt(g,p,{alreadyEngaged:m=>_n(h,m),nowIso:Dt()});fe(g),console.log(`
297
+ Filled ${w.added} from [${t.join(", ")}]${o?` (\u2265${o} job-posts)`:""}.`),w.skippedDup&&console.log(` ${w.skippedDup} already in queue \u2014 skipped.`),w.skippedEngaged&&console.log(` ${w.skippedEngaged} already connected/pending \u2014 skipped.`),d&&console.log(` ${d} in excluded locations \u2014 skipped.`),console.log(`
298
+ Queue now: ${Se(g,"queued").length} queued, ${Se(g,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function jr(){let e=ee();if(!e.length)return console.log("\nQueue is empty. Add people with `connect add <file.json>`.");let t=le("status"),n=st(),o=ye();console.log(`
299
+ === Connect Queue === (quota left: ${o.daily.remaining}/${o.daily.max} today, ${o.weekly.remaining}/${o.weekly.max} week)
300
+ `);let r={};for(let l of e)r[l.status]=(r[l.status]||0)+1;console.log("Status: "+Object.entries(r).map(([l,c])=>`${l}=${c}`).join(" ")+`
301
+ `),t&&!ze.includes(t)&&console.log(`(unknown status "${t}" \u2014 valid: ${ze.join(", ")})
302
+ `);let i=t?e.filter(l=>l.status===t):e,a={approved:0,queued:1,failed:2,skipped:3,sent:4},u=[...i].sort((l,c)=>(a[l.status]??9)-(a[c.status]??9));for(let l of u){let c=n.get(W(l.url)),d=c&&c.name||"",f=c&&c.title?` \xB7 ${c.title.slice(0,40)}`:"",p=c&&c.mutualConnections?` \xB7 ${c.mutualConnections} mutual`:"",g=l.withNote?"\u{1F4DD}":" ",h=l.priority==="high"?"\u2B06high ":l.priority==="low"?"\u2B07low ":"normal";console.log(` [${l.status.padEnd(8)}] ${h} ${g} ${d}${f}${p}`),console.log(` ${l.url} (tag=${l.tag})`)}let s=e.filter(l=>(l.status==="queued"||l.status==="approved")&&l.withNote).length;s&&console.log(`
303
+ ${s} pending entries will use a custom note (LinkedIn limits these \u2014 spend deliberately).`),console.log("")}function ot(e,t,n,o){let r=ee(),i=0;for(let a of r)e(a)&&t.includes(a.status)&&(a.status=n,i++);return fe(r),console.log(`
304
+ ${o}: ${i} entr${i===1?"y":"ies"} \u2192 ${n}.`),i}function Fr(){let e=["queued","failed"];if(rt("all"))return ot(()=>!0,e,"approved","Approved");let t=le("tag");if(t)return ot(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=De[1];if(!n)return F("Usage: connect approve <url> | --all | --tag=X");let o=se(n);return ot(r=>se(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function Lr(){let e=De[1];if(!e)return F("Usage: connect skip <url>");let t=se(e);return ot(n=>se(n.url)===t,["queued","approved"],"skipped","Skipped")}function Mr(){let e=Ie[1],t=Ie[2];if(!e||t===void 0)return F('Usage: connect note <url> "custom note text"');let n=t.trim();if(!n)return F("Note is empty \u2014 use `connect no-note <url>` to remove a note.");if(n.length>we)return F(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${we}. Shorten it.`);let o=ee(),r=Me(o,e);if(!r)return F("Not in queue.");r.note=n,r.withNote=!0,fe(o),console.log(`
305
+ Note set (${n.length} chars) \u2014 this entry will send WITH a note. Notes are limited, use sparingly.`)}function Pr(){let e=De[1];if(!e)return F("Usage: connect no-note <url>");let t=ee(),n=Me(t,e);if(!n)return F("Not in queue.");n.note=null,n.withNote=!1,fe(t),console.log(`
306
+ Note cleared \u2014 this entry will send WITHOUT a note (note budget freed).`)}function qr(){let e=De[1],t=De[2];if(!e||!de.includes(t))return F(`Usage: connect priority <url> <${de.join("|")}>`);let n=ee(),o=Me(n,e);if(!o)return F("Not in queue.");o.priority=t,fe(n),console.log(`
307
+ Priority set to ${t}.`)}async function Br(){let e=rt("dry-run"),t=rt("yes"),n=le("max"),o=1/0;if(n!==void 0){let v=parseInt(n,10);if(!Number.isInteger(v)||v<0)return F("--max must be a non-negative integer.");o=v}let r=ye(),i=Math.min(r.daily.remaining,r.weekly.remaining),a=ee(),u=Qt(Se(a,"approved"));if(!u.length){let v=Se(a,"queued").length;console.log(`
308
+ Nothing approved to send.`),v&&console.log(` ${v} queued \u2014 approve them first: \`connect approve --all\` (or --tag=X).`);return}if(i<=0){console.log(`
309
+ Connection quota is used up (${r.daily.remaining}/${r.daily.max} today, ${r.weekly.remaining}/${r.weekly.max} week). Try again later.`);return}let s=u.slice(0,Math.min(o,i));if(!s.length){console.log(`
310
+ Nothing to send (--max=${o===1/0?"\u221E":o}).`);return}let l=s.filter(v=>v.withNote).length;console.log(`
311
+ === Connect run ===`),console.log(` Approved: ${u.length} \xB7 quota left: ${i} \xB7 sending: ${s.length}${l?` (${l} with a note)`:""}`);let c=st();if(s.forEach((v,T)=>{let A=c.get(W(v.url));console.log(` ${T+1}. ${v.withNote?"\u{1F4DD}":" "} ${A?.name||v.url} (${v.priority}, tag=${v.tag})`)}),e){console.log(`
312
+ [dry-run] Nothing sent. Drop --dry-run to send.`);return}t||(console.log(`
313
+ Press Enter to send, or Ctrl+C to cancel...`),await new Promise(v=>process.stdin.once("data",()=>v())));let d=(await import("puppeteer")).default,{loadCookies:f}=await Promise.resolve().then(()=>(un(),cn)),{sendConnectionRequest:p}=await yn().then(()=>gn),{delayed:g}=await Promise.resolve().then(()=>(tt(),dn)),{startRun:h,endRun:w}=await Promise.resolve().then(()=>(An(),En)),m=h("connect","run"),y,k;try{y=await d.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),k=await y.newPage(),await k.setCookie(...f())}catch(v){console.error(`
314
+ [!] ${v.message}
315
+ `);try{y&&await y.close()}catch{}try{w(m,"error",null,v.message)}catch{}process.exit(1)}let C=0;try{let v=H(),T=new Map;for(let[O,I]of Object.entries(v)){let q=W(I.profileUrl||O);q&&T.set(q,O)}let A=0,U=0,$=0;for(let O of s){if(!Fe().allowed){console.log(" Quota reached mid-run \u2014 stopping.");break}let I=await p(k,O.url,{message:O.withNote?O.note:null,useCustomMessage:O.withNote,source:O.tag,skipQuotaGate:!0}),q;if(I.connectionSent?(q="sent",A++):In.has(I.reason)?(q="skipped",U++):(q="failed",$++),I.connectionSent||In.has(I.reason)){let V=T.get(W(O.url))||O.url;try{Qe(V,I.reason,{method:I.method,messageSent:I.messageSent,profileInfo:I.profileInfo})}catch{}}try{let V=ee(),X=Me(V,O.url);X&&(X.status=q,q==="sent"&&(X.sentAt=Dt()),X.result=I.reason||I.error||q,fe(V))}catch(V){console.error(` \u26A0 Could not persist queue update for ${O.url}: ${V.message}`)}await g(3e3+Math.random()*2e3)}let _=ye();console.log(`
316
+ === Done: ${A} sent, ${U} skipped, ${$} failed ===`),console.log(`Connection quota left: ${_.daily.remaining}/${_.daily.max} today, ${_.weekly.remaining}/${_.weekly.max} week.`);try{w(m,"success",{sent:A,skipped:U,failed:$})}catch{}}catch(v){console.error(`
317
+ [!] Run aborted: ${v.message}`);try{w(m,"error",null,v.message)}catch{}C=1}finally{try{await y.close()}catch{}}process.exit(C)}function F(e){console.error(e),process.exit(1)}function Ur(){console.log(`connect \u2014 connect queue
318
+
319
+ connect add <file.json> [--tag=X] [--priority=high|normal|low]
320
+ connect fill --category=founder,investor,... [--valuable] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
321
+ connect list [--status=queued|approved|sent|skipped|failed]
322
+ connect approve <url> | --all | --tag=X
323
+ connect note <url> "custom note" connect no-note <url>
324
+ connect skip <url> connect priority <url> <high|normal|low>
325
+ connect run [--max=N] [--dry-run] [--yes]`)}var Vr={add:_r,fill:Or,list:jr,approve:Fr,skip:Lr,note:Mr,"no-note":Pr,priority:qr,run:Br},On=Vr[Nn];On||(Ur(),process.exit(Nn?1:0));await sn();await On();